Source Code
Latest 25 from a total of 478 transactions
| Transaction Hash |
Method
|
Block
|
From
|
|
To
|
||||
|---|---|---|---|---|---|---|---|---|---|
| Claim | 24528526 | 27 secs ago | IN | 0 ETH | 0.00030916 | ||||
| Claim | 24528464 | 13 mins ago | IN | 0 ETH | 0.00001246 | ||||
| Claim | 24528371 | 31 mins ago | IN | 0 ETH | 0.00021632 | ||||
| Claim | 24527878 | 2 hrs ago | IN | 0 ETH | 0.00009622 | ||||
| Claim | 24523867 | 15 hrs ago | IN | 0 ETH | 0.00021017 | ||||
| Claim | 24522127 | 21 hrs ago | IN | 0 ETH | 0.00031749 | ||||
| Claim | 24521717 | 22 hrs ago | IN | 0 ETH | 0.00024671 | ||||
| Claim | 24521708 | 22 hrs ago | IN | 0 ETH | 0.00024615 | ||||
| Claim | 24521702 | 22 hrs ago | IN | 0 ETH | 0.00024563 | ||||
| Claim | 24521695 | 22 hrs ago | IN | 0 ETH | 0.00024644 | ||||
| Claim | 24521686 | 22 hrs ago | IN | 0 ETH | 0.00024588 | ||||
| Claim | 24520820 | 25 hrs ago | IN | 0 ETH | 0.00001328 | ||||
| Claim | 24519767 | 29 hrs ago | IN | 0 ETH | 0.00024527 | ||||
| Claim | 24518685 | 32 hrs ago | IN | 0 ETH | 0.00000429 | ||||
| Claim | 24514901 | 45 hrs ago | IN | 0 ETH | 0.00026821 | ||||
| Claim | 24514816 | 45 hrs ago | IN | 0 ETH | 0.00000457 | ||||
| Claim | 24514811 | 45 hrs ago | IN | 0 ETH | 0.00000573 | ||||
| Claim | 24514801 | 45 hrs ago | IN | 0 ETH | 0.00000524 | ||||
| Claim | 24514506 | 46 hrs ago | IN | 0 ETH | 0.00001776 | ||||
| Claim | 24514498 | 46 hrs ago | IN | 0 ETH | 0.00002145 | ||||
| Claim | 24514487 | 46 hrs ago | IN | 0 ETH | 0.00003464 | ||||
| Claim | 24514457 | 47 hrs ago | IN | 0 ETH | 0.00001895 | ||||
| Claim | 24514429 | 47 hrs ago | IN | 0 ETH | 0.00001734 | ||||
| Claim | 24512875 | 2 days ago | IN | 0 ETH | 0.0000094 | ||||
| Claim | 24511290 | 2 days ago | IN | 0 ETH | 0.00000741 |
Latest 1 internal transaction
Advanced mode:
| Parent Transaction Hash | Method | Block |
From
|
|
To
|
||
|---|---|---|---|---|---|---|---|
| 0x61010060 | 23541314 | 138 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0xC3973DA4...658990D0f The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
BUILDClaim
Compiler Version
v0.8.26+commit.8a97fa7a
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IBUILDClaim} from "./interfaces/IBUILDClaim.sol";
import {IBUILDFactory} from "./interfaces/IBUILDFactory.sol";
import {ITypeAndVersion} from "chainlink/contracts/src/v0.8/shared/interfaces/ITypeAndVersion.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {BUILDFactory} from "./BUILDFactory.sol";
import {Closable} from "./Closable.sol";
import {UnlockState, getUnlockState} from "./Unlockable.sol";
import {FixedPointMathLib} from "@solady/FixedPointMathLib.sol";
import {IDelegateRegistry} from "@delegatexyz/delegate-registry/v2.0/src/IDelegateRegistry.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract BUILDClaim is IBUILDClaim, ITypeAndVersion, ReentrancyGuard {
using SafeERC20 for IERC20;
using FixedPointMathLib for uint256;
/// @inheritdoc ITypeAndVersion
string public constant override typeAndVersion = "BUILDClaim 1.0.0";
/// @notice The claimed and early claimed states for a user per season
mapping(address user => mapping(uint256 seasonId => UserState)) private s_userStates;
/// @notice The global states for a season
mapping(uint256 seasonId => GlobalState globalState) private s_globalStates;
/// @notice The project token
IERC20 private immutable i_token;
/// @notice The factory that deployed this contract
BUILDFactory private immutable i_factory;
/// @notice The delegate registry contract address
address private immutable i_delegateRegistry;
/// @notice The Multicall3 contract address
address private immutable i_multicall3;
/// @notice The basis points denominator for percentages
uint256 private constant PERCENTAGE_BASIS_POINTS_DENOMINATOR = 10_000;
// ================================================================
// | Initialization |
// ================================================================
/// @notice constructor
/// @param token The project token
/// @param delegateRegistry The address of the Delegate Registry contract
/// @param multicall3 The address of the Multicall3 contract
constructor(address token, address delegateRegistry, address multicall3) {
i_token = IERC20(token);
i_factory = BUILDFactory(msg.sender);
i_delegateRegistry = delegateRegistry;
i_multicall3 = multicall3;
}
/// @inheritdoc IBUILDClaim
function getFactory() external view override returns (BUILDFactory) {
return i_factory;
}
/// @inheritdoc IBUILDClaim
function getToken() external view override returns (IERC20) {
return i_token;
}
/// @inheritdoc IERC165
function supportsInterface(
bytes4 interfaceId
) external pure override returns (bool) {
return interfaceId == type(IBUILDClaim).interfaceId || interfaceId == type(IERC165).interfaceId;
}
// ================================================================
// | Token Deposits |
// ================================================================
/// @inheritdoc IBUILDClaim
function deposit(
uint256 amount
) external override nonReentrant whenClaimNotPaused onlyProjectAdmin {
// only callable when factory contract is open
if (!i_factory.isOpen()) {
revert Closable.AlreadyClosed();
}
uint256 balanceBefore = i_token.balanceOf(address(this));
uint256 totalDeposited = i_factory.addTotalDeposited(address(i_token), amount);
i_token.safeTransferFrom(msg.sender, address(this), amount);
uint256 balanceAfter = i_token.balanceOf(address(this));
if (balanceBefore + amount != balanceAfter) {
revert InvalidDeposit(balanceBefore, balanceAfter);
}
emit Deposited(address(i_token), msg.sender, amount, totalDeposited);
}
// ================================================================
// | Token Withdrawals |
// ================================================================
/// @inheritdoc IBUILDClaim
function withdraw() external override nonReentrant onlyProjectAdmin {
(IBUILDFactory.Withdrawal memory withdrawal, uint256 totalWithdrawn) =
i_factory.executeWithdraw(address(i_token));
i_token.safeTransfer(withdrawal.recipient, withdrawal.amount);
emit Withdrawn(address(i_token), withdrawal.recipient, withdrawal.amount, totalWithdrawn);
}
// ================================================================
// | Token Claims |
// ================================================================
/// @inheritdoc IBUILDClaim
function claim(
address user,
ClaimParams[] calldata params
) external override nonReentrant whenClaimNotPaused {
_claim(user, params);
}
/// @inheritdoc IBUILDClaim
function getGlobalState(
uint256[] calldata seasonIds
) external view returns (GlobalState[] memory) {
uint256 count = seasonIds.length;
GlobalState[] memory states = new GlobalState[](count);
for (uint256 i; i < count; ++i) {
states[i] = s_globalStates[seasonIds[i]];
}
return states;
}
/// @inheritdoc IBUILDClaim
function getUserState(
UserSeasonId[] calldata usersAndSeasonIds
) external view returns (UserState[] memory) {
uint256 count = usersAndSeasonIds.length;
UserState[] memory states = new UserState[](count);
for (uint256 i; i < count; ++i) {
states[i] = s_userStates[usersAndSeasonIds[i].user][usersAndSeasonIds[i].seasonId];
}
return states;
}
/// @inheritdoc IBUILDClaim
function getCurrentClaimValues(
address user,
SeasonIdAndMaxTokenAmount[] calldata seasonIdsAndMaxTokenAmounts
) external view returns (ClaimableState[] memory) {
uint256 count = seasonIdsAndMaxTokenAmounts.length;
ClaimableState[] memory claimableStates = new ClaimableState[](count);
for (uint256 i; i < count; ++i) {
uint256 seasonId = seasonIdsAndMaxTokenAmounts[i].seasonId;
(IBUILDFactory.ProjectSeasonConfig memory config, uint256 unlockStartsAt) =
i_factory.getProjectSeasonConfig(address(i_token), seasonId);
UnlockState memory unlockState =
getUnlockState(unlockStartsAt, config.unlockDelay, config.unlockDuration, block.timestamp);
claimableStates[i] = _getClaimableState(
config,
s_globalStates[seasonId],
s_userStates[user][seasonId],
unlockState,
seasonIdsAndMaxTokenAmounts[i].maxTokenAmount
);
}
return claimableStates;
}
/// @notice Validates if the user is eligible to claim the amount of tokens for a season
/// A merkle tree's leaf consists of a user address, their max token amount for the season and a
/// salt
/// @param root The merkle root of a season
/// @param user The user's address
/// @param proof The merkle proof of the user's address, max token amount and salt
/// @param maxTokenAmount The user's total claimable token amount for the season
/// @param isEarlyClaim Whether the user is claiming early
/// @param salt A randomly generated salt to prevent brute-force guessing of merkle proofs
/// @return bool Returns true if the user's proof, maxTokenAmount and salt are valid
function _verifyMerkleProof(
bytes32 root,
address user,
bytes32[] memory proof,
uint256 maxTokenAmount,
bool isEarlyClaim,
uint256 salt
) private pure returns (bool) {
bytes32 leaf =
keccak256(bytes.concat(keccak256(abi.encode(user, maxTokenAmount, isEarlyClaim, salt))));
return MerkleProof.verify(proof, root, leaf);
}
/// @notice Calculates the amount of tokens that can be claimed by a user for a season
/// without requiring an early claim at a particular timestamp.
/// This amount is the sum of the base tokens amount that is released all at once after the
/// unlock delay and the unlocked amount that is released linearly over the unlock duration.
/// This does not factor in any claimed amounts
/// @param config The project season config
/// @param globalState The global state for the season
/// @param userState The user state for the season
/// @param unlockState The unlock state for the season
/// @param maxTokenAmount The maximum token amount for the user
/// @return ClaimableState The amount of tokens that can be claimed
function _getClaimableState(
IBUILDFactory.ProjectSeasonConfig memory config,
IBUILDClaim.GlobalState memory globalState,
UserState memory userState,
UnlockState memory unlockState,
uint256 maxTokenAmount
) internal pure returns (ClaimableState memory) {
ClaimableState memory claimableState;
claimableState.base =
(maxTokenAmount * config.baseTokenClaimBps) / PERCENTAGE_BASIS_POINTS_DENOMINATOR;
claimableState.bonus = maxTokenAmount - claimableState.base;
if (config.tokenAmount == 0 || (config.isRefunding && userState.claimed == 0)) {
return claimableState;
}
claimableState.claimed = userState.claimed;
if (userState.hasEarlyClaimed || unlockState.isBeforeUnlock) return claimableState;
// calculate share of loyalty pool to receive
// The loyalty bonus is informative only in the unlock period, as it is not
// claimable until the vesting is completed.
claimableState.loyaltyBonus = maxTokenAmount * globalState.totalLoyalty
/ (config.tokenAmount - globalState.totalLoyaltyIneligible);
if (unlockState.isUnlocking) {
// unlock period is in progress
// At this point, it's guaranteed that config.unlockDuration > 0
claimableState.vested =
(claimableState.bonus * unlockState.unlockElapsedDuration) / config.unlockDuration;
claimableState.claimable =
claimableState.base + claimableState.vested - claimableState.claimed;
claimableState.earlyVestableBonus =
_calcEarlyVestableBonus(claimableState, config, unlockState.unlockElapsedDuration);
} else {
// unlock completed
claimableState.claimable =
maxTokenAmount + claimableState.loyaltyBonus - claimableState.claimed;
}
return claimableState;
}
/// @notice Calculates the amount of bonus tokens that can be claimed early
/// @param claimableState The claimable state for the user
/// @param config The project season config
/// @param timeElapsed The amount of time that has elapsed since the unlock started
/// @return uint256 The amount of bonus tokens that can be claimed early
/// @dev This function is not called when config.unlockDuration == 0, since that would set
/// unlockState.isUnlocking to false
function _calcEarlyVestableBonus(
ClaimableState memory claimableState,
IBUILDFactory.ProjectSeasonConfig memory config,
uint256 timeElapsed
) private pure returns (uint256) {
return FixedPointMathLib.mulWad(
claimableState.bonus - claimableState.vested,
FixedPointMathLib.divWad(config.earlyVestRatioMinBps, PERCENTAGE_BASIS_POINTS_DENOMINATOR)
+ (
FixedPointMathLib.divWad(
config.earlyVestRatioMaxBps - config.earlyVestRatioMinBps,
PERCENTAGE_BASIS_POINTS_DENOMINATOR
) * timeElapsed
) / config.unlockDuration
);
}
/// @notice Validates the claim parameters for a user
/// @param user The user address
/// @param userState The user state for the season
/// @param param The claim parameters for a user
/// @param config The project season config
/// @param unlockStartsAt The timestamp when the unlock period starts
/// @param unlockState The unlock state for the season
/// @dev Reverts if the claim parameters are invalid
/// @dev Reverts if the unlock period has not started yet, including the configured unlock delay
/// @dev Reverts if the project season does not exist for the given token address
/// @dev Reverts if the user's proof is invalid
/// @dev Reverts if user attempts to earlyClaim after previously early claiming during the unlock
/// period
function _validateClaimParams(
address user,
UserState memory userState,
ClaimParams memory param,
IBUILDFactory.ProjectSeasonConfig memory config,
uint256 unlockStartsAt,
UnlockState memory unlockState
) private view {
if (user == address(0)) {
revert InvalidUser(user);
}
if (unlockStartsAt == 0) {
revert IBUILDFactory.SeasonDoesNotExist(param.seasonId);
}
if (unlockState.isBeforeUnlock) {
revert UnlockNotStarted(param.seasonId);
}
if (config.tokenAmount == 0) {
revert IBUILDFactory.ProjectSeasonDoesNotExist(param.seasonId, address(i_token));
}
if (
!_verifyMerkleProof(
config.merkleRoot, user, param.proof, param.maxTokenAmount, param.isEarlyClaim, param.salt
)
) {
revert InvalidMerkleProof();
}
if (unlockState.isUnlocking && param.isEarlyClaim && userState.hasEarlyClaimed) {
revert InvalidEarlyClaim(user, param.seasonId);
}
if (userState.claimed == 0 && config.isRefunding) {
// If the user hasn't claimed for this season before the refunding starts, the user will
// be refunded their allocated credits but can no longer claim tokens
revert IBUILDFactory.ProjectSeasonIsRefunding(address(i_token), param.seasonId);
}
}
/// @notice Util function that claims tokens for a user for multiple seasons
/// @param user The user address
/// @param params An array of claim params including the season ID, proof, and max token amount
/// for each season
function _claim(address user, ClaimParams[] memory params) private {
uint256 totalClaimableAmount;
bool isEarlyClaim = false;
// Cache array length outside loop
uint256 paramsLength = params.length;
for (uint256 i = 0; i < paramsLength; ++i) {
ClaimParams memory param = params[i];
if (param.isEarlyClaim) {
isEarlyClaim = true;
}
(IBUILDFactory.ProjectSeasonConfig memory config, uint256 unlockStartsAt) =
i_factory.getProjectSeasonConfig(address(i_token), param.seasonId);
UserState memory userState = s_userStates[user][param.seasonId];
UnlockState memory unlockState =
getUnlockState(unlockStartsAt, config.unlockDelay, config.unlockDuration, block.timestamp);
_validateClaimParams(user, userState, param, config, unlockStartsAt, unlockState);
if (userState.hasEarlyClaimed) {
continue;
}
GlobalState storage globalState = s_globalStates[param.seasonId];
ClaimableState memory claimableState =
_getClaimableState(config, globalState, userState, unlockState, param.maxTokenAmount);
// short-circuit on potential zero claim value before consuming refundable amount
// if regular claim, claimable must be > 0
// if early claim, earlyClaimable must be > 0
if (
(claimableState.claimable == 0 && !param.isEarlyClaim)
|| (
claimableState.claimable == 0 && claimableState.earlyVestableBonus == 0
&& param.isEarlyClaim
)
) {
continue;
}
if (claimableState.claimed == 0) {
// User is claiming for the first time for this particular season, so the project can no
// longer reclaim the refundable amount for this user's credits
i_factory.reduceRefundableAmount(address(i_token), param.seasonId, param.maxTokenAmount);
}
uint256 toBeClaimed = claimableState.claimable;
if (unlockState.isUnlocking && param.isEarlyClaim) {
globalState.totalLoyalty +=
claimableState.bonus - claimableState.vested - claimableState.earlyVestableBonus;
globalState.totalLoyaltyIneligible += param.maxTokenAmount;
userState.hasEarlyClaimed = true;
toBeClaimed += claimableState.earlyVestableBonus;
}
totalClaimableAmount += toBeClaimed;
_updateClaimedAmounts(
user,
globalState,
userState,
param,
toBeClaimed,
param.isEarlyClaim ? claimableState.earlyVestableBonus : 0
);
}
// check delegation for early claims and exclude i_multicall3 contract.
if (isEarlyClaim && user != msg.sender) {
if (
!IDelegateRegistry(i_delegateRegistry).checkDelegateForContract({
to: msg.sender,
from: user,
contract_: address(i_factory),
rights: bytes32(0)
}) || msg.sender == i_multicall3
) {
revert InvalidSender(msg.sender);
}
}
if (totalClaimableAmount == 0) {
return;
}
i_token.safeTransfer(user, totalClaimableAmount);
}
/// @notice Updates the claimed amounts for a user and the season
/// @param user The user address
/// @param globalState The global state for the season
/// @param userState The user state for the season
/// @param param The input parameters for the claim
/// @param toBeClaimed The amount of tokens to be claimed by the user
/// @param earlyVestableBonus The amount of bonus tokens that can be claimed early
/// @dev This function is called when a user claims tokens
function _updateClaimedAmounts(
address user,
GlobalState storage globalState,
UserState memory userState,
ClaimParams memory param,
uint256 toBeClaimed,
uint256 earlyVestableBonus
) private {
userState.claimed += uint248(toBeClaimed);
s_userStates[user][param.seasonId] = userState;
globalState.totalClaimed += toBeClaimed;
emit Claimed(
user,
param.seasonId,
toBeClaimed,
param.isEarlyClaim,
earlyVestableBonus,
userState.claimed,
globalState.totalClaimed,
globalState.totalLoyalty,
globalState.totalLoyaltyIneligible
);
}
/// @notice Only callable by the factory contract admin
modifier onlyProjectAdmin() {
if (msg.sender != i_factory.getProjectConfig(address(i_token)).admin) {
revert IAccessControl.AccessControlUnauthorizedAccount(msg.sender, keccak256("PROJECT_ADMIN"));
}
_;
}
/// @notice Only callable when claim contract is not paused
modifier whenClaimNotPaused() {
if (i_factory.isClaimContractPaused(address(i_token))) {
revert Pausable.EnforcedPause();
}
_;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {BUILDFactory} from "../BUILDFactory.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IBUILDClaim is IERC165 {
/// @notice this event is emitted when a token deposit is made
/// @param token The token address
/// @param sender The depositor address
/// @param amount The deposit amount
/// @param totalDeposit The cumulative amount deposited to this contract
event Deposited(
address indexed token, address indexed sender, uint256 amount, uint256 totalDeposit
);
/// @notice this event is emitted when a token withdrawal is made
/// @param token The token address
/// @param recipient The withdrawal address
/// @param amount The withdrawal amount
/// @param totalWithdrawn The cumulative amount withdrawn from this contract
event Withdrawn(
address indexed token, address indexed recipient, uint256 amount, uint256 totalWithdrawn
);
/// @notice this event is emitted when a claim is made
/// @param user The user address
/// @param seasonId The season id
/// @param amount The claim amount
/// @param isEarlyClaim The flag indicating the claim was an early vest
/// @param earlyVestAmount The portion of claim amount that is early vested
/// @param userClaimedInSeason The cumulative amount claimed by the user in the season
/// @param totalClaimedInSeason The cumulative amount claimed by all users in the season
/// @param totalLoyaltyAmount The cumulative amount in the loyalty pool in the season
/// @param totalLoyaltyIneligibleAmount The cumulative amount of ineligible loyalty in the season
event Claimed(
address indexed user,
uint256 seasonId,
uint256 amount,
bool isEarlyClaim,
uint256 earlyVestAmount,
uint256 userClaimedInSeason,
uint256 totalClaimedInSeason,
uint256 totalLoyaltyAmount,
uint256 totalLoyaltyIneligibleAmount
);
/// @notice this error is thrown when an invalid merkle proof is provided
error InvalidMerkleProof();
/// @notice this error is thrown when a zero address is provided as the user address
/// @param user The user address
error InvalidUser(address user);
/// @notice this error is thrown when the sender is not the user or their delegate and
/// is trying to early claim
/// @param msgSender The address of the sender
error InvalidSender(address msgSender);
/// @notice this error is thrown when the unlock period for a season has not started
/// @param seasonId The season id
error UnlockNotStarted(uint256 seasonId);
/// @notice This error is thrown when the user is trying to early claim tokens for a season that
/// has finished vesting
/// @param user The user address
/// @param seasonId The season id
error InvalidEarlyClaim(address user, uint256 seasonId);
/// @notice This error is thrown when the expected token amount wasn't transferred after a deposit
/// @param balanceBefore The balance before the deposit
/// @param balanceAfter The balance after the deposit
error InvalidDeposit(uint256 balanceBefore, uint256 balanceAfter);
/// @notice This struct defines the parameters for claiming tokens
struct ClaimParams {
uint32 seasonId; // ────╮ The season id
bool isEarlyClaim; // ──╯ is Early Claim
bytes32[] proof; // The merkle proof for the user's token amount for a season
uint256 maxTokenAmount; // The total token amount user can get for a season
uint256 salt; // A randomly generated salt to prevent brute-force guessing of merkle proofs
}
/// @notice this struct defines all the necessary state of the claimable tokens for a user
struct ClaimableState {
uint256 base; // The base amount of tokens that can be claimed
uint256 bonus; // The bonus amount of tokens that can be claimed
uint256 vested; // The amount of bonus tokens that are vested
uint256 claimable; // The total amount of tokens that can be claimed, roughly base + vested
uint256 earlyVestableBonus; // The amount of bonus tokens that are not vested and can be claimed
// early
uint256 loyaltyBonus; // The amount of loyalty bonus tokens that can be claimed
uint256 claimed; // The amount of tokens that have already been claimed by this user
// earlyVestClaimable is derivable by claimable + earlyVestableBonus
}
/// @notice this struct defines the global state of a season
struct GlobalState {
uint256 totalLoyalty; // The total amount of loyalty bonus tokens that can be claimed
uint256 totalLoyaltyIneligible; // The total amount of regular claim tokens that are factored
// out of consideration for totalLoyalty allocation.
// This is the sum of all max token amounts of users who have early claimed
uint256 totalClaimed; // The total amount of tokens that have been claimed by all users
}
/// @notice The user state for a season
struct UserState {
uint248 claimed; // ───────╮ The amount of tokens that have already been claimed by this user
bool hasEarlyClaimed; // ──╯ Whether the user has already claimed tokens for this season
}
/// @notice This struct defines the user and season id for batch queries
struct UserSeasonId {
/// @notice The user address
address user;
/// @notice The season id
uint256 seasonId;
}
/// @notice This struct defines the user and season id for batch queries
struct SeasonIdAndMaxTokenAmount {
/// @notice The season id
uint256 seasonId;
/// @notice the max token amount for the season
uint256 maxTokenAmount;
}
/// @notice Project admins can deposit tokens for the program.
/// @param amount The deposit amount
function deposit(
uint256 amount
) external;
/// @notice Project admins can execute the scheduled token withdrawal
function withdraw() external;
/// @notice Calculates the unlocked tokens for a particular user and transfers the tokens to the
/// user.
/// The user must provide a valid merkle proof and total token amount they will get after unlock
/// finishes for each season they want to claim for.
/// This function is to be used by EOAs when they claim from a single BUILDClaim contract, as well
/// as by multisig wallets when they claim from a single BUILDClaim contract or batch claim from
/// multiple BUILDClaim contracts.
/// @param user The address of the user claiming the tokens. This should match the msg.sender.
/// @param params Claim params including the season IDs, proofs, salts, and max token amounts
function claim(address user, ClaimParams[] calldata params) external;
/// @notice Returns the BUILDFactory that was used to deploy the claim contract
/// @return the factory address
function getFactory() external view returns (BUILDFactory);
/// @notice Returns the project token
/// @return the token address
function getToken() external view returns (IERC20);
/// @notice Calculates the global state for a season
/// @param seasonIds The season id array
/// @return GlobalState The global state for the seasons
function getGlobalState(
uint256[] calldata seasonIds
) external view returns (GlobalState[] memory);
/// @notice Returns the user state for a list of seasons
/// @param usersAndSeasonIds The list of user address + season id
/// @return UserState[] The user's claimed amount for list of seasons
function getUserState(
UserSeasonId[] calldata usersAndSeasonIds
) external view returns (UserState[] memory);
/// @notice Calculates the various amounts of claiming related tokens for a user
/// @param user The user address
/// @param seasonIdsAndMaxTokenAmounts The list of season ids and total claimable token amount for
/// the season
/// @return ClaimableState The various amounts of tokens related to claiming for a user
function getCurrentClaimValues(
address user,
SeasonIdAndMaxTokenAmount[] calldata seasonIdsAndMaxTokenAmounts
) external view returns (ClaimableState[] memory);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
import {BUILDClaim} from "../BUILDClaim.sol";
import {IBUILDClaim} from "./IBUILDClaim.sol";
interface IBUILDFactory {
/// @notice This event is emitted when a new project is added or its admin changed
/// @param token The project token
/// @param admin The new project admin
event ProjectAddedOrAdminChanged(address indexed token, address admin);
/// @notice This event is emitted when an existing project is removed
/// @param token The project token
event ProjectRemoved(address indexed token);
/// @notice This event is emitted when a season config is updated
/// @param seasonId The season id
/// @param unlockStartsAt The season's unlock start time
event SeasonUnlockStartTimeUpdated(uint256 indexed seasonId, uint256 unlockStartsAt);
/// @notice This event is emitted when the maxUnlockDuration is updated
/// @param maxUnlockDuration The new maximum unlock duration
event MaxUnlockDurationUpdated(uint40 maxUnlockDuration);
/// @notice This event is emitted when the maxUnlockDelay is updated
/// @param maxUnlockDelay The new maximum unlock delay
event MaxUnlockDelayUpdated(uint40 maxUnlockDelay);
/// @notice this event is emitted when a project's season config is changed
/// @param token The project token
/// @param seasonId The season id
/// @param config The new project season config
event ProjectSeasonConfigUpdated(
address indexed token, uint256 indexed seasonId, ProjectSeasonConfig config
);
/// @notice this event is emitted when the total deposited amount of a project is increased
/// @param token The project token
/// @param sender The sender address
/// @param amount The deposit amount
/// @param totalDeposited The cumulative deposited amount of the project after the update
event ProjectTotalDepositedIncreased(
address indexed token, address indexed sender, uint256 amount, uint256 totalDeposited
);
/// @notice this event is emitted when the total allocated amount of a token is updated
/// @param token The project token
/// @param totalAllocatedToAllSeasonsPrev The cumulative amount allocated before the update
/// @param totalAllocatedToAllSeasons The cumulative amount allocated after the update
event ProjectTotalAllocatedUpdated(
address indexed token,
uint256 totalAllocatedToAllSeasonsPrev,
uint256 totalAllocatedToAllSeasons,
uint256 refundableAmount
);
/// @notice this event is emitted when a token withdrawal is scheduled
/// @param token The project token
/// @param recipient The recipient address
/// @param amount The withdrawal amount
event WithdrawalScheduled(address indexed token, address indexed recipient, uint256 amount);
/// @notice this event is emitted when a token withdrawal is cancelled
/// @param token The project token
/// @param recipient The previous recipient address
/// @param amount The previous withdrawal amount
event WithdrawalCancelled(address indexed token, address indexed recipient, uint256 amount);
/// @notice this event is emitted when a token withdrawal is executed
/// @param token The project token
/// @param recipient The recipient address
/// @param amount The withdrawal amount
/// @param totalWithdrawn The cumulative amount withdrawn on the token after the update
event WithdrawalExecuted(
address indexed token, address indexed recipient, uint256 amount, uint256 totalWithdrawn
);
/// @notice This event is emitted when a new claim contract is deployed for a project
/// @param token The project token
/// @param claim The project claim contract
event ClaimDeployed(address indexed token, address indexed claim);
/// @notice This event is emitted when a claim contract is paused
/// @param token The project token
event ClaimPaused(address indexed token);
/// @notice This event is emitted when a claim contract is unpaused
/// @param token The project token
event ClaimUnpaused(address indexed token);
/// @notice This event is emitted when refunding has started for season and token
/// @param token The project token
/// @param seasonId the season id
/// @param totalRefunded the total refunded amount for the projec
event ProjectSeasonRefundStarted(
address indexed token, uint256 indexed seasonId, uint256 totalRefunded
);
/// @notice This event is emitted when the refundable amount is reduced for a project season
/// @param token The project token
/// @param seasonId the season id
/// @param amount the amount to reduce the project's refundable amount by
/// @param refundableAmount the refundable amount after the update
event ProjectSeasonRefundableAmountReduced(
address indexed token, uint256 indexed seasonId, uint256 amount, uint256 refundableAmount
);
/// @notice this error is thrown when the project doesn't have enough tokens to allocate for a
/// season
/// @param token the address of the project
/// @param seasonId The season id
/// @param amount The requested amount
/// @param maxAvailable The maximum available amount
error InsufficientFunds(address token, uint256 seasonId, uint256 amount, uint256 maxAvailable);
/// @notice This error is thrown when attempting to add projects with invalid parameters
error InvalidAddProjectParams();
/// @notice This error is thrown when attempting to fetch a nonexistent project
error ProjectDoesNotExist(address token);
/// @notice This error is thrown when attempting to fetch a nonexistent season
error SeasonDoesNotExist(uint256 seasonId);
/// @notice This error is thrown when deploy a claim contract for a token when one is already
/// deployed
error ClaimAlreadyExists(address token, address claim);
/// @notice This error is thrown when attempting to set a project season config for a season after
/// its unlock start time
/// @param seasonId The season id
error SeasonAlreadyStarted(uint256 seasonId);
/// @notice this error is thrown when the project season that hasn't been configured
/// @param seasonId The season id
error ProjectSeasonDoesNotExist(uint256 seasonId, address token);
/// @notice This error is thrown when attempting to set a project season config or start the
/// refund phase for a season that is refunding
/// @param token The project token
/// @param seasonId The season id
error ProjectSeasonIsRefunding(address token, uint256 seasonId);
/// @notice This error is thrown when attempting to set a season start date in the past.
error InvalidUnlockStartsAt(uint256 seasonId, uint256 unlockStartsAt);
/// @notice this error is thrown when a zero or a value greater than the maxUnlockDuration is
/// provided as the project season's unlock duration
/// @param seasonId The season id
/// @param unlockDuration The unlock duration
error InvalidUnlockDuration(uint256 seasonId, uint40 unlockDuration);
/// @notice this error is thrown when a zero or a value greater than the maxUnlockDelay is
/// provided as the project season's unlock delay
/// @param seasonId The season id
/// @param unlockDelay The unlock delay
error InvalidUnlockDelay(uint256 seasonId, uint40 unlockDelay);
/// @notice this error is thrown when a zero token amount for a season is provided
/// @param seasonId The season id
error InvalidTokenAmount(uint256 seasonId);
/// @notice This error is thrown whenever a zero-address is supplied when
/// a non-zero address is required
error InvalidZeroAddress();
/// @notice This error is thrown whenever an unauthorized sender calls a protected function
error Unauthorized();
/// @notice This error is thrown when a zero unlock duration is provided
error InvalidZeroMaxUnlockDuration();
/// @notice This error is thrown when a zero unlock delay is provided
error InvalidZeroMaxUnlockDelay();
/// @notice This error is thrown when an invalid amount that does not satisfy the system
/// requirements is provided
error InvalidAmount();
/// @notice this error is thrown when a withdrawal is scheduled with a zero address as the
/// recipient
/// @param recipient The withdrawal recipient address
error InvalidWithdrawalRecipient(address recipient);
/// @notice this error is thrown when a withdrawal is scheduled with an invalid amount
/// @param amount The withdrawal amount
/// @param maxAvailable The maximum amount available to withdraw
error InvalidWithdrawalAmount(uint256 amount, uint256 maxAvailable);
/// @notice this error is thrown when attempting to cancel or execute a nonexistent withdrawal
/// @param token The token address
error WithdrawalDoesNotExist(address token);
/// @notice this error is thrown when a withdrawal is already scheduled for the token
/// @param token The token address
/// @param amount The amount of the currently scheduled withdrawal
error WithdrawalAlreadyScheduled(address token, uint256 amount);
/// @notice this error is thrown when an base token claim percentage value of more than 100% is
/// provided or when the base token claim percentage is 100% and the unlock duration is
/// greater than 1
/// @param seasonId The season id
/// @param baseTokenClaimBps The base token claim percentage
/// @param unlockDuration The unlock duration
error InvalidBaseTokenClaimBps(uint256 seasonId, uint16 baseTokenClaimBps, uint40 unlockDuration);
/// @notice this error is thrown when the min ratio > max ratio
/// @param earlyVestRatioMinBps The minimum early vest ratio
/// @param earlyVestRatioMaxBps The maximum early vest ratio
error InvalidEarlyVestRatios(uint256 earlyVestRatioMinBps, uint256 earlyVestRatioMaxBps);
/// @notice This error is thrown when a project season is not ready for refunding
/// @param token The project token address
/// @param seasonId The season id
/// @dev The season is not ready for refunding if the unlock period has not started
/// or if the unlock period has not ended yet
error SeasonNotReadyForRefund(address token, uint256 seasonId);
/// @notice This struct defines the params required by the addProjects function
struct AddProjectParams {
address token; // The project token address
address admin; // The project admin address
}
/// @notice This struct defines the configs for each project
struct ProjectConfig {
address admin; // The project admin address
BUILDClaim claim; // The project claim contract
}
/// @notice This struct defines the configs for a single project's season
struct ProjectSeasonConfig {
uint256 tokenAmount; // The amount of tokens available for the project on the season
bytes32 merkleRoot; // The root for the allowlist merkle tree
uint40 unlockDelay; // ───────────╮ The delay after the unlock starts
// │ before the tokens are claimable
uint40 unlockDuration; // │ The duration of the unlock period
uint40 earlyVestRatioMinBps; // │ The minimum early vest ratio in bps
uint40 earlyVestRatioMaxBps; // │ The maximum early vest ratio in bps
uint16 baseTokenClaimBps; // │ The base token amount that can be claimed
// │ instantly in basis points. This value can be set between
// │ 0 (0%) and 10000 (100%), inclusive.
bool isRefunding; // ─────────────╯ Whether the project
// started refunding credits for the season
}
/// @notice This struct defines the parameters for setting a project season config
struct SetProjectSeasonParams {
uint256 seasonId; // The season id
address token; // The project token address
ProjectSeasonConfig config; // The project season config
}
/// @notice The token amounts status for the project
struct TokenAmounts {
uint256 totalDeposited; // The total amount of tokens deposited by the project
uint256 totalWithdrawn; // The total amount of tokens withdrawn by the project
uint256 totalAllocatedToAllSeasons; // The total amount of tokens allocated to all seasons
uint256 totalRefunded; // The total amount of tokens that can be reclaimed by the project
// (corresponding to the credits amount that users have been refunded for)
}
/// @notice This struct defines the parameters for a scheduled withdrawal
struct Withdrawal {
address recipient; // The scheduled withdrawal address
uint256 amount; // The scheduled withdrawal amount
}
struct UnlockMaxConfigs {
uint40 maxUnlockDuration; // ──╮ The upper bound for the unlock duration
uint40 maxUnlockDelay; // ─────╯ The upper bound for the unlock delay
}
/// @notice Allowlists one or more projects and sets the project admin
/// Can also be used to update the project admin’s address
/// @dev Only callable by the default admin
/// @param projects the project's token and admin address
function addProjects(
AddProjectParams[] calldata projects
) external;
/// @notice Removes one or more projects from the allowlist and revokes the PROJECT_ROLE from the
/// projects’ admins
/// @dev Only callable by the default admin
/// @param tokens a list of project token addresses
function removeProjects(
address[] calldata tokens
) external;
/// @notice Deploys a new claim contract for a project
/// The project must be allowlisted first
/// Only callable by the project admin
/// @param token The project token address
function deployClaim(
address token
) external returns (IBUILDClaim);
/// @notice Sets the upper bounds for the unlock duration and the delay
/// @dev Only callable by the default admin
/// @dev Only callable when the contract is open
/// @param config The new maximum unlock duration and unlock delay
function setUnlockConfigMaxValues(
UnlockMaxConfigs calldata config
) external;
/// @notice Sets the unlock starting time of the new season
/// @dev Cannot set a season's unlock start time after the season has started
/// @dev Only callable by the default admin
/// @param seasonId The season id
/// @param unlockStartsAt The season's unlock start time
function setSeasonUnlockStartTime(uint256 seasonId, uint256 unlockStartsAt) external;
/// @notice Updates the configs for a project's single season
/// @param params The season config parameters
/// @dev Only callable by the admin of the BUILDFactory
/// @dev tokenAmount = 0 means the project is not in the season
/// @dev unlockDelay = 0 means the unlock period starts immediately, at
/// s_seasonUnlockStartTimes[seasonId]
/// @dev unlockDuration = 0 means all tokens are unlocked immediately, at
/// s_seasonUnlockStartTimes[seasonId] + unlockDelay
function setProjectSeasonConfig(
SetProjectSeasonParams[] calldata params
) external;
/// @notice Pauses claim contract for a specific project
/// @dev Only callable by the pauser role
/// @dev The emergencyPause is used to pause all claim contracts as well as the factory contract
/// @param token The project token
function pauseClaimContract(
address token
) external;
/// @notice Unpauses claim contract for a specific project
/// @dev Only callable by the pauser role
/// @dev The emergencyUnpause is used to unpause all claim contracts as well as the factory
/// contract
/// @dev A claim contract cannot be unpaused if the factory is paused
/// @param token The project token
function unpauseClaimContract(
address token
) external;
/// @notice Sets a season to a refunding state
/// Only callable by the project admin
/// @param token the contract to set into a refunding state
/// @param seasonId the season to set into a refunding state
function startRefund(address token, uint256 seasonId) external;
/// @notice Reduce the refundable amount for a project season
/// @dev Can only be called from the claims contract
/// @param token the token address of the project
/// @param seasonId the seasonId
/// @param amount the amount to reduce the project's refundable amount by
function reduceRefundableAmount(address token, uint256 seasonId, uint256 amount) external;
/// @notice Increment the total deposited token of the project
/// @dev Can only be called from the claims contract
/// @param token the token address of the project
/// @param amount to increment totalDeposited
function addTotalDeposited(address token, uint256 amount) external returns (uint256);
/// @notice Factory admins can schedule token withdrawals for the project.
/// @dev Only callable by the admin of the BUILDFactory
/// @param token address of the project token
/// @param recipient The withdrawal address
/// @param amount The withdrawal amount
function scheduleWithdraw(address token, address recipient, uint256 amount) external;
/// @notice Factory admins can cancel previously scheduled token withdrawals
/// @dev Only callable by the admin of the BUILDFactory
/// @param token address of the project token
function cancelWithdraw(
address token
) external;
/// @notice Project admins can execute scheduled token withdrawals from the claim contract
/// @dev Only callable by the claims contract
/// @param token address of the project token
/// @return Withdrawal The withdrawal recipient and amount
/// @return uint256 The updated total withdrawn amount of the project
function executeWithdraw(
address token
) external returns (Withdrawal memory, uint256);
/// @notice Returns all projects
/// @return The list of project token addresses
function getProjects() external view returns (address[] memory);
/// @notice Returns the upper bounds for the unlock duration and delay
/// @return UnlockMaxConfigs The max unlock duration and max unlock delay
function getUnlockConfigMaxValues() external view returns (UnlockMaxConfigs memory);
/// @notice Returns a project config
/// @param token The project token address
/// @return A project config consisting of the project’s admin address and the claim contract
/// address
function getProjectConfig(
address token
) external view returns (ProjectConfig memory);
/// @notice Returns a season config
/// @param seasonId The season id
/// @return startTime The season's unlock start time
function getSeasonUnlockStartTime(
uint256 seasonId
) external view returns (uint256 startTime);
/// @notice Returns a project season config
/// @param token The project token address
/// @param seasonId The season id
/// @return projectSeasonConfig project season config consisting of the token amount, unlock ends
/// at, total credits,
/// and merkle root
/// @return unlockEndsAt The season's unlock end time
function getProjectSeasonConfig(
address token,
uint256 seasonId
) external view returns (ProjectSeasonConfig memory projectSeasonConfig, uint256 unlockEndsAt);
/// @notice Returns the current pause state of a claim contract for a specific project
/// @dev A claim contract is considered paused when the factory is paused (emergencyPause) or the
/// claim contract is paused individually (pauseClaimContract)
/// @param token The project token address
/// @return bool The current pause state
function isClaimContractPaused(
address token
) external view returns (bool);
/// @notice Returns the refunding state of a season contract
/// @param token the address of the token
/// @param seasonId the id of the season
/// @return bool The current refunding state of season
function isRefunding(address token, uint256 seasonId) external view returns (bool);
/// @notice Get the token amount struct of the project
/// @param token the token address of the project
/// @return TokenAmounts the token amount struct for the project
function getTokenAmounts(
address token
) external view returns (TokenAmounts memory);
/// @notice Calculate the max available token amount of the project
/// @param token the token address of the project
/// @return uint256 maxAvailable The maximum available amount to be allocated or withdrawn
function calcMaxAvailableAmount(
address token
) external view returns (uint256);
/// @notice Get the refundable amount for a project season
/// @param token the token address of the project
/// @param seasonId the seasonId
/// @return uint256 The refundable amount
function getRefundableAmount(address token, uint256 seasonId) external view returns (uint256);
/// @notice Returns parameters for a scheduled withdrawal, if any
/// @param token address of the project token
/// @return the withdrawal recipient address and amount
function getScheduledWithdrawal(
address token
) external view returns (Withdrawal memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITypeAndVersion {
function typeAndVersion() external pure returns (string memory);
}// 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);
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {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);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
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` to `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;
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {IBUILDClaim} from "./interfaces/IBUILDClaim.sol";
import {IBUILDFactory} from "./interfaces/IBUILDFactory.sol";
import {ITypeAndVersion} from "chainlink/contracts/src/v0.8/shared/interfaces/ITypeAndVersion.sol";
import {BUILDClaim} from "./BUILDClaim.sol";
import {ManagedAccessControl} from "./ManagedAccessControl.sol";
import {UnlockState, getUnlockState} from "./Unlockable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
contract BUILDFactory is IBUILDFactory, ITypeAndVersion, ManagedAccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
/// @inheritdoc ITypeAndVersion
string public constant override typeAndVersion = "BUILDFactory 1.0.0";
/// @notice Parameters required to instantiate the BUILDFactory contract
struct ConstructorParams {
address admin; // ───────────────────╮ The initial factory admin address
uint40 maxUnlockDuration; // │ The initial max unlock duration
uint40 maxUnlockDelay; // ───────────╯ The initial max unlock delay
address delegateRegistry; // The delegate registry contract
address multicall3; // The Multicall3 contract address
}
/// @notice The delegate registry contract
address private immutable i_delegateRegistry;
/// @notice The Multicall3 contract address
address private immutable i_multicall3;
/// @notice The maximum unlock duration and delay values allowed
UnlockMaxConfigs private s_unlockMaxConfigs;
/// @notice The set of project addresses
EnumerableSet.AddressSet private s_projectsList;
/// @notice The project configs
mapping(address token => ProjectConfig config) private s_projects;
/// @notice The season unlock start times for all projects
mapping(uint256 seasonId => uint256 unlockStartsAt) private s_seasonUnlockStartTimes;
/// @notice The project season configs
mapping(address token => mapping(uint256 seasonId => ProjectSeasonConfig config)) private
s_projectSeasonConfigs;
/// @notice The amount of tokens that can be refunded to a project for each season
/// @dev This is the amount of tokens that corresponds to the credits of the users who have not
/// claimed anything yet from the season, and may be refunded for their credits in the future.
/// The project can reclaim these tokens if the users don't claim them until the refund phase
/// starts.
mapping(address token => mapping(uint256 seasonId => uint256 amount)) private s_refundableAmounts;
/// @notice Mapping of token amounts per project
mapping(address token => TokenAmounts) private s_tokenAmounts;
/// @notice The parameters for a scheduled withdrawal, if any
mapping(address token => Withdrawal) private s_withdrawals;
/// @notice Pause state for claim contracts by project
mapping(address token => bool paused) private s_claimPaused;
/// @notice The basis points denominator for percentages
uint256 private constant PERCENTAGE_BASIS_POINTS_DENOMINATOR = 10_000;
// ================================================================
// | Initialization |
// ================================================================
/// @dev We set the adminRoleTransferDelay to 0 (no delay)
/// @dev In AccessControlDefaultAdminRules, we check that params.admin is not a zero address and
/// set it as the initial defaultAdmin, with the DEFAULT_ADMIN_ROLE role.
constructor(
ConstructorParams memory params
) ManagedAccessControl(0, params.admin) {
_setUnlockConfigMaxValues(
IBUILDFactory.UnlockMaxConfigs({
maxUnlockDelay: params.maxUnlockDelay,
maxUnlockDuration: params.maxUnlockDuration
})
);
if (address(params.delegateRegistry) == address(0) || address(params.multicall3) == address(0))
{
revert InvalidZeroAddress();
}
i_delegateRegistry = params.delegateRegistry;
i_multicall3 = params.multicall3;
}
// ================================================================
// | Project Allowlisting |
// ================================================================
/// @inheritdoc IBUILDFactory
function addProjects(
AddProjectParams[] calldata projects
) external override whenOpen onlyRole(DEFAULT_ADMIN_ROLE) {
// Cache array length outside loop
uint256 projectsLength = projects.length;
for (uint256 i = 0; i < projectsLength; ++i) {
AddProjectParams memory params = projects[i];
if (params.admin == address(0) || params.token == address(0)) {
revert InvalidAddProjectParams();
}
try IERC20Metadata(params.token).decimals() returns (uint8) {
ProjectConfig storage project = s_projects[params.token];
project.admin = params.admin;
s_projectsList.add(params.token);
emit ProjectAddedOrAdminChanged(params.token, project.admin);
} catch {
revert InvalidAddProjectParams();
}
}
}
/// @inheritdoc IBUILDFactory
function removeProjects(
address[] calldata tokens
) external override whenOpen onlyRole(DEFAULT_ADMIN_ROLE) {
EnumerableSet.AddressSet storage projectsList = s_projectsList;
// Cache array length outside loop
uint256 tokensLength = tokens.length;
for (uint256 i = 0; i < tokensLength; ++i) {
address token = tokens[i];
if (!projectsList.remove(token)) {
revert ProjectDoesNotExist(token);
}
delete s_projects[token];
emit ProjectRemoved(token);
}
}
/// @inheritdoc IBUILDFactory
function getProjects() external view override returns (address[] memory) {
return s_projectsList.values();
}
/// @inheritdoc IBUILDFactory
function getProjectConfig(
address token
) external view override returns (ProjectConfig memory) {
return s_projects[token];
}
/// @inheritdoc IBUILDFactory
function deployClaim(
address token
) external override whenOpen whenNotPaused returns (IBUILDClaim) {
_ensureProjectExists(token);
ProjectConfig storage project = s_projects[token];
if (msg.sender != project.admin) revert Unauthorized();
if (address(project.claim) != address(0)) {
revert ClaimAlreadyExists(token, address(project.claim));
}
BUILDClaim claim = new BUILDClaim(token, i_delegateRegistry, i_multicall3);
project.claim = claim;
emit ClaimDeployed(token, address(claim));
return IBUILDClaim(claim);
}
/// @notice Util to ensure only the claims contract can call a function
/// @param token The project token address
function _requireRegisteredClaim(
address token
) internal view {
if (address(s_projects[token].claim) != msg.sender) {
revert Unauthorized();
}
}
// ================================================================
// | Season Configuration |
// ================================================================
/// @inheritdoc IBUILDFactory
function setUnlockConfigMaxValues(
UnlockMaxConfigs calldata config
) external override onlyRole(DEFAULT_ADMIN_ROLE) whenOpen {
_setUnlockConfigMaxValues(config);
}
/// @notice Util function to set the maximum unlock duration and delay
/// @param config The new maximum unlock duration and unlock delay
function _setUnlockConfigMaxValues(
UnlockMaxConfigs memory config
) private {
if (config.maxUnlockDuration == 0) {
revert InvalidZeroMaxUnlockDuration();
}
if (config.maxUnlockDelay == 0) {
revert InvalidZeroMaxUnlockDelay();
}
UnlockMaxConfigs storage currentMax = s_unlockMaxConfigs;
if (currentMax.maxUnlockDuration != config.maxUnlockDuration) {
currentMax.maxUnlockDuration = config.maxUnlockDuration;
emit MaxUnlockDurationUpdated(config.maxUnlockDuration);
}
if (currentMax.maxUnlockDelay != config.maxUnlockDelay) {
currentMax.maxUnlockDelay = config.maxUnlockDelay;
emit MaxUnlockDelayUpdated(config.maxUnlockDelay);
}
}
/// @inheritdoc IBUILDFactory
function getUnlockConfigMaxValues() external view override returns (UnlockMaxConfigs memory) {
return s_unlockMaxConfigs;
}
/// @inheritdoc IBUILDFactory
function setSeasonUnlockStartTime(
uint256 seasonId,
uint256 unlockStartsAt
) external override whenOpen onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 currentUnlockStartTime = s_seasonUnlockStartTimes[seasonId];
// A start time of 0 means it has not been set yet
bool hasUnlockStarted = currentUnlockStartTime != 0 && currentUnlockStartTime <= block.timestamp;
if (hasUnlockStarted || unlockStartsAt <= block.timestamp) {
revert InvalidUnlockStartsAt(seasonId, unlockStartsAt);
}
s_seasonUnlockStartTimes[seasonId] = unlockStartsAt;
emit SeasonUnlockStartTimeUpdated(seasonId, unlockStartsAt);
}
/// @inheritdoc IBUILDFactory
function setProjectSeasonConfig(
SetProjectSeasonParams[] calldata params
) external override whenOpen onlyRole(DEFAULT_ADMIN_ROLE) {
for (uint256 i = 0; i < params.length; ++i) {
_setProjectSeasonConfig(params[i]);
}
}
/// @notice Internal function to set the project season config
/// @dev This function is called by the setProjectSeasonConfig function
/// @param params The parameters for the project season config
function _setProjectSeasonConfig(
SetProjectSeasonParams calldata params
) internal {
_requireClaimNotPaused(params.token);
_ensureProjectExists(params.token);
uint256 unlockStartsAt = s_seasonUnlockStartTimes[params.seasonId];
if (unlockStartsAt == 0) {
revert SeasonDoesNotExist(params.seasonId);
}
if (unlockStartsAt <= block.timestamp) {
revert SeasonAlreadyStarted(params.seasonId);
}
ProjectSeasonConfig storage currentConfig =
s_projectSeasonConfigs[params.token][params.seasonId];
ProjectSeasonConfig memory config = params.config;
UnlockMaxConfigs memory unlockMaxConfigs = s_unlockMaxConfigs;
if (config.isRefunding) {
// Ignore the isRefunding flag, starting refund should be done with the startRefund function
config.isRefunding = false;
}
if (config.unlockDuration > unlockMaxConfigs.maxUnlockDuration) {
revert InvalidUnlockDuration(params.seasonId, config.unlockDuration);
}
if (config.unlockDelay > unlockMaxConfigs.maxUnlockDelay) {
revert InvalidUnlockDelay(params.seasonId, config.unlockDelay);
}
// prevent overflow for UserState.claimed value
if (config.tokenAmount > type(uint248).max) {
revert InvalidTokenAmount(params.seasonId);
}
// baseTokenClaimBps should be <100%. 100% means no unlock period, i.e., only allowed when
// unlockDuration == 0.
if (
config.baseTokenClaimBps > PERCENTAGE_BASIS_POINTS_DENOMINATOR
|| (
config.baseTokenClaimBps == PERCENTAGE_BASIS_POINTS_DENOMINATOR
&& config.unlockDuration != 0
)
) {
revert InvalidBaseTokenClaimBps(
params.seasonId, config.baseTokenClaimBps, config.unlockDuration
);
}
if (
config.earlyVestRatioMaxBps > PERCENTAGE_BASIS_POINTS_DENOMINATOR
|| config.earlyVestRatioMinBps > config.earlyVestRatioMaxBps
) {
revert InvalidEarlyVestRatios(config.earlyVestRatioMinBps, config.earlyVestRatioMaxBps);
}
_setSeasonTokenAmount(
params.token, params.seasonId, config.tokenAmount, currentConfig.tokenAmount
);
currentConfig.tokenAmount = config.tokenAmount;
currentConfig.baseTokenClaimBps = config.baseTokenClaimBps;
currentConfig.unlockDelay = config.unlockDelay;
currentConfig.unlockDuration = config.unlockDuration;
currentConfig.merkleRoot = config.merkleRoot;
currentConfig.earlyVestRatioMinBps = config.earlyVestRatioMinBps;
currentConfig.earlyVestRatioMaxBps = config.earlyVestRatioMaxBps;
emit ProjectSeasonConfigUpdated(params.token, params.seasonId, currentConfig);
}
/// @notice Internal function to set the season allocated and refundable token amounts
/// @dev The new amount must be less than or equal to the max available amount, based on the total
/// deposit, withdrawal, refunded and season-allocated amounts.
/// @param token The project's token address
/// @param seasonId The season id
/// @param amount The new token amount
/// @param currentAmount The current token amount
function _setSeasonTokenAmount(
address token,
uint256 seasonId,
uint256 amount,
uint256 currentAmount
) internal {
TokenAmounts storage tokenAmounts = s_tokenAmounts[token];
uint256 totalAllocatedAmountBefore = tokenAmounts.totalAllocatedToAllSeasons;
uint256 maxAvailable = _calcMaxAvailableForWithdrawalOrNewSeason(tokenAmounts);
// If the season is being updated, the current amount allocated to the same season should be
// added to the max available amount.
// If there is a scheduled withdrawal, the amount should be subtracted from the max available
// amount.
// The validation for amount > 0 is done in the BUILDFactory.setProjectSeasonConfig that
// calls this function.
maxAvailable = maxAvailable + currentAmount - s_withdrawals[token].amount;
if (amount > maxAvailable) {
revert InsufficientFunds(token, seasonId, amount, maxAvailable);
}
bool isUpdating = currentAmount != 0;
if (isUpdating) {
tokenAmounts.totalAllocatedToAllSeasons -= currentAmount;
}
tokenAmounts.totalAllocatedToAllSeasons += amount;
s_refundableAmounts[token][seasonId] = amount;
emit ProjectTotalAllocatedUpdated(
token, totalAllocatedAmountBefore, tokenAmounts.totalAllocatedToAllSeasons, amount
);
}
/// @inheritdoc IBUILDFactory
function getSeasonUnlockStartTime(
uint256 seasonId
) external view override returns (uint256) {
return s_seasonUnlockStartTimes[seasonId];
}
/// @inheritdoc IBUILDFactory
function getProjectSeasonConfig(
address token,
uint256 seasonId
) external view override returns (ProjectSeasonConfig memory, uint256 seasonUnlockStartTime) {
return (s_projectSeasonConfigs[token][seasonId], s_seasonUnlockStartTimes[seasonId]);
}
// ================================================================
// | Token Accounting |
// ================================================================
/// @inheritdoc IBUILDFactory
function addTotalDeposited(address token, uint256 amount) external override returns (uint256) {
_requireRegisteredClaim(token);
if (amount == 0) {
revert InvalidAmount();
}
TokenAmounts storage tokenAmounts = s_tokenAmounts[token];
uint256 newTotalDeposited = tokenAmounts.totalDeposited + amount;
tokenAmounts.totalDeposited = newTotalDeposited;
emit ProjectTotalDepositedIncreased(token, msg.sender, amount, newTotalDeposited);
return newTotalDeposited;
}
/// @inheritdoc IBUILDFactory
function reduceRefundableAmount(
address token,
uint256 seasonId,
uint256 amount
) external override {
_requireRegisteredClaim(token);
uint256 currentRefundableAmount = s_refundableAmounts[token][seasonId];
// amount cannot be greater than the refundable amount for the project
if (amount > currentRefundableAmount) {
revert InvalidAmount();
}
s_refundableAmounts[token][seasonId] -= amount;
emit ProjectSeasonRefundableAmountReduced(
token, seasonId, amount, currentRefundableAmount - amount
);
}
/// @inheritdoc IBUILDFactory
function getTokenAmounts(
address token
) external view override returns (TokenAmounts memory) {
return s_tokenAmounts[token];
}
/// @inheritdoc IBUILDFactory
function startRefund(address token, uint256 seasonId) external override whenNotPaused {
if (msg.sender != s_projects[token].admin) revert Unauthorized();
ProjectSeasonConfig storage config = s_projectSeasonConfigs[token][seasonId];
if (config.tokenAmount == 0) {
revert ProjectSeasonDoesNotExist(seasonId, token);
}
if (config.isRefunding) {
revert ProjectSeasonIsRefunding(token, seasonId);
}
UnlockState memory unlockState = getUnlockState(
s_seasonUnlockStartTimes[seasonId], config.unlockDelay, config.unlockDuration, block.timestamp
);
if (unlockState.isUnlocking || unlockState.isBeforeUnlock) {
revert SeasonNotReadyForRefund(token, seasonId);
}
config.isRefunding = true;
uint256 refundEligible = s_refundableAmounts[token][seasonId];
uint256 totalLoyaltyRefundEligible =
_getTotalLoyaltyRefundEligible(token, seasonId, config.tokenAmount, refundEligible);
s_tokenAmounts[token].totalRefunded += refundEligible + totalLoyaltyRefundEligible;
emit ProjectSeasonRefundStarted(token, seasonId, s_tokenAmounts[token].totalRefunded);
}
/// @notice Returns the loyalty token amount for users who are eligible for refunds
/// @param token The project token address
/// @param seasonId The season id
/// @param tokenAmount The project token amount for the season
/// @param refundEligible The amount of tokens that can be refunded to the project for the season
/// @return The loyalty token amount for users who are eligible for refunds
function _getTotalLoyaltyRefundEligible(
address token,
uint256 seasonId,
uint256 tokenAmount,
uint256 refundEligible
) internal view returns (uint256) {
uint256[] memory seasonIdArr = new uint256[](1);
seasonIdArr[0] = seasonId;
IBUILDClaim.GlobalState[] memory globalState =
s_projects[token].claim.getGlobalState(seasonIdArr);
if (globalState[0].totalLoyalty == 0) {
return 0;
}
// By definition tokenAmount is always greater than or equal to totalLoyaltyIneligible
uint256 totalLoyaltyEligible = tokenAmount - globalState[0].totalLoyaltyIneligible;
// no loyalty eligible, entire loyalty pool is refundable
if (totalLoyaltyEligible == 0) {
return globalState[0].totalLoyalty;
}
return globalState[0].totalLoyalty * refundEligible / totalLoyaltyEligible;
}
/// @inheritdoc IBUILDFactory
function isRefunding(address token, uint256 seasonId) external view override returns (bool) {
return s_projectSeasonConfigs[token][seasonId].isRefunding;
}
/// @inheritdoc IBUILDFactory
function getRefundableAmount(
address token,
uint256 seasonId
) external view override returns (uint256) {
ProjectSeasonConfig memory config = s_projectSeasonConfigs[token][seasonId];
uint256 refundEligible = s_refundableAmounts[token][seasonId];
uint256 totalLoyaltyRefundEligible =
_getTotalLoyaltyRefundEligible(token, seasonId, config.tokenAmount, refundEligible);
return s_refundableAmounts[token][seasonId] + totalLoyaltyRefundEligible;
}
/// @inheritdoc IBUILDFactory
function calcMaxAvailableAmount(
address token
) external view override returns (uint256) {
return _calcMaxAvailableForWithdrawalOrNewSeason(s_tokenAmounts[token]);
}
/// @notice Calculates the maximum available amount that can be used for allocation to a new
/// season or withdrawn
/// @param tokenAmounts The project's token amounts
function _calcMaxAvailableForWithdrawalOrNewSeason(
TokenAmounts memory tokenAmounts
) private pure returns (uint256) {
return tokenAmounts.totalDeposited + tokenAmounts.totalRefunded - tokenAmounts.totalWithdrawn
- tokenAmounts.totalAllocatedToAllSeasons;
}
// ================================================================
// | Token Withdrawals |
// ================================================================
/// @inheritdoc IBUILDFactory
function scheduleWithdraw(
address token,
address recipient,
uint256 amount
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
if (recipient == address(0)) {
revert InvalidWithdrawalRecipient(recipient);
}
if (s_withdrawals[token].amount != 0) {
// an entry is already pending – must be cancelled first
revert WithdrawalAlreadyScheduled(token, s_withdrawals[token].amount);
}
_validateNewWithdrawal(token, amount);
s_withdrawals[token] = Withdrawal({recipient: recipient, amount: amount});
emit WithdrawalScheduled(token, recipient, amount);
}
/// @inheritdoc IBUILDFactory
function cancelWithdraw(
address token
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
Withdrawal memory withdrawal = s_withdrawals[token];
if (withdrawal.recipient == address(0) || withdrawal.amount == 0) {
revert WithdrawalDoesNotExist(token);
}
delete s_withdrawals[token];
emit WithdrawalCancelled(token, withdrawal.recipient, withdrawal.amount);
}
/// @inheritdoc IBUILDFactory
function executeWithdraw(
address token
) external override returns (IBUILDFactory.Withdrawal memory, uint256) {
_requireRegisteredClaim(token);
BUILDFactory.Withdrawal memory withdrawal = s_withdrawals[token];
if (withdrawal.recipient == address(0) || withdrawal.amount == 0) {
revert WithdrawalDoesNotExist(token);
}
_validateNewWithdrawal(token, withdrawal.amount);
s_tokenAmounts[token].totalWithdrawn += withdrawal.amount;
delete s_withdrawals[token];
emit WithdrawalExecuted(
token, withdrawal.recipient, withdrawal.amount, s_tokenAmounts[token].totalWithdrawn
);
return (withdrawal, s_tokenAmounts[token].totalWithdrawn);
}
/// @inheritdoc IBUILDFactory
function getScheduledWithdrawal(
address token
) external view override returns (Withdrawal memory) {
return s_withdrawals[token];
}
/// @notice Checks if the withdrawal amount is valid
/// @dev Throws if the amount is zero or the project does not have enough tokens to withdraw the
/// amount
/// @param token The project token address
/// @param amount The withdrawal amount
function _validateNewWithdrawal(address token, uint256 amount) private view {
// Use != 0 instead of > 0 for unsigned integer comparison
if ((isClaimContractPaused(token) || !s_isOpen) && amount != 0) {
// If the claim contract is emergency paused or factory is closed, we bypass the available
// amount validation and allow the project to withdraw the remaining tokens.
return;
}
uint256 maxAvailable = _calcMaxAvailableForWithdrawalOrNewSeason(s_tokenAmounts[token]);
if (amount == 0 || amount > maxAvailable) {
revert InvalidWithdrawalAmount(amount, maxAvailable);
}
}
// ================================================================
// | Pausing Projects |
// ================================================================
/// @inheritdoc IBUILDFactory
function pauseClaimContract(
address token
) external override onlyRole(PAUSER_ROLE) {
if (s_claimPaused[token]) {
revert EnforcedPause();
}
_ensureProjectExists(token);
s_claimPaused[token] = true;
emit ClaimPaused(token);
}
/// @inheritdoc IBUILDFactory
function unpauseClaimContract(
address token
) external override onlyRole(PAUSER_ROLE) {
if (!isClaimContractPaused(token)) {
revert ExpectedPause();
}
_ensureProjectExists(token);
s_claimPaused[token] = false;
emit ClaimUnpaused(token);
}
/// @inheritdoc IBUILDFactory
function isClaimContractPaused(
address token
) public view override returns (bool) {
return paused() || s_claimPaused[token];
}
/// @notice throws if the claims contract or factory is paused.
/// @param token address of the project token
function _requireClaimNotPaused(
address token
) internal view virtual {
if (isClaimContractPaused(token)) {
revert EnforcedPause();
}
}
/// @notice throws if the project does not exist.
/// @param token address of the project token
function _ensureProjectExists(
address token
) internal view {
if (!s_projectsList.contains(token)) revert ProjectDoesNotExist(token);
}
/// ================================================================
/// | Delegate Registry |
/// ================================================================
/// @notice Returns the address of the Delegate Registry contract
/// @return The address of the Delegate Registry contract
function getDelegateRegistry() external view returns (address) {
return i_delegateRegistry;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @notice Abstract contract that adds closing functionality
abstract contract Closable {
/// @notice This event is emitted when the factory is closed
event Closed();
/// @notice This error is thrown when attempting to close and the factory is already closed
error AlreadyClosed();
/// @notice Whether the contract is open for depositing and claiming
bool internal s_isOpen = true;
/// @notice Closes the factory. Irreversible.
/// Only callable by the default admin
function _close() internal whenOpen {
s_isOpen = false;
emit Closed();
}
/// @notice Returns whether the contract is open or closed
/// @return True if the contract is open
function isOpen() external view returns (bool) {
return s_isOpen;
}
/// @notice Modifier to check if the contract is open
/// @dev Throws AlreadyClosed if the contract is closed
modifier whenOpen() {
if (!s_isOpen) revert AlreadyClosed();
_;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
/// @notice The unlock state for a season at a given time
struct UnlockState {
uint256 unlockElapsedDuration; // The amount of time that has elapsed since
// the unlock delay started
bool isBeforeUnlock; // Whether the unlock period has started (including the delay)
bool isUnlocking; // Whether the unlock period is in progress
}
/// @notice Returns the unlock progress for a season
/// @param unlockStartsAt The timestamp when the unlock period starts
/// @param unlockDelay The delay before the unlock period starts
/// @param unlockDuration The duration of the unlock period
/// @param targetTime The timestamp to evaluate the unlock progress at
/// @return UnlockState The unlock state for the target time
function getUnlockState(
uint256 unlockStartsAt,
uint256 unlockDelay,
uint256 unlockDuration,
uint256 targetTime
) pure returns (UnlockState memory) {
uint256 unlockDelayEndsAt = unlockStartsAt + unlockDelay;
if (targetTime < unlockDelayEndsAt) {
return UnlockState({isBeforeUnlock: true, isUnlocking: false, unlockElapsedDuration: 0});
}
return UnlockState({
isBeforeUnlock: false,
isUnlocking: unlockDuration > 0 && targetTime < unlockDelayEndsAt + unlockDuration,
unlockElapsedDuration: targetTime - unlockDelayEndsAt
});
}// SPDX-License-Identifier: MIT
// Vendor: https://github.com/Vectorized/solady/tree/4c895b961d45c53a49ed500cfc76868b7ee1328b
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate
/// (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero
/// checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero
/// checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(
int256 x
) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r =
int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(
int256 x
) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(
int256 x
) internal pure returns (int256 w) {
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(
uint256 a,
uint256 b,
uint256 x,
uint256 y
) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z :=
mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z :=
mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(
uint256 x
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(
uint256 x
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(
uint256 x
) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(
uint256 x
) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns the factorial of `x`.
function factorial(
uint256 x
) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(
uint256 x
) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(
uint256 x
) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(
uint256 x
) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(
uint256 x
) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(
uint256 x
) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(
uint256 x
) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(
uint256 x
) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(
uint256 x
) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(
uint256 packed
) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(
int256 x
) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(
uint256 a,
uint256 b,
uint256 t,
uint256 begin,
uint256 end
) internal pure returns (uint256) {
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begins == end`, returns `t <= begin ? a : b`.
function lerp(
int256 a,
int256 b,
int256 t,
int256 begin,
int256 end
) internal pure returns (int256) {
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(
uint256 x
) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}// SPDX-License-Identifier: CC0-1.0
pragma solidity >=0.8.13;
/**
* @title IDelegateRegistry
* @custom:version 2.0
* @custom:author foobar (0xfoobar)
* @notice A standalone immutable registry storing delegated permissions from one address to another
*/
interface IDelegateRegistry {
/// @notice Delegation type, NONE is used when a delegation does not exist or is revoked
enum DelegationType {
NONE,
ALL,
CONTRACT,
ERC721,
ERC20,
ERC1155
}
/// @notice Struct for returning delegations
struct Delegation {
DelegationType type_;
address to;
address from;
bytes32 rights;
address contract_;
uint256 tokenId;
uint256 amount;
}
/// @notice Emitted when an address delegates or revokes rights for their entire wallet
event DelegateAll(address indexed from, address indexed to, bytes32 rights, bool enable);
/// @notice Emitted when an address delegates or revokes rights for a contract address
event DelegateContract(
address indexed from, address indexed to, address indexed contract_, bytes32 rights, bool enable
);
/// @notice Emitted when an address delegates or revokes rights for an ERC721 tokenId
event DelegateERC721(
address indexed from,
address indexed to,
address indexed contract_,
uint256 tokenId,
bytes32 rights,
bool enable
);
/// @notice Emitted when an address delegates or revokes rights for an amount of ERC20 tokens
event DelegateERC20(
address indexed from,
address indexed to,
address indexed contract_,
bytes32 rights,
uint256 amount
);
/// @notice Emitted when an address delegates or revokes rights for an amount of an ERC1155
/// tokenId
event DelegateERC1155(
address indexed from,
address indexed to,
address indexed contract_,
uint256 tokenId,
bytes32 rights,
uint256 amount
);
/// @notice Thrown if multicall calldata is malformed
error MulticallFailed();
/**
* ----------- WRITE -----------
*/
/**
* @notice Call multiple functions in the current contract and return the data from all of them if
* they all succeed
* @param data The encoded function data for each of the calls to make to this contract
* @return results The results from each of the calls passed in via data
*/
function multicall(
bytes[] calldata data
) external payable returns (bytes[] memory results);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for all contracts
* @param to The address to act as delegate
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring
* to encompass all rights
* @param enable Whether to enable or disable this delegation, true delegates and false revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateAll(
address to,
bytes32 rights,
bool enable
) external payable returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific contract
* @param to The address to act as delegate
* @param contract_ The contract whose rights are being delegated
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring
* to encompass all rights
* @param enable Whether to enable or disable this delegation, true delegates and false revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateContract(
address to,
address contract_,
bytes32 rights,
bool enable
) external payable returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific ERC721 token
* @param to The address to act as delegate
* @param contract_ The contract whose rights are being delegated
* @param tokenId The token id to delegate
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring
* to encompass all rights
* @param enable Whether to enable or disable this delegation, true delegates and false revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateERC721(
address to,
address contract_,
uint256 tokenId,
bytes32 rights,
bool enable
) external payable returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific amount of ERC20
* tokens
* @dev The actual amount is not encoded in the hash, just the existence of a amount (since it is
* an upper bound)
* @param to The address to act as delegate
* @param contract_ The address for the fungible token contract
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring
* to encompass all rights
* @param amount The amount to delegate, > 0 delegates and 0 revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateERC20(
address to,
address contract_,
bytes32 rights,
uint256 amount
) external payable returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific amount of ERC1155
* tokens
* @dev The actual amount is not encoded in the hash, just the existence of a amount (since it is
* an upper bound)
* @param to The address to act as delegate
* @param contract_ The address of the contract that holds the token
* @param tokenId The token id to delegate
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring
* to encompass all rights
* @param amount The amount of that token id to delegate, > 0 delegates and 0 revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateERC1155(
address to,
address contract_,
uint256 tokenId,
bytes32 rights,
uint256 amount
) external payable returns (bytes32 delegationHash);
/**
* ----------- CHECKS -----------
*/
/**
* @notice Check if `to` is a delegate of `from` for the entire wallet
* @param to The potential delegate address
* @param from The potential address who delegated rights
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and
* check full delegations only
* @return valid Whether delegate is granted to act on the from's behalf
*/
function checkDelegateForAll(
address to,
address from,
bytes32 rights
) external view returns (bool);
/**
* @notice Check if `to` is a delegate of `from` for the specified `contract_` or the entire
* wallet
* @param to The delegated address to check
* @param contract_ The specific contract address being checked
* @param from The cold wallet who issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and
* check full delegations only
* @return valid Whether delegate is granted to act on from's behalf for entire wallet or that
* specific contract
*/
function checkDelegateForContract(
address to,
address from,
address contract_,
bytes32 rights
) external view returns (bool);
/**
* @notice Check if `to` is a delegate of `from` for the specific `contract` and `tokenId`, the
* entire `contract_`, or the entire wallet
* @param to The delegated address to check
* @param contract_ The specific contract address being checked
* @param tokenId The token id for the token to delegating
* @param from The wallet that issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and
* check full delegations only
* @return valid Whether delegate is granted to act on from's behalf for entire wallet, that
* contract, or that specific tokenId
*/
function checkDelegateForERC721(
address to,
address from,
address contract_,
uint256 tokenId,
bytes32 rights
) external view returns (bool);
/**
* @notice Returns the amount of ERC20 tokens the delegate is granted rights to act on the behalf
* of
* @param to The delegated address to check
* @param contract_ The address of the token contract
* @param from The cold wallet who issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and
* check full delegations only
* @return balance The delegated balance, which will be 0 if the delegation does not exist
*/
function checkDelegateForERC20(
address to,
address from,
address contract_,
bytes32 rights
) external view returns (uint256);
/**
* @notice Returns the amount of a ERC1155 tokens the delegate is granted rights to act on the
* behalf of
* @param to The delegated address to check
* @param contract_ The address of the token contract
* @param tokenId The token id to check the delegated amount of
* @param from The cold wallet who issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and
* check full delegations only
* @return balance The delegated balance, which will be 0 if the delegation does not exist
*/
function checkDelegateForERC1155(
address to,
address from,
address contract_,
uint256 tokenId,
bytes32 rights
) external view returns (uint256);
/**
* ----------- ENUMERATIONS -----------
*/
/**
* @notice Returns all enabled delegations a given delegate has received
* @param to The address to retrieve delegations for
* @return delegations Array of Delegation structs
*/
function getIncomingDelegations(
address to
) external view returns (Delegation[] memory delegations);
/**
* @notice Returns all enabled delegations an address has given out
* @param from The address to retrieve delegations for
* @return delegations Array of Delegation structs
*/
function getOutgoingDelegations(
address from
) external view returns (Delegation[] memory delegations);
/**
* @notice Returns all hashes associated with enabled delegations an address has received
* @param to The address to retrieve incoming delegation hashes for
* @return delegationHashes Array of delegation hashes
*/
function getIncomingDelegationHashes(
address to
) external view returns (bytes32[] memory delegationHashes);
/**
* @notice Returns all hashes associated with enabled delegations an address has given out
* @param from The address to retrieve outgoing delegation hashes for
* @return delegationHashes Array of delegation hashes
*/
function getOutgoingDelegationHashes(
address from
) external view returns (bytes32[] memory delegationHashes);
/**
* @notice Returns the delegations for a given array of delegation hashes
* @param delegationHashes is an array of hashes that correspond to delegations
* @return delegations Array of Delegation structs, return empty structs for nonexistent or
* revoked delegations
*/
function getDelegationsFromHashes(
bytes32[] calldata delegationHashes
) external view returns (Delegation[] memory delegations);
/**
* ----------- STORAGE ACCESS -----------
*/
/**
* @notice Allows external contracts to read arbitrary storage slots
*/
function readSlot(
bytes32 location
) external view returns (bytes32);
/**
* @notice Allows external contracts to read an arbitrary array of storage slots
*/
function readSlots(
bytes32[] calldata locations
) external view returns (bytes32[] memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.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 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);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @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());
}
}// 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;
}
}// 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];
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(
bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role
* (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(
bytes32 role
) external view returns (bytes32);
/**
* @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.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @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 granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// 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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override
* {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(
bytes4 interfaceId
) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;
import {Closable} from "./Closable.sol";
import {AccessControlDefaultAdminRules} from
"@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
/// @notice Base contract that adds pausing, closing, and access control functionality.
abstract contract ManagedAccessControl is Pausable, Closable, AccessControlDefaultAdminRules {
/// @notice This is the ID for the pauser role, which is given to the addresses that can pause and
/// unpause the contract.
/// @dev Hash: 65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor(
uint48 adminRoleTransferDelay,
address admin
) AccessControlDefaultAdminRules(adminRoleTransferDelay, admin) {}
/// @notice This function pauses the contract
/// @dev Sets the pause flag to true
function emergencyPause() external onlyRole(PAUSER_ROLE) {
_pause();
}
/// @notice This function unpauses the contract
/// @dev Sets the pause flag to false
function emergencyUnpause() external onlyRole(PAUSER_ROLE) {
_unpause();
}
/// @notice Closes the contract
/// @dev This is an irreversible operation
/// @dev Only callable by the default admin
/// @dev Only callable when the contract is open
function close() external onlyRole(DEFAULT_ADMIN_ROLE) {
_close();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering
* the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a
* fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the
// last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(
Set storage set
) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive.
* This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should
* keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may
* render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in
* a block.
*/
function _values(
Set storage set
) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(
Bytes32Set storage set
) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive.
* This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should
* keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may
* render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in
* a block.
*/
function values(
Bytes32Set storage set
) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(
AddressSet storage set
) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive.
* This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should
* keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may
* render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in
* a block.
*/
function values(
AddressSet storage set
) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(
UintSet storage set
) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive.
* This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should
* keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may
* render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in
* a block.
*/
function values(
UintSet storage set
) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions
* pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success,) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use
* https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(
address target,
bytes memory data
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the
* target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in
* case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by
* bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(
bool success,
bytes memory returndata
) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(
bytes memory returndata
) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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) private pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0)
// (access/extensions/AccessControlDefaultAdminRules.sol)
pragma solidity ^0.8.20;
import {IAccessControlDefaultAdminRules} from "./IAccessControlDefaultAdminRules.sol";
import {AccessControl, IAccessControl} from "../AccessControl.sol";
import {SafeCast} from "../../utils/math/SafeCast.sol";
import {Math} from "../../utils/math/Math.sol";
import {IERC5313} from "../../interfaces/IERC5313.sol";
/**
* @dev Extension of {AccessControl} that allows specifying special rules to manage
* the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions
* over other roles that may potentially have privileged rights in the system.
*
* If a specific role doesn't have an admin role assigned, the holder of the
* `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it.
*
* This contract implements the following risk mitigations on top of {AccessControl}:
*
* * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially
* renounced.
* * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account.
* * Enforces a configurable delay between the two steps, with the ability to cancel before the
* transfer is accepted.
* * The delay can be changed by scheduling, see {changeDefaultAdminDelay}.
* * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`.
*
* Example usage:
*
* ```solidity
* contract MyToken is AccessControlDefaultAdminRules {
* constructor() AccessControlDefaultAdminRules(
* 3 days,
* msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder
* ) {}
* }
* ```
*/
abstract contract AccessControlDefaultAdminRules is
IAccessControlDefaultAdminRules,
IERC5313,
AccessControl
{
// pending admin pair read/written together frequently
address private _pendingDefaultAdmin;
uint48 private _pendingDefaultAdminSchedule; // 0 == unset
uint48 private _currentDelay;
address private _currentDefaultAdmin;
// pending delay pair read/written together frequently
uint48 private _pendingDelay;
uint48 private _pendingDelaySchedule; // 0 == unset
/**
* @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address.
*/
constructor(uint48 initialDelay, address initialDefaultAdmin) {
if (initialDefaultAdmin == address(0)) {
revert AccessControlInvalidDefaultAdmin(address(0));
}
_currentDelay = initialDelay;
_grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(
bytes4 interfaceId
) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC5313-owner}.
*/
function owner() public view virtual returns (address) {
return defaultAdmin();
}
///
/// Override AccessControl role management
///
/**
* @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function grantRole(
bytes32 role,
address account
) public virtual override(AccessControl, IAccessControl) {
if (role == DEFAULT_ADMIN_ROLE) {
revert AccessControlEnforcedDefaultAdminRules();
}
super.grantRole(role, account);
}
/**
* @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function revokeRole(
bytes32 role,
address account
) public virtual override(AccessControl, IAccessControl) {
if (role == DEFAULT_ADMIN_ROLE) {
revert AccessControlEnforcedDefaultAdminRules();
}
super.revokeRole(role, account);
}
/**
* @dev See {AccessControl-renounceRole}.
*
* For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling
* {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the
* {pendingDefaultAdmin} schedule
* has also passed when calling this function.
*
* After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions.
*
* NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin},
* thereby disabling any functionality that is only available for it, and the possibility of
* reassigning a
* non-administrated role.
*/
function renounceRole(
bytes32 role,
address account
) public virtual override(AccessControl, IAccessControl) {
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
(address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin();
if (
newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)
) {
revert AccessControlEnforcedDefaultAdminDelay(schedule);
}
delete _pendingDefaultAdminSchedule;
}
super.renounceRole(role, account);
}
/**
* @dev See {AccessControl-_grantRole}.
*
* For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if
* the
* role has been previously renounced.
*
* NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE`
* assignable again. Make sure to guarantee this is the expected behavior in your implementation.
*/
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
if (role == DEFAULT_ADMIN_ROLE) {
if (defaultAdmin() != address(0)) {
revert AccessControlEnforcedDefaultAdminRules();
}
_currentDefaultAdmin = account;
}
return super._grantRole(role, account);
}
/**
* @dev See {AccessControl-_revokeRole}.
*/
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) {
delete _currentDefaultAdmin;
}
return super._revokeRole(role, account);
}
/**
* @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override {
if (role == DEFAULT_ADMIN_ROLE) {
revert AccessControlEnforcedDefaultAdminRules();
}
super._setRoleAdmin(role, adminRole);
}
///
/// AccessControlDefaultAdminRules accessors
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdmin() public view virtual returns (address) {
return _currentDefaultAdmin;
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) {
return (_pendingDefaultAdmin, _pendingDefaultAdminSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdminDelay() public view virtual returns (uint48) {
uint48 schedule = _pendingDelaySchedule;
return
(_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? _pendingDelay : _currentDelay;
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function pendingDefaultAdminDelay()
public
view
virtual
returns (uint48 newDelay, uint48 schedule)
{
schedule = _pendingDelaySchedule;
return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule))
? (_pendingDelay, schedule)
: (0, 0);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) {
return 5 days;
}
///
/// AccessControlDefaultAdminRules public and internal setters for
/// defaultAdmin/pendingDefaultAdmin
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function beginDefaultAdminTransfer(
address newAdmin
) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_beginDefaultAdminTransfer(newAdmin);
}
/**
* @dev See {beginDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _beginDefaultAdminTransfer(
address newAdmin
) internal virtual {
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay();
_setPendingDefaultAdmin(newAdmin, newSchedule);
emit DefaultAdminTransferScheduled(newAdmin, newSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_cancelDefaultAdminTransfer();
}
/**
* @dev See {cancelDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _cancelDefaultAdminTransfer() internal virtual {
_setPendingDefaultAdmin(address(0), 0);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function acceptDefaultAdminTransfer() public virtual {
(address newDefaultAdmin,) = pendingDefaultAdmin();
if (_msgSender() != newDefaultAdmin) {
// Enforce newDefaultAdmin explicit acceptance.
revert AccessControlInvalidDefaultAdmin(_msgSender());
}
_acceptDefaultAdminTransfer();
}
/**
* @dev See {acceptDefaultAdminTransfer}.
*
* Internal function without access restriction.
*/
function _acceptDefaultAdminTransfer() internal virtual {
(address newAdmin, uint48 schedule) = pendingDefaultAdmin();
if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) {
revert AccessControlEnforcedDefaultAdminDelay(schedule);
}
_revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin());
_grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
delete _pendingDefaultAdmin;
delete _pendingDefaultAdminSchedule;
}
///
/// AccessControlDefaultAdminRules public and internal setters for
/// defaultAdminDelay/pendingDefaultAdminDelay
///
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function changeDefaultAdminDelay(
uint48 newDelay
) public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_changeDefaultAdminDelay(newDelay);
}
/**
* @dev See {changeDefaultAdminDelay}.
*
* Internal function without access restriction.
*/
function _changeDefaultAdminDelay(
uint48 newDelay
) internal virtual {
uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay);
_setPendingDelay(newDelay, newSchedule);
emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule);
}
/**
* @inheritdoc IAccessControlDefaultAdminRules
*/
function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) {
_rollbackDefaultAdminDelay();
}
/**
* @dev See {rollbackDefaultAdminDelay}.
*
* Internal function without access restriction.
*/
function _rollbackDefaultAdminDelay() internal virtual {
_setPendingDelay(0, 0);
}
/**
* @dev Returns the amount of seconds to wait after the `newDelay` will
* become the new {defaultAdminDelay}.
*
* The value returned guarantees that if the delay is reduced, it will go into effect
* after a wait that honors the previously set delay.
*
* See {defaultAdminDelayIncreaseWait}.
*/
function _delayChangeWait(
uint48 newDelay
) internal view virtual returns (uint48) {
uint48 currentDelay = defaultAdminDelay();
// When increasing the delay, we schedule the delay change to occur after a period of "new
// delay" has passed, up
// to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if
// increasing from 1 day
// to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10
// days, the new
// delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix
// an error like
// using milliseconds instead of seconds.
//
// When decreasing the delay, we wait the difference between "current delay" and "new delay".
// This guarantees
// that an admin transfer cannot be made faster than "current delay" at the time the delay
// change is scheduled.
// For example, if decreasing from 10 days to 3 days, the new delay will come into effect after
// 7 days.
return newDelay > currentDelay
? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both
// inputs are uint48
: currentDelay - newDelay;
}
///
/// Private setters
///
/**
* @dev Setter of the tuple for pending admin and its schedule.
*
* May emit a DefaultAdminTransferCanceled event.
*/
function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private {
(, uint48 oldSchedule) = pendingDefaultAdmin();
_pendingDefaultAdmin = newAdmin;
_pendingDefaultAdminSchedule = newSchedule;
// An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted.
if (_isScheduleSet(oldSchedule)) {
// Emit for implicit cancellations when another default admin was scheduled.
emit DefaultAdminTransferCanceled();
}
}
/**
* @dev Setter of the tuple for pending delay and its schedule.
*
* May emit a DefaultAdminDelayChangeCanceled event.
*/
function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private {
uint48 oldSchedule = _pendingDelaySchedule;
if (_isScheduleSet(oldSchedule)) {
if (_hasSchedulePassed(oldSchedule)) {
// Materialize a virtual delay
_currentDelay = _pendingDelay;
} else {
// Emit for implicit cancellations when another delay was scheduled.
emit DefaultAdminDelayChangeCanceled();
}
}
_pendingDelay = newDelay;
_pendingDelaySchedule = newSchedule;
}
///
/// Private helpers
///
/**
* @dev Defines if an `schedule` is considered set. For consistency purposes.
*/
function _isScheduleSet(
uint48 schedule
) private pure returns (bool) {
return schedule != 0;
}
/**
* @dev Defines if an `schedule` is considered passed. For consistency purposes.
*/
function _hasSchedulePassed(
uint48 schedule
) private view returns (bool) {
return schedule < block.timestamp;
}
}// 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";// 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";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0)
// (access/extensions/IAccessControlDefaultAdminRules.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "../IAccessControl.sol";
/**
* @dev External interface of AccessControlDefaultAdminRules declared to support ERC-165 detection.
*/
interface IAccessControlDefaultAdminRules is IAccessControl {
/**
* @dev The new default admin is not a valid default admin.
*/
error AccessControlInvalidDefaultAdmin(address defaultAdmin);
/**
* @dev At least one of the following rules was violated:
*
* - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
* - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
* - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
*/
error AccessControlEnforcedDefaultAdminRules();
/**
* @dev The delay for transferring the default admin delay is enforced and
* the operation must wait until `schedule`.
*
* NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
*/
error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);
/**
* @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
* address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after
* `acceptSchedule`
* passes.
*/
event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);
/**
* @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its
* schedule.
*/
event DefaultAdminTransferCanceled();
/**
* @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
* delay to be applied between default admin transfer after `effectSchedule` has passed.
*/
event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);
/**
* @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
*/
event DefaultAdminDelayChangeCanceled();
/**
* @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
*/
function defaultAdmin() external view returns (address);
/**
* @dev Returns a tuple of a `newAdmin` and an accept schedule.
*
* After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
* by calling {acceptDefaultAdminTransfer}, completing the role transfer.
*
* A zero value only in `acceptSchedule` indicates no pending admin transfer.
*
* NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
*/
function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);
/**
* @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer
* started.
*
* This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to
* set
* the acceptance schedule.
*
* NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes,
* making this
* function returns the new delay. See {changeDefaultAdminDelay}.
*/
function defaultAdminDelay() external view returns (uint48);
/**
* @dev Returns a tuple of `newDelay` and an effect schedule.
*
* After the `schedule` passes, the `newDelay` will get into effect immediately for every
* new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
*
* A zero value only in `effectSchedule` indicates no pending delay change.
*
* NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
* will be zero after the effect schedule.
*/
function pendingDefaultAdminDelay()
external
view
returns (uint48 newDelay, uint48 effectSchedule);
/**
* @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for
* acceptance
* after the current timestamp plus a {defaultAdminDelay}.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* Emits a DefaultAdminRoleChangeStarted event.
*/
function beginDefaultAdminTransfer(
address newAdmin
) external;
/**
* @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
*
* A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* May emit a DefaultAdminTransferCanceled event.
*/
function cancelDefaultAdminTransfer() external;
/**
* @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
*
* After calling the function:
*
* - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
* - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
* - {pendingDefaultAdmin} should be reset to zero values.
*
* Requirements:
*
* - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
* - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
*/
function acceptDefaultAdminTransfer() external;
/**
* @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled
* for getting
* into effect after the current timestamp plus a {defaultAdminDelay}.
*
* This function guarantees that any call to {beginDefaultAdminTransfer} done between the
* timestamp this
* method is called and the {pendingDefaultAdminDelay} effect schedule will use the current
* {defaultAdminDelay}
* set before calling.
*
* The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the
* schedule and then
* calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another
* {defaultAdmin}
* complete transfer (including acceptance).
*
* The schedule is designed for two scenarios:
*
* - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay`
* capped by
* {defaultAdminDelayIncreaseWait}.
* - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current
* delay - new delay)`.
*
* A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new
* scheduled change.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled
* event.
*/
function changeDefaultAdminDelay(
uint48 newDelay
) external;
/**
* @dev Cancels a scheduled {defaultAdminDelay} change.
*
* Requirements:
*
* - Only can be called by the current {defaultAdmin}.
*
* May emit a DefaultAdminDelayChangeCanceled event.
*/
function rollbackDefaultAdminDelay() external;
/**
* @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using
* {changeDefaultAdminDelay})
* to take effect. Default to 5 days.
*
* When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new
* delay has passed with
* the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds
* instead of seconds)
* that may lock the contract. However, to avoid excessive schedules, the wait is capped by this
* function and it can
* be overrode for a custom {defaultAdminDelay} increase scheduling.
*
* IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
* there's a risk of setting a high new delay that goes into effect almost immediately without the
* possibility of human intervention in the case of an input error (eg. set milliseconds instead
* of seconds).
*/
function defaultAdminDelayIncreaseWait() external view returns (uint48);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(
uint256 value
) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(
uint256 value
) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(
uint256 value
) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(
uint256 value
) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(
uint256 value
) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(
uint256 value
) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(
uint256 value
) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(
uint256 value
) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(
uint256 value
) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(
uint256 value
) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(
uint256 value
) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(
uint256 value
) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(
uint256 value
) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(
uint256 value
) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(
uint256 value
) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(
uint256 value
) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(
uint256 value
) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(
uint256 value
) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(
uint256 value
) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(
uint256 value
) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(
uint256 value
) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(
uint256 value
) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(
uint256 value
) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(
uint256 value
) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(
uint256 value
) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(
uint256 value
) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(
uint256 value
) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(
uint256 value
) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(
uint256 value
) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(
uint256 value
) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(
uint256 value
) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(
int256 value
) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(
int256 value
) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(
int256 value
) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(
int256 value
) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(
int256 value
) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(
int256 value
) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(
int256 value
) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(
int256 value
) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(
int256 value
) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(
int256 value
) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(
int256 value
) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(
int256 value
) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(
int256 value
) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(
int256 value
) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(
int256 value
) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(
int256 value
) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(
int256 value
) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(
int256 value
) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(
int256 value
) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(
int256 value
) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(
int256 value
) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(
int256 value
) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(
int256 value
) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(
int256 value
) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(
int256 value
) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(
int256 value
) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(
int256 value
) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(
int256 value
) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(
int256 value
) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(
int256 value
) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(
int256 value
) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(
int256 value
) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(
uint256 value
) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(
bool b
) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division
* by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only
* compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a
* uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with
* further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶
// - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in
// two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See
// https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of
// denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse
// modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed
// that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting
// lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of
// denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee
// that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of
// the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding
* direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
return mulDiv(x, y, denominator)
+ SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little
* theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater
* than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know
* that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which
* means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e %
* m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function,
* make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be
* incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e %
* m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as
* failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make
* sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05
* as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will
* succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(
uint256 b,
uint256 e,
uint256 m
) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b |
// 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e |
// 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m |
// 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b |
// 0x<.............................................................b> |
// | 0x80:0x9f | value of e |
// 0x<.............................................................e> |
// | 0xa0:0xbf | value of m |
// 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(
bytes memory byteArray
) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is
* rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted
* to only
* using integer operations.
*/
function sqrt(
uint256 a
) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves
// building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the
// error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the
// square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because
// `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a
// method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n
// ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the
// error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k =
// 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a
// precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is
// now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(
uint256 value
) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(
uint256 value
) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value`
* as a hex string.
*/
function log256(
uint256 value
) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive
* value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(
Rounding rounding
) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5313.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface for the Light Contract Ownership Standard.
*
* A standardized minimal interface required to identify an account that controls a contract
*/
interface IERC5313 {
/**
* @dev Gets the address of the owner.
*/
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from
* https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(
uint256 code
) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}{
"remappings": [
"@openzeppelin/=lib/vendor/openzeppelin-solidity/v5.1.0/",
"@openzeppelin@5.2.0/=lib/vendor/openzeppelin-solidity/v5.2.0/",
"@solady/=lib/vendor/solady/",
"chainlink/=lib/vendor/chainlink/v2.18.0/",
"forge-std/=lib/vendor/forge-std/v1.9.4/src/",
"space-and-time/=lib/vendor/space-and-time/",
"@delegatexyz/=lib/vendor/delegatexyz/",
"vendor/=lib/vendor/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"delegateRegistry","type":"address"},{"internalType":"address","name":"multicall3","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"AlreadyClosed","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[{"internalType":"uint256","name":"balanceBefore","type":"uint256"},{"internalType":"uint256","name":"balanceAfter","type":"uint256"}],"name":"InvalidDeposit","type":"error"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"seasonId","type":"uint256"}],"name":"InvalidEarlyClaim","type":"error"},{"inputs":[],"name":"InvalidMerkleProof","type":"error"},{"inputs":[{"internalType":"address","name":"msgSender","type":"address"}],"name":"InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"InvalidUser","type":"error"},{"inputs":[{"internalType":"uint256","name":"seasonId","type":"uint256"},{"internalType":"address","name":"token","type":"address"}],"name":"ProjectSeasonDoesNotExist","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"seasonId","type":"uint256"}],"name":"ProjectSeasonIsRefunding","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"seasonId","type":"uint256"}],"name":"SeasonDoesNotExist","type":"error"},{"inputs":[{"internalType":"uint256","name":"seasonId","type":"uint256"}],"name":"UnlockNotStarted","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"seasonId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isEarlyClaim","type":"bool"},{"indexed":false,"internalType":"uint256","name":"earlyVestAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"userClaimedInSeason","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalClaimedInSeason","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalLoyaltyAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalLoyaltyIneligibleAmount","type":"uint256"}],"name":"Claimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalDeposit","type":"uint256"}],"name":"Deposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalWithdrawn","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"components":[{"internalType":"uint32","name":"seasonId","type":"uint32"},{"internalType":"bool","name":"isEarlyClaim","type":"bool"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"uint256","name":"maxTokenAmount","type":"uint256"},{"internalType":"uint256","name":"salt","type":"uint256"}],"internalType":"struct IBUILDClaim.ClaimParams[]","name":"params","type":"tuple[]"}],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"components":[{"internalType":"uint256","name":"seasonId","type":"uint256"},{"internalType":"uint256","name":"maxTokenAmount","type":"uint256"}],"internalType":"struct IBUILDClaim.SeasonIdAndMaxTokenAmount[]","name":"seasonIdsAndMaxTokenAmounts","type":"tuple[]"}],"name":"getCurrentClaimValues","outputs":[{"components":[{"internalType":"uint256","name":"base","type":"uint256"},{"internalType":"uint256","name":"bonus","type":"uint256"},{"internalType":"uint256","name":"vested","type":"uint256"},{"internalType":"uint256","name":"claimable","type":"uint256"},{"internalType":"uint256","name":"earlyVestableBonus","type":"uint256"},{"internalType":"uint256","name":"loyaltyBonus","type":"uint256"},{"internalType":"uint256","name":"claimed","type":"uint256"}],"internalType":"struct IBUILDClaim.ClaimableState[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFactory","outputs":[{"internalType":"contract BUILDFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"seasonIds","type":"uint256[]"}],"name":"getGlobalState","outputs":[{"components":[{"internalType":"uint256","name":"totalLoyalty","type":"uint256"},{"internalType":"uint256","name":"totalLoyaltyIneligible","type":"uint256"},{"internalType":"uint256","name":"totalClaimed","type":"uint256"}],"internalType":"struct IBUILDClaim.GlobalState[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"seasonId","type":"uint256"}],"internalType":"struct IBUILDClaim.UserSeasonId[]","name":"usersAndSeasonIds","type":"tuple[]"}],"name":"getUserState","outputs":[{"components":[{"internalType":"uint248","name":"claimed","type":"uint248"},{"internalType":"bool","name":"hasEarlyClaimed","type":"bool"}],"internalType":"struct IBUILDClaim.UserState[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"typeAndVersion","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
0x610100604052348015610010575f80fd5b506040516126a23803806126a283398101604081905261002f9161006f565b60015f556001600160a01b039283166080523360a05290821660c0521660e0526100af565b80516001600160a01b038116811461006a575f80fd5b919050565b5f805f60608486031215610081575f80fd5b61008a84610054565b925061009860208501610054565b91506100a660408501610054565b90509250925092565b60805160a05160c05160e0516124f56101ad5f395f61141e01525f6113a301525f81816101bc015281816103ad01528181610613015281816108060152818161090701528181610a8401528181610b4a01528181610c0501528181610d7301528181610ffc01528181611211015261137501525f818161015a01528181610385015281816105cb015281816107de015281816108db0152818161098c015281816109c201528181610a5c01528181610b2201528181610cb701528181610d3f01528181610dec01528181610e2b01528181610ee301528181610fc3015281816111d40152818161147b0152818161180a015261190401526124f55ff3fe608060405234801561000f575f80fd5b506004361061009b575f3560e01c806321df0da71161006357806321df0da71461015857806330b338aa146101925780633ccfd60b146101b257806388cc58e4146101ba578063b6b55f25146101e0575f80fd5b806301ffc9a71461009f5780630afad777146100c75780631720c211146100e7578063181f5a77146100fc5780631ffa8efa14610138575b5f80fd5b6100b26100ad366004611cef565b6101f3565b60405190151581526020015b60405180910390f35b6100da6100d5366004611d5d565b610229565b6040516100be9190611d9b565b6100fa6100f5366004611e48565b610366565b005b61012b6040518060400160405280601081526020016f04255494c44436c61696d20312e302e360841b81525081565b6040516100be9190611e98565b61014b610146366004611ecd565b610455565b6040516100be9190611eff565b7f00000000000000000000000000000000000000000000000000000000000000005b6040516001600160a01b0390911681526020016100be565b6101a56101a0366004611f52565b610546565b6040516100be9190611f95565b6100fa6107bf565b7f000000000000000000000000000000000000000000000000000000000000000061017a565b6100fa6101ee366004612010565b610a3d565b5f6001600160e01b031982166311fa7f5b60e01b148061022357506001600160e01b031982166301ffc9a760e01b145b92915050565b6060815f816001600160401b0381111561024557610245612027565b60405190808252806020026020018201604052801561028957816020015b604080518082019091525f80825260208201528152602001906001900390816102635790505b5090505f5b8281101561035d5760015f8787848181106102ab576102ab61203b565b6102c1926020604090920201908101915061204f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f8787848181106102f3576102f361203b565b6020604091820293909301830135845283830194909452509082015f208251808401909352546001600160f81b038116835260ff600160f81b90910416151590820152825183908390811061034a5761034a61203b565b602090810291909101015260010161028e565b50949350505050565b61036e610f46565b604051638c52c16160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f00000000000000000000000000000000000000000000000000000000000000001690638c52c16190602401602060405180830381865afa1580156103f2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104169190612087565b156104345760405163d93c066560e01b815260040160405180910390fd5b6104478361044283856121c1565b610f6e565b61045060015f55565b505050565b6060815f816001600160401b0381111561047157610471612027565b6040519080825280602002602001820160405280156104c357816020015b6104b060405180606001604052805f81526020015f81526020015f81525090565b81526020019060019003908161048f5790505b5090505f5b8281101561035d5760025f8787848181106104e5576104e561203b565b9050602002013581526020019081526020015f206040518060600160405290815f8201548152602001600182015481526020016002820154815250508282815181106105335761053361203b565b60209081029190910101526001016104c8565b6060815f816001600160401b0381111561056257610562612027565b60405190808252806020026020018201604052801561059b57816020015b610588611cb9565b8152602001906001900390816105805790505b5090505f5b828110156107b5575f8686838181106105bb576105bb61203b565b60408051630c5419e360e11b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0390811660048301529190920293909301356024820181905293505f928392507f000000000000000000000000000000000000000000000000000000000000000016906318a833c69060440161012060405180830381865afa158015610659573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061067d91906122be565b915091505f6106a482846040015164ffffffffff16856060015164ffffffffff16426114a9565b90506107898360025f8781526020019081526020015f206040518060600160405290815f82015481526020016001820154815260200160028201548152505060015f8f6001600160a01b03166001600160a01b031681526020019081526020015f205f8881526020019081526020015f206040518060400160405290815f82015f9054906101000a90046001600160f81b03166001600160f81b03166001600160f81b031681526020015f8201601f9054906101000a900460ff161515151581525050848e8e8b81811061077a5761077a61203b565b90506040020160200135611545565b86868151811061079b5761079b61203b565b6020026020010181905250505050508060010190506105a0565b5095945050505050565b6107c7610f46565b60405163dd4c74c160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063dd4c74c1906024016040805180830381865afa15801561084a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061086e919061236d565b516001600160a01b031633146108c45760405163e2517d3f60e01b81523360048201527f43d5f2668bd1c7628e58e967bbd8b63f1feac3fe0c46b06ccf42fdd0dc6cc15060248201526044015b60405180910390fd5b604051634313878960e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9182917f000000000000000000000000000000000000000000000000000000000000000016906343138789906024016060604051808303815f875af115801561094d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061097191906123ae565b815160208301519294509092506109b3916001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691906116b3565b815f01516001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03167f91fb9d98b786c57d74c099ccd2beca1739e9f6a81fb49001ca465c4b7591bbe2846020015184604051610a28929190918252602082015260400190565b60405180910390a35050610a3b60015f55565b565b610a45610f46565b604051638c52c16160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f00000000000000000000000000000000000000000000000000000000000000001690638c52c16190602401602060405180830381865afa158015610ac9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610aed9190612087565b15610b0b5760405163d93c066560e01b815260040160405180910390fd5b60405163dd4c74c160e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063dd4c74c1906024016040805180830381865afa158015610b8e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bb2919061236d565b516001600160a01b03163314610c035760405163e2517d3f60e01b81523360048201527f43d5f2668bd1c7628e58e967bbd8b63f1feac3fe0c46b06ccf42fdd0dc6cc15060248201526044016108bb565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166347535d7b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c5f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c839190612087565b610ca057604051634d65bf2960e11b815260040160405180910390fd5b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610d04573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d2891906123fc565b604051639380d40560e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166004830152602482018590529192505f917f00000000000000000000000000000000000000000000000000000000000000001690639380d405906044016020604051808303815f875af1158015610db9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ddd91906123fc565b9050610e146001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016333086611712565b6040516370a0823160e01b81523060048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610e78573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e9c91906123fc565b905080610ea98585612427565b14610ed157604051633bfb3e2360e11b815260048101849052602481018290526044016108bb565b604080518581526020810184905233917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316917ff5681f9d0db1b911ac18ee83d515a1cf1051853a9eae418316a2fdf7dea427c5910160405180910390a3505050610f4360015f55565b50565b60025f5403610f6857604051633ee5aeb560e01b815260040160405180910390fd5b60025f55565b80515f908190815b81811015611334575f858281518110610f9157610f9161203b565b60200260200101519050806020015115610faa57600193505b8051604051630c5419e360e11b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015263ffffffff90921660248201525f9182917f0000000000000000000000000000000000000000000000000000000000000000909116906318a833c69060440161012060405180830381865afa158015611044573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061106891906122be565b6001600160a01b038b165f908152600160209081526040808320885163ffffffff16845282528083208151808301835290546001600160f81b0381168252600160f81b900460ff1615159281019290925284015160608501519496509294509290916110e191859164ffffffffff9081169116426114a9565b90506110f18b8387878786611751565b81602001511561110557505050505061132c565b5f60025f875f015163ffffffff1681526020019081526020015f2090505f61115c86836040518060600160405290815f82015481526020016001820154815260200160028201548152505086868b60600151611545565b905080606001515f14801561117357508660200151155b8061119a5750606081015115801561118d57506080810151155b801561119a575086602001515b156111ab575050505050505061132c565b8060c001515f0361126b5786516060880151604051630df4b04f60e41b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015263ffffffff909316602482015260448101919091527f00000000000000000000000000000000000000000000000000000000000000009091169063df4b04f0906064015f604051808303815f87803b158015611254575f80fd5b505af1158015611266573d5f803e3d5ffd5b505050505b606081015160408401518015611282575087602001515b156112f6578160800151826040015183602001516112a0919061243a565b6112aa919061243a565b835f015f8282546112bb9190612427565b909155505060608801516001840180545f906112d8908490612427565b90915550506001602086015260808201516112f39082612427565b90505b611300818d612427565b9b506113238e84878b858d60200151611319575f611946565b8760800151611946565b50505050505050505b600101610f76565b5081801561134b57506001600160a01b0385163314155b1561146057604051638988eea960e01b81523360048201526001600160a01b0386811660248301527f0000000000000000000000000000000000000000000000000000000000000000811660448301525f60648301527f00000000000000000000000000000000000000000000000000000000000000001690638988eea990608401602060405180830381865afa1580156113e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061140c9190612087565b15806114405750336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016145b15611460576040516313053d9360e21b81523360048201526024016108bb565b825f0361146e575050505050565b6114a26001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001686856116b3565b5050505050565b604080516060810182525f80825260208201819052918101829052906114cf8587612427565b9050808310156114fc575050604080516060810182525f808252600160208301529181019190915261153d565b60405180606001604052808285611513919061243a565b81525f6020820152604001851580159061153557506115328684612427565b85105b151590529150505b949350505050565b61154d611cb9565b611555611cb9565b6127108760c0015161ffff168461156c919061244d565b6115769190612464565b808252611583908461243a565b6020820152865115806115aa57508660e0015180156115aa575084516001600160f81b0316155b156115b65790506116aa565b84516001600160f81b031660c08201526020850151806115d7575083602001515b156115e35790506116aa565b602086015187516115f4919061243a565b8651611600908561244d565b61160a9190612464565b60a082015260408401511561168357866060015164ffffffffff16845f01518260200151611638919061244d565b6116429190612464565b6040820181905260c08201518251909161165b91612427565b611665919061243a565b606082015283516116799082908990611a56565b60808201526116a7565b60c081015160a08201516116979085612427565b6116a1919061243a565b60608201525b90505b95945050505050565b6040516001600160a01b0383811660248301526044820183905261045091859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611adb565b6040516001600160a01b03848116602483015283811660448301526064820183905261174b9186918216906323b872dd906084016116e0565b50505050565b6001600160a01b03861661178357604051632e86c5bb60e21b81526001600160a01b03871660048201526024016108bb565b815f036117ae578351604051633ae3261b60e01b815263ffffffff90911660048201526024016108bb565b8060200151156117dc5783516040516302bc564f60e01b815263ffffffff90911660048201526024016108bb565b82515f036118375783516040516311fa919f60e21b815263ffffffff90911660048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001660248201526044016108bb565b6118598360200151878660400151876060015188602001518960800151611b47565b6118765760405163582f497d60e11b815260040160405180910390fd5b80604001518015611888575083602001515b8015611895575084602001515b156118cd5783516040516334d28b2d60e21b81526001600160a01b038816600482015263ffffffff90911660248201526044016108bb565b84516001600160f81b03161580156118e657508260e001515b1561193e57835160405163f728cb7360e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016600482015263ffffffff90911660248201526044016108bb565b505050505050565b81845f018181516119579190612483565b6001600160f81b039081169091526001600160a01b0388165f908152600160209081526040808320885163ffffffff168452825282208851918901511515600160f81b0291909316179091556002870180548593509091906119ba908490612427565b9091555050825160208085015186516002890154895460018b01546040805163ffffffff909816885295870189905293151586860152606086018790526001600160f81b03909216608086015260a085015260c084015260e0830152516001600160a01b038816917f83034380a9b075d8b2ba1006ed3ad2e1e1c9e2bb01f697cec908d2adedf62fc991908190036101000190a2505050505050565b5f61153d84604001518560200151611a6e919061243a565b846060015164ffffffffff1684611aa187608001518860a00151611a9291906124a2565b64ffffffffff16612710611bc2565b611aab919061244d565b611ab59190612464565b611acc866080015164ffffffffff16612710611bc2565b611ad69190612427565b611c04565b5f8060205f8451602086015f885af180611afa576040513d5f823e3d81fd5b50505f513d91508115611b11578060011415611b1e565b6001600160a01b0384163b155b1561174b57604051635274afe760e01b81526001600160a01b03851660048201526024016108bb565b604080516001600160a01b03871660208201529081018490528215156060820152608081018290525f90819060a00160408051601f1981840301815282825280516020918201209083015201604051602081830303815290604052805190602001209050611bb6868983611c33565b98975050505050505050565b5f7812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f2283108202611bf257637c5f487d5f526004601cfd5b50670de0b6b3a7640000919091020490565b5f815f1904831115611c23578115611c235763bac65e5b5f526004601cfd5b50670de0b6b3a764000091020490565b5f82611c3f8584611c48565b14949350505050565b5f81815b8451811015611c8257611c7882868381518110611c6b57611c6b61203b565b6020026020010151611c8a565b9150600101611c4c565b509392505050565b5f818310611ca4575f828152602084905260409020611cb2565b5f8381526020839052604090205b9392505050565b6040518060e001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f60208284031215611cff575f80fd5b81356001600160e01b031981168114611cb2575f80fd5b5f8083601f840112611d26575f80fd5b5081356001600160401b03811115611d3c575f80fd5b6020830191508360208260061b8501011115611d56575f80fd5b9250929050565b5f8060208385031215611d6e575f80fd5b82356001600160401b03811115611d83575f80fd5b611d8f85828601611d16565b90969095509350505050565b602080825282518282018190525f918401906040840190835b81811015611de957835180516001600160f81b0316845260209081015115158185015290930192604090920191600101611db4565b509095945050505050565b6001600160a01b0381168114610f43575f80fd5b5f8083601f840112611e18575f80fd5b5081356001600160401b03811115611e2e575f80fd5b6020830191508360208260051b8501011115611d56575f80fd5b5f805f60408486031215611e5a575f80fd5b8335611e6581611df4565b925060208401356001600160401b03811115611e7f575f80fd5b611e8b86828701611e08565b9497909650939450505050565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f8060208385031215611ede575f80fd5b82356001600160401b03811115611ef3575f80fd5b611d8f85828601611e08565b602080825282518282018190525f918401906040840190835b81811015611de957835180518452602081015160208501526040810151604085015250606083019250602084019350600181019050611f18565b5f805f60408486031215611f64575f80fd5b8335611f6f81611df4565b925060208401356001600160401b03811115611f89575f80fd5b611e8b86828701611d16565b602080825282518282018190525f918401906040840190835b81811015611de9578351805184526020810151602085015260408101516040850152606081015160608501526080810151608085015260a081015160a085015260c081015160c08501525060e083019250602084019350600181019050611fae565b5f60208284031215612020575f80fd5b5035919050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561205f575f80fd5b8135611cb281611df4565b8015158114610f43575f80fd5b80516120828161206a565b919050565b5f60208284031215612097575f80fd5b8151611cb28161206a565b60405160a081016001600160401b03811182821017156120c4576120c4612027565b60405290565b60405161010081016001600160401b03811182821017156120c4576120c4612027565b604080519081016001600160401b03811182821017156120c4576120c4612027565b604051601f8201601f191681016001600160401b038111828210171561213757612137612027565b604052919050565b5f6001600160401b0382111561215757612157612027565b5060051b60200190565b5f82601f830112612170575f80fd5b813561218361217e8261213f565b61210f565b8082825260208201915060208360051b8601019250858311156121a4575f80fd5b602085015b838110156107b55780358352602092830192016121a9565b5f6121ce61217e8461213f565b8381526020810190600585901b8401368111156121e9575f80fd5b845b81811015611de95780356001600160401b03811115612208575f80fd5b860160a036829003121561221a575f80fd5b6122226120a2565b813563ffffffff81168114612235575f80fd5b815260208201356122458161206a565b602082015260408201356001600160401b03811115612262575f80fd5b61226e36828501612161565b60408301525060608281013590820152608091820135918101919091528452602093840193016121eb565b805164ffffffffff81168114612082575f80fd5b805161ffff81168114612082575f80fd5b5f808284036101208112156122d1575f80fd5b6101008112156122df575f80fd5b506122e86120ca565b835181526020808501519082015261230260408501612299565b604082015261231360608501612299565b606082015261232460808501612299565b608082015261233560a08501612299565b60a082015261234660c085016122ad565b60c082015261235760e08501612077565b60e0820152610100939093015192949293505050565b5f604082840312801561237e575f80fd5b506123876120ed565b825161239281611df4565b815260208301516123a281611df4565b60208201529392505050565b5f8082840360608112156123c0575f80fd5b60408112156123cd575f80fd5b506123d66120ed565b83516123e181611df4565b81526020848101519082015260409093015192949293505050565b5f6020828403121561240c575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561022357610223612413565b8181038181111561022357610223612413565b808202811582820484141761022357610223612413565b5f8261247e57634e487b7160e01b5f52601260045260245ffd5b500490565b6001600160f81b03818116838216019081111561022357610223612413565b64ffffffffff82811682821603908111156102235761022361241356fea26469706673582212205a33527b9352c08532f922b7a42ed0a82d7f61db02e6062a88748f264ee059fd64736f6c634300081a0033000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb19500000000000000000000000000000000000000447e69651d841bd8d104bed493000000000000000000000000ca11bde05977b3631167028862be2a173976ca11
Deployed Bytecode
0x608060405234801561000f575f80fd5b506004361061009b575f3560e01c806321df0da71161006357806321df0da71461015857806330b338aa146101925780633ccfd60b146101b257806388cc58e4146101ba578063b6b55f25146101e0575f80fd5b806301ffc9a71461009f5780630afad777146100c75780631720c211146100e7578063181f5a77146100fc5780631ffa8efa14610138575b5f80fd5b6100b26100ad366004611cef565b6101f3565b60405190151581526020015b60405180910390f35b6100da6100d5366004611d5d565b610229565b6040516100be9190611d9b565b6100fa6100f5366004611e48565b610366565b005b61012b6040518060400160405280601081526020016f04255494c44436c61696d20312e302e360841b81525081565b6040516100be9190611e98565b61014b610146366004611ecd565b610455565b6040516100be9190611eff565b7f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1955b6040516001600160a01b0390911681526020016100be565b6101a56101a0366004611f52565b610546565b6040516100be9190611f95565b6100fa6107bf565b7f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba61017a565b6100fa6101ee366004612010565b610a3d565b5f6001600160e01b031982166311fa7f5b60e01b148061022357506001600160e01b031982166301ffc9a760e01b145b92915050565b6060815f816001600160401b0381111561024557610245612027565b60405190808252806020026020018201604052801561028957816020015b604080518082019091525f80825260208201528152602001906001900390816102635790505b5090505f5b8281101561035d5760015f8787848181106102ab576102ab61203b565b6102c1926020604090920201908101915061204f565b6001600160a01b03166001600160a01b031681526020019081526020015f205f8787848181106102f3576102f361203b565b6020604091820293909301830135845283830194909452509082015f208251808401909352546001600160f81b038116835260ff600160f81b90910416151590820152825183908390811061034a5761034a61203b565b602090810291909101015260010161028e565b50949350505050565b61036e610f46565b604051638c52c16160e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb195811660048301527f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba1690638c52c16190602401602060405180830381865afa1580156103f2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104169190612087565b156104345760405163d93c066560e01b815260040160405180910390fd5b6104478361044283856121c1565b610f6e565b61045060015f55565b505050565b6060815f816001600160401b0381111561047157610471612027565b6040519080825280602002602001820160405280156104c357816020015b6104b060405180606001604052805f81526020015f81526020015f81525090565b81526020019060019003908161048f5790505b5090505f5b8281101561035d5760025f8787848181106104e5576104e561203b565b9050602002013581526020019081526020015f206040518060600160405290815f8201548152602001600182015481526020016002820154815250508282815181106105335761053361203b565b60209081029190910101526001016104c8565b6060815f816001600160401b0381111561056257610562612027565b60405190808252806020026020018201604052801561059b57816020015b610588611cb9565b8152602001906001900390816105805790505b5090505f5b828110156107b5575f8686838181106105bb576105bb61203b565b60408051630c5419e360e11b81527f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1956001600160a01b0390811660048301529190920293909301356024820181905293505f928392507f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba16906318a833c69060440161012060405180830381865afa158015610659573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061067d91906122be565b915091505f6106a482846040015164ffffffffff16856060015164ffffffffff16426114a9565b90506107898360025f8781526020019081526020015f206040518060600160405290815f82015481526020016001820154815260200160028201548152505060015f8f6001600160a01b03166001600160a01b031681526020019081526020015f205f8881526020019081526020015f206040518060400160405290815f82015f9054906101000a90046001600160f81b03166001600160f81b03166001600160f81b031681526020015f8201601f9054906101000a900460ff161515151581525050848e8e8b81811061077a5761077a61203b565b90506040020160200135611545565b86868151811061079b5761079b61203b565b6020026020010181905250505050508060010190506105a0565b5095945050505050565b6107c7610f46565b60405163dd4c74c160e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb195811660048301527f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba169063dd4c74c1906024016040805180830381865afa15801561084a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061086e919061236d565b516001600160a01b031633146108c45760405163e2517d3f60e01b81523360048201527f43d5f2668bd1c7628e58e967bbd8b63f1feac3fe0c46b06ccf42fdd0dc6cc15060248201526044015b60405180910390fd5b604051634313878960e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb195811660048301525f9182917f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba16906343138789906024016060604051808303815f875af115801561094d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061097191906123ae565b815160208301519294509092506109b3916001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1951691906116b3565b815f01516001600160a01b03167f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1956001600160a01b03167f91fb9d98b786c57d74c099ccd2beca1739e9f6a81fb49001ca465c4b7591bbe2846020015184604051610a28929190918252602082015260400190565b60405180910390a35050610a3b60015f55565b565b610a45610f46565b604051638c52c16160e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb195811660048301527f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba1690638c52c16190602401602060405180830381865afa158015610ac9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610aed9190612087565b15610b0b5760405163d93c066560e01b815260040160405180910390fd5b60405163dd4c74c160e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb195811660048301527f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba169063dd4c74c1906024016040805180830381865afa158015610b8e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bb2919061236d565b516001600160a01b03163314610c035760405163e2517d3f60e01b81523360048201527f43d5f2668bd1c7628e58e967bbd8b63f1feac3fe0c46b06ccf42fdd0dc6cc15060248201526044016108bb565b7f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba6001600160a01b03166347535d7b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c5f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c839190612087565b610ca057604051634d65bf2960e11b815260040160405180910390fd5b6040516370a0823160e01b81523060048201525f907f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1956001600160a01b0316906370a0823190602401602060405180830381865afa158015610d04573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d2891906123fc565b604051639380d40560e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb19581166004830152602482018590529192505f917f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba1690639380d405906044016020604051808303815f875af1158015610db9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ddd91906123fc565b9050610e146001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb19516333086611712565b6040516370a0823160e01b81523060048201525f907f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1956001600160a01b0316906370a0823190602401602060405180830381865afa158015610e78573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e9c91906123fc565b905080610ea98585612427565b14610ed157604051633bfb3e2360e11b815260048101849052602481018290526044016108bb565b604080518581526020810184905233917f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1956001600160a01b0316917ff5681f9d0db1b911ac18ee83d515a1cf1051853a9eae418316a2fdf7dea427c5910160405180910390a3505050610f4360015f55565b50565b60025f5403610f6857604051633ee5aeb560e01b815260040160405180910390fd5b60025f55565b80515f908190815b81811015611334575f858281518110610f9157610f9161203b565b60200260200101519050806020015115610faa57600193505b8051604051630c5419e360e11b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1958116600483015263ffffffff90921660248201525f9182917f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba909116906318a833c69060440161012060405180830381865afa158015611044573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061106891906122be565b6001600160a01b038b165f908152600160209081526040808320885163ffffffff16845282528083208151808301835290546001600160f81b0381168252600160f81b900460ff1615159281019290925284015160608501519496509294509290916110e191859164ffffffffff9081169116426114a9565b90506110f18b8387878786611751565b81602001511561110557505050505061132c565b5f60025f875f015163ffffffff1681526020019081526020015f2090505f61115c86836040518060600160405290815f82015481526020016001820154815260200160028201548152505086868b60600151611545565b905080606001515f14801561117357508660200151155b8061119a5750606081015115801561118d57506080810151155b801561119a575086602001515b156111ab575050505050505061132c565b8060c001515f0361126b5786516060880151604051630df4b04f60e41b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1958116600483015263ffffffff909316602482015260448101919091527f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba9091169063df4b04f0906064015f604051808303815f87803b158015611254575f80fd5b505af1158015611266573d5f803e3d5ffd5b505050505b606081015160408401518015611282575087602001515b156112f6578160800151826040015183602001516112a0919061243a565b6112aa919061243a565b835f015f8282546112bb9190612427565b909155505060608801516001840180545f906112d8908490612427565b90915550506001602086015260808201516112f39082612427565b90505b611300818d612427565b9b506113238e84878b858d60200151611319575f611946565b8760800151611946565b50505050505050505b600101610f76565b5081801561134b57506001600160a01b0385163314155b1561146057604051638988eea960e01b81523360048201526001600160a01b0386811660248301527f000000000000000000000000ed587067e15bced0f7226133facd65248939c6ba811660448301525f60648301527f00000000000000000000000000000000000000447e69651d841bd8d104bed4931690638988eea990608401602060405180830381865afa1580156113e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061140c9190612087565b15806114405750336001600160a01b037f000000000000000000000000ca11bde05977b3631167028862be2a173976ca1116145b15611460576040516313053d9360e21b81523360048201526024016108bb565b825f0361146e575050505050565b6114a26001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1951686856116b3565b5050505050565b604080516060810182525f80825260208201819052918101829052906114cf8587612427565b9050808310156114fc575050604080516060810182525f808252600160208301529181019190915261153d565b60405180606001604052808285611513919061243a565b81525f6020820152604001851580159061153557506115328684612427565b85105b151590529150505b949350505050565b61154d611cb9565b611555611cb9565b6127108760c0015161ffff168461156c919061244d565b6115769190612464565b808252611583908461243a565b6020820152865115806115aa57508660e0015180156115aa575084516001600160f81b0316155b156115b65790506116aa565b84516001600160f81b031660c08201526020850151806115d7575083602001515b156115e35790506116aa565b602086015187516115f4919061243a565b8651611600908561244d565b61160a9190612464565b60a082015260408401511561168357866060015164ffffffffff16845f01518260200151611638919061244d565b6116429190612464565b6040820181905260c08201518251909161165b91612427565b611665919061243a565b606082015283516116799082908990611a56565b60808201526116a7565b60c081015160a08201516116979085612427565b6116a1919061243a565b60608201525b90505b95945050505050565b6040516001600160a01b0383811660248301526044820183905261045091859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611adb565b6040516001600160a01b03848116602483015283811660448301526064820183905261174b9186918216906323b872dd906084016116e0565b50505050565b6001600160a01b03861661178357604051632e86c5bb60e21b81526001600160a01b03871660048201526024016108bb565b815f036117ae578351604051633ae3261b60e01b815263ffffffff90911660048201526024016108bb565b8060200151156117dc5783516040516302bc564f60e01b815263ffffffff90911660048201526024016108bb565b82515f036118375783516040516311fa919f60e21b815263ffffffff90911660048201526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb1951660248201526044016108bb565b6118598360200151878660400151876060015188602001518960800151611b47565b6118765760405163582f497d60e11b815260040160405180910390fd5b80604001518015611888575083602001515b8015611895575084602001515b156118cd5783516040516334d28b2d60e21b81526001600160a01b038816600482015263ffffffff90911660248201526044016108bb565b84516001600160f81b03161580156118e657508260e001515b1561193e57835160405163f728cb7360e01b81526001600160a01b037f000000000000000000000000e6bfd33f52d82ccb5b37e16d3dd81f9ffdabb19516600482015263ffffffff90911660248201526044016108bb565b505050505050565b81845f018181516119579190612483565b6001600160f81b039081169091526001600160a01b0388165f908152600160209081526040808320885163ffffffff168452825282208851918901511515600160f81b0291909316179091556002870180548593509091906119ba908490612427565b9091555050825160208085015186516002890154895460018b01546040805163ffffffff909816885295870189905293151586860152606086018790526001600160f81b03909216608086015260a085015260c084015260e0830152516001600160a01b038816917f83034380a9b075d8b2ba1006ed3ad2e1e1c9e2bb01f697cec908d2adedf62fc991908190036101000190a2505050505050565b5f61153d84604001518560200151611a6e919061243a565b846060015164ffffffffff1684611aa187608001518860a00151611a9291906124a2565b64ffffffffff16612710611bc2565b611aab919061244d565b611ab59190612464565b611acc866080015164ffffffffff16612710611bc2565b611ad69190612427565b611c04565b5f8060205f8451602086015f885af180611afa576040513d5f823e3d81fd5b50505f513d91508115611b11578060011415611b1e565b6001600160a01b0384163b155b1561174b57604051635274afe760e01b81526001600160a01b03851660048201526024016108bb565b604080516001600160a01b03871660208201529081018490528215156060820152608081018290525f90819060a00160408051601f1981840301815282825280516020918201209083015201604051602081830303815290604052805190602001209050611bb6868983611c33565b98975050505050505050565b5f7812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f2283108202611bf257637c5f487d5f526004601cfd5b50670de0b6b3a7640000919091020490565b5f815f1904831115611c23578115611c235763bac65e5b5f526004601cfd5b50670de0b6b3a764000091020490565b5f82611c3f8584611c48565b14949350505050565b5f81815b8451811015611c8257611c7882868381518110611c6b57611c6b61203b565b6020026020010151611c8a565b9150600101611c4c565b509392505050565b5f818310611ca4575f828152602084905260409020611cb2565b5f8381526020839052604090205b9392505050565b6040518060e001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f60208284031215611cff575f80fd5b81356001600160e01b031981168114611cb2575f80fd5b5f8083601f840112611d26575f80fd5b5081356001600160401b03811115611d3c575f80fd5b6020830191508360208260061b8501011115611d56575f80fd5b9250929050565b5f8060208385031215611d6e575f80fd5b82356001600160401b03811115611d83575f80fd5b611d8f85828601611d16565b90969095509350505050565b602080825282518282018190525f918401906040840190835b81811015611de957835180516001600160f81b0316845260209081015115158185015290930192604090920191600101611db4565b509095945050505050565b6001600160a01b0381168114610f43575f80fd5b5f8083601f840112611e18575f80fd5b5081356001600160401b03811115611e2e575f80fd5b6020830191508360208260051b8501011115611d56575f80fd5b5f805f60408486031215611e5a575f80fd5b8335611e6581611df4565b925060208401356001600160401b03811115611e7f575f80fd5b611e8b86828701611e08565b9497909650939450505050565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b5f8060208385031215611ede575f80fd5b82356001600160401b03811115611ef3575f80fd5b611d8f85828601611e08565b602080825282518282018190525f918401906040840190835b81811015611de957835180518452602081015160208501526040810151604085015250606083019250602084019350600181019050611f18565b5f805f60408486031215611f64575f80fd5b8335611f6f81611df4565b925060208401356001600160401b03811115611f89575f80fd5b611e8b86828701611d16565b602080825282518282018190525f918401906040840190835b81811015611de9578351805184526020810151602085015260408101516040850152606081015160608501526080810151608085015260a081015160a085015260c081015160c08501525060e083019250602084019350600181019050611fae565b5f60208284031215612020575f80fd5b5035919050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561205f575f80fd5b8135611cb281611df4565b8015158114610f43575f80fd5b80516120828161206a565b919050565b5f60208284031215612097575f80fd5b8151611cb28161206a565b60405160a081016001600160401b03811182821017156120c4576120c4612027565b60405290565b60405161010081016001600160401b03811182821017156120c4576120c4612027565b604080519081016001600160401b03811182821017156120c4576120c4612027565b604051601f8201601f191681016001600160401b038111828210171561213757612137612027565b604052919050565b5f6001600160401b0382111561215757612157612027565b5060051b60200190565b5f82601f830112612170575f80fd5b813561218361217e8261213f565b61210f565b8082825260208201915060208360051b8601019250858311156121a4575f80fd5b602085015b838110156107b55780358352602092830192016121a9565b5f6121ce61217e8461213f565b8381526020810190600585901b8401368111156121e9575f80fd5b845b81811015611de95780356001600160401b03811115612208575f80fd5b860160a036829003121561221a575f80fd5b6122226120a2565b813563ffffffff81168114612235575f80fd5b815260208201356122458161206a565b602082015260408201356001600160401b03811115612262575f80fd5b61226e36828501612161565b60408301525060608281013590820152608091820135918101919091528452602093840193016121eb565b805164ffffffffff81168114612082575f80fd5b805161ffff81168114612082575f80fd5b5f808284036101208112156122d1575f80fd5b6101008112156122df575f80fd5b506122e86120ca565b835181526020808501519082015261230260408501612299565b604082015261231360608501612299565b606082015261232460808501612299565b608082015261233560a08501612299565b60a082015261234660c085016122ad565b60c082015261235760e08501612077565b60e0820152610100939093015192949293505050565b5f604082840312801561237e575f80fd5b506123876120ed565b825161239281611df4565b815260208301516123a281611df4565b60208201529392505050565b5f8082840360608112156123c0575f80fd5b60408112156123cd575f80fd5b506123d66120ed565b83516123e181611df4565b81526020848101519082015260409093015192949293505050565b5f6020828403121561240c575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561022357610223612413565b8181038181111561022357610223612413565b808202811582820484141761022357610223612413565b5f8261247e57634e487b7160e01b5f52601260045260245ffd5b500490565b6001600160f81b03818116838216019081111561022357610223612413565b64ffffffffff82811682821603908111156102235761022361241356fea26469706673582212205a33527b9352c08532f922b7a42ed0a82d7f61db02e6062a88748f264ee059fd64736f6c634300081a0033
Loading...
Loading
Loading...
Loading
Net Worth in USD
$1,512,917.11
Net Worth in ETH
816.703488
Token Allocations
SXT
100.00%
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|---|---|---|---|---|
| ETH | 100.00% | $0.022755 | 66,487,939.5692 | $1,512,917.11 |
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.