Source Code
Overview
HYPE Balance
HYPE Value
$0.00More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 25 from a total of 395 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Rebalance | 25571501 | 37 mins ago | IN | 0 HYPE | 0.00141493 | ||||
| Rebalance | 25570277 | 58 mins ago | IN | 0 HYPE | 0.00101877 | ||||
| Rebalance | 25569061 | 1 hr ago | IN | 0 HYPE | 0.00106506 | ||||
| Rebalance | 25567853 | 1 hr ago | IN | 0 HYPE | 0.00090598 | ||||
| Rebalance | 25566617 | 1 hr ago | IN | 0 HYPE | 0.00123154 | ||||
| Rebalance | 25565400 | 2 hrs ago | IN | 0 HYPE | 0.00141493 | ||||
| Rebalance | 25564180 | 2 hrs ago | IN | 0 HYPE | 0.00101877 | ||||
| Rebalance | 25563567 | 2 hrs ago | IN | 0 HYPE | 0.00155981 | ||||
| Rebalance | 25562346 | 3 hrs ago | IN | 0 HYPE | 0.00122306 | ||||
| Rebalance | 25557467 | 4 hrs ago | IN | 0 HYPE | 0.00144241 | ||||
| Rebalance | 25556246 | 4 hrs ago | IN | 0 HYPE | 0.00189632 | ||||
| Rebalance | 25554420 | 5 hrs ago | IN | 0 HYPE | 0.00142577 | ||||
| Rebalance | 25551367 | 6 hrs ago | IN | 0 HYPE | 0.00102786 | ||||
| Rebalance | 25550147 | 6 hrs ago | IN | 0 HYPE | 0.00081682 | ||||
| Rebalance | 25548317 | 6 hrs ago | IN | 0 HYPE | 0.00110847 | ||||
| Rebalance | 25542826 | 8 hrs ago | IN | 0 HYPE | 0.0012162 | ||||
| Rebalance | 25541606 | 8 hrs ago | IN | 0 HYPE | 0.00116344 | ||||
| Rebalance | 25534901 | 10 hrs ago | IN | 0 HYPE | 0.00091058 | ||||
| Rebalance | 25533678 | 10 hrs ago | IN | 0 HYPE | 0.00122337 | ||||
| Rebalance | 25531846 | 11 hrs ago | IN | 0 HYPE | 0.00090917 | ||||
| Rebalance | 25531236 | 11 hrs ago | IN | 0 HYPE | 0.00091058 | ||||
| Rebalance | 25530017 | 11 hrs ago | IN | 0 HYPE | 0.00122337 | ||||
| Approve | 25529367 | 12 hrs ago | IN | 0 HYPE | 0.00034072 | ||||
| Rebalance | 25527581 | 12 hrs ago | IN | 0 HYPE | 0.00173275 | ||||
| Approve | 25526417 | 12 hrs ago | IN | 0 HYPE | 0.00012293 |
Advanced mode: Intended for advanced users or developers and will display all Internal Transactions including zero value transfers.
Latest 25 internal transactions (View All)
Advanced mode:
| Parent Transaction Hash | Block | From | To | ||||
|---|---|---|---|---|---|---|---|
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE | |||||
| 25571501 | 37 mins ago | 0 HYPE |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
FleetCommander
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 25 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArk} from "../interfaces/IArk.sol";
import {IFleetCommander} from "../interfaces/IFleetCommander.sol";
import {ArkData, FleetCommanderParams, FleetConfig, RebalanceData} from "../types/FleetCommanderTypes.sol";
import {CooldownEnforcer} from "../utils/CooldownEnforcer/CooldownEnforcer.sol";
import {FleetCommanderCache} from "./FleetCommanderCache.sol";
import {FleetCommanderConfigProvider} from "./FleetCommanderConfigProvider.sol";
import {Tipper} from "./Tipper.sol";
import {ERC20, ERC4626, IERC20, IERC4626, SafeERC20} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IFleetCommanderRewardsManager} from "../interfaces/IFleetCommanderRewardsManager.sol";
import {Constants} from "@summerfi/constants/Constants.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
import {PercentageUtils} from "@summerfi/percentage-solidity/contracts/PercentageUtils.sol";
/**
* @title FleetCommander
* @notice Manages a fleet of Arks, coordinating deposits, withdrawals, and rebalancing operations
* @dev Implements IFleetCommander interface and inherits from various utility contracts
*/
contract FleetCommander is
IFleetCommander,
FleetCommanderConfigProvider,
ERC4626,
Tipper,
FleetCommanderCache,
CooldownEnforcer
{
using SafeERC20 for IERC20;
using PercentageUtils for uint256;
using Math for uint256;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the FleetCommander contract
* @param params FleetCommanderParams struct containing initialization parameters
*/
constructor(
FleetCommanderParams memory params
)
ERC4626(IERC20(params.asset))
ERC20(params.name, params.symbol)
FleetCommanderConfigProvider(params)
Tipper(params.initialTipRate)
CooldownEnforcer(params.initialRebalanceCooldown, false)
{}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @dev Modifier to collect the tip before any other action is taken
*/
modifier collectTip() {
_setIsCollectingTip(true);
_accrueTip(tipJar(), totalSupply());
_;
_setIsCollectingTip(false);
}
/**
* @dev Modifier to cache ark data for deposit operations.
* @notice This modifier retrieves ark data before the function execution,
* allows the modified function to run, and then flushes the cache.
* @dev The cache is required due to multiple calls to `totalAssets` in the same transaction.
* those calls migh be gas expensive for some arks.
*/
modifier useCache() {
_getArksData(config.bufferArk);
_;
_flushCache();
}
/**
* @dev Modifier to cache withdrawable ark data for withdraw operations.
* @notice This modifier retrieves withdrawable ark data before the function execution,
* allows the modified function to run, and then flushes the cache.
* @dev The cache is required due to multiple calls to `totalAssets` in the same transaction.
* those calls migh be gas expensive for some arks.
*/
modifier useWithdrawCache() {
_getWithdrawableArksData(config.bufferArk);
_;
_flushCache();
}
/*//////////////////////////////////////////////////////////////
PUBLIC USER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IFleetCommander
function withdrawFromBuffer(
uint256 assets,
address receiver,
address owner
) public whenNotPaused collectTip useCache returns (uint256 shares) {
shares = previewWithdraw(assets);
_validateBufferWithdraw(assets, shares, owner);
uint256 prevQueueBalance = config.bufferArk.totalAssets();
_disembark(address(config.bufferArk), assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
emit FundsBufferBalanceUpdated(
_msgSender(),
prevQueueBalance,
config.bufferArk.totalAssets()
);
}
/// @inheritdoc IFleetCommander
function redeem(
uint256 shares,
address receiver,
address owner
)
public
override(ERC4626, IFleetCommander)
collectTip
useCache
whenNotPaused
returns (uint256 assets)
{
uint256 bufferBalance = config.bufferArk.totalAssets();
uint256 bufferBalanceInShares = convertToShares(bufferBalance);
if (shares == Constants.MAX_UINT256) {
shares = balanceOf(owner);
}
if (shares <= bufferBalanceInShares) {
assets = redeemFromBuffer(shares, receiver, owner);
} else {
assets = redeemFromArks(shares, receiver, owner);
}
}
/// @inheritdoc IFleetCommander
function redeemFromBuffer(
uint256 shares,
address receiver,
address owner
) public collectTip useCache whenNotPaused returns (uint256 assets) {
_validateBufferRedeem(shares, owner);
uint256 previousFundsBufferBalance = config.bufferArk.totalAssets();
assets = previewRedeem(shares);
_disembark(address(config.bufferArk), assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
emit FundsBufferBalanceUpdated(
_msgSender(),
previousFundsBufferBalance,
config.bufferArk.totalAssets()
);
}
/// @inheritdoc IFleetCommander
function withdraw(
uint256 assets,
address receiver,
address owner
)
public
override(ERC4626, IFleetCommander)
collectTip
useCache
whenNotPaused
returns (uint256 shares)
{
uint256 bufferBalance = config.bufferArk.totalAssets();
if (assets == Constants.MAX_UINT256) {
uint256 totalUserShares = balanceOf(owner);
assets = previewRedeem(totalUserShares);
}
if (assets <= bufferBalance) {
shares = withdrawFromBuffer(assets, receiver, owner);
} else {
shares = withdrawFromArks(assets, receiver, owner);
}
}
/// @inheritdoc IFleetCommander
function withdrawFromArks(
uint256 assets,
address receiver,
address owner
)
public
override(IFleetCommander)
collectTip
useWithdrawCache
whenNotPaused
returns (uint256 totalSharesToRedeem)
{
totalSharesToRedeem = previewWithdraw(assets);
_validateWithdrawFromArks(assets, totalSharesToRedeem, owner);
_forceDisembarkFromSortedArks(assets);
_withdraw(_msgSender(), receiver, owner, assets, totalSharesToRedeem);
_resetLastActionTimestamp();
emit FleetCommanderWithdrawnFromArks(owner, receiver, assets);
}
/// @inheritdoc IFleetCommander
function redeemFromArks(
uint256 shares,
address receiver,
address owner
)
public
override(IFleetCommander)
collectTip
useWithdrawCache
whenNotPaused
returns (uint256 totalAssetsToWithdraw)
{
_validateRedeemFromArks(shares, owner);
totalAssetsToWithdraw = previewRedeem(shares);
_forceDisembarkFromSortedArks(totalAssetsToWithdraw);
_withdraw(_msgSender(), receiver, owner, totalAssetsToWithdraw, shares);
_resetLastActionTimestamp();
emit FleetCommanderRedeemedFromArks(owner, receiver, shares);
}
/// @inheritdoc IERC4626
function deposit(
uint256 assets,
address receiver
)
public
override(ERC4626, IERC4626)
collectTip
useCache
whenNotPaused
returns (uint256 shares)
{
_validateDeposit(assets, _msgSender());
uint256 previousFundsBufferBalance = config.bufferArk.totalAssets();
shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
_board(address(config.bufferArk), assets);
emit FundsBufferBalanceUpdated(
_msgSender(),
previousFundsBufferBalance,
config.bufferArk.totalAssets()
);
}
/// @inheritdoc IFleetCommander
function deposit(
uint256 assets,
address receiver,
bytes memory referralCode
) external returns (uint256) {
emit FleetCommanderReferral(receiver, referralCode);
return deposit(assets, receiver);
}
/// @inheritdoc IERC4626
function mint(
uint256 shares,
address receiver
)
public
override(ERC4626, IERC4626)
collectTip
useCache
whenNotPaused
returns (uint256 assets)
{
_validateMint(shares, _msgSender());
uint256 previousFundsBufferBalance = config.bufferArk.totalAssets();
assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
_board(address(config.bufferArk), assets);
emit FundsBufferBalanceUpdated(
_msgSender(),
previousFundsBufferBalance,
config.bufferArk.totalAssets()
);
}
/// @inheritdoc IFleetCommander
function tip() public whenNotPaused returns (uint256) {
return _accrueTip(tipJar(), totalSupply());
}
/*//////////////////////////////////////////////////////////////
PUBLIC VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @dev Overrides the totalSupply function to include the tip shares
* @dev This is done to ensure that the totalSupply is always accurate, even when tips are being accrued
* @dev This is done by checking if the _isCollectingTip flag is set, and if it is, return the totalSupply
* @dev If the _isCollectingTip flag is not set, then we need to accrue the tips and return the totalSupply + the
* previewTip
* @dev when collecting fee we require totalSupply to be the pre tip totalSupply, after the tip is collected the
* totalSupply will include the tip shares
* @dev when called in view functions we need to return the totalSupply + the previewTip
* @return uint256 The total supply of the FleetCommander, including tip shares
*/
function totalSupply()
public
view
override(ERC20, IERC20)
returns (uint256)
{
if (_isCollectingTip()) {
return super.totalSupply();
}
uint256 _totalSupply = super.totalSupply();
return _totalSupply + previewTip(tipJar(), _totalSupply);
}
/// @inheritdoc IFleetCommander
function totalAssets()
public
view
override(IFleetCommander, ERC4626)
returns (uint256)
{
return _totalAssets(config.bufferArk);
}
/// @inheritdoc IFleetCommander
function withdrawableTotalAssets() public view returns (uint256) {
return _withdrawableTotalAssets(config.bufferArk);
}
/// @inheritdoc IERC4626
function maxDeposit(
address owner
) public view override(ERC4626, IERC4626) returns (uint256 _maxDeposit) {
uint256 _totalAssets = totalAssets();
uint256 maxAssets = _totalAssets > config.depositCap
? 0
: config.depositCap - _totalAssets;
_maxDeposit = Math.min(maxAssets, IERC20(asset()).balanceOf(owner));
}
/// @inheritdoc IERC4626
function maxMint(
address owner
) public view override(ERC4626, IERC4626) returns (uint256 _maxMint) {
uint256 _totalAssets = totalAssets();
uint256 maxAssets = _totalAssets > config.depositCap
? 0
: config.depositCap - _totalAssets;
_maxMint = previewDeposit(
Math.min(maxAssets, IERC20(asset()).balanceOf(owner))
);
}
/// @inheritdoc IFleetCommander
function maxBufferWithdraw(
address owner
) public view returns (uint256 _maxBufferWithdraw) {
_maxBufferWithdraw = Math.min(
config.bufferArk.totalAssets(),
previewRedeem(balanceOf(owner))
);
}
/// @inheritdoc IERC4626
function maxWithdraw(
address owner
) public view override(ERC4626, IERC4626) returns (uint256 _maxWithdraw) {
_maxWithdraw = Math.min(
withdrawableTotalAssets(),
previewRedeem(balanceOf(owner))
);
}
/// @inheritdoc IERC4626
function maxRedeem(
address owner
) public view override(ERC4626, IERC4626) returns (uint256 _maxRedeem) {
_maxRedeem = Math.min(
convertToShares(withdrawableTotalAssets()),
balanceOf(owner)
);
}
/// @inheritdoc IFleetCommander
function maxBufferRedeem(
address owner
) public view returns (uint256 _maxBufferRedeem) {
_maxBufferRedeem = Math.min(
previewWithdraw(config.bufferArk.totalAssets()),
balanceOf(owner)
);
}
/*//////////////////////////////////////////////////////////////
EXTERNAL KEEPER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IFleetCommander
function rebalance(
RebalanceData[] calldata rebalanceData
) external onlyKeeper enforceCooldown collectTip whenNotPaused {
_validateReallocateAllAssets(rebalanceData);
_validateAdjustBuffer(rebalanceData);
_reallocateAllAssets(rebalanceData);
}
/*//////////////////////////////////////////////////////////////
EXTERNAL GOVERNOR FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IFleetCommander
function setTipRate(
Percentage newTipRate
) external onlyGovernor whenNotPaused {
// The newTipRate uses the Percentage type from @summerfi/percentage-solidity
// Percentages have 18 decimals of precision
// For example, 1% would be represented as 1 * 10^18 (assuming PERCENTAGE_DECIMALS is 18)
_setTipRate(newTipRate, tipJar(), totalSupply());
}
/// @inheritdoc IFleetCommander
function setMinimumPauseTime(
uint256 _newMinimumPauseTime
) public onlyGovernor whenNotPaused {
_setMinimumPauseTime(_newMinimumPauseTime);
}
/// @inheritdoc IFleetCommander
function updateRebalanceCooldown(
uint256 newCooldown
) external onlyCurator(address(this)) whenNotPaused {
_updateCooldown(newCooldown);
}
/// @inheritdoc IFleetCommander
function forceRebalance(
RebalanceData[] calldata rebalanceData
) external onlyGovernor collectTip whenNotPaused {
_validateReallocateAllAssets(rebalanceData);
_validateAdjustBuffer(rebalanceData);
_reallocateAllAssets(rebalanceData);
}
/// @inheritdoc IFleetCommander
function pause() external onlyGuardianOrGovernor {
_pause();
}
/// @inheritdoc IFleetCommander
function unpause() external onlyGuardianOrGovernor {
_unpause();
}
/*//////////////////////////////////////////////////////////////
PUBLIC ERC20 FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IERC20
function transfer(
address to,
uint256 amount
) public override(IERC20, ERC20) returns (bool) {
if (transfersEnabled || _msgSender() == config.stakingRewardsManager) {
return super.transfer(to, amount);
}
revert FleetCommanderTransfersDisabled();
}
/// @inheritdoc IERC20
function transferFrom(
address from,
address to,
uint256 amount
) public override(IERC20, ERC20) returns (bool) {
if (transfersEnabled || _msgSender() == config.stakingRewardsManager) {
return super.transferFrom(from, to, amount);
}
revert FleetCommanderTransfersDisabled();
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Mints new shares as tips to the specified account
* @dev This function overrides the abstract _mintTip function from the Tipper contract.
* It is called internally by the _accrueTip function to mint new shares as tips.
* In the context of FleetCommander, this creates new shares without requiring
* additional underlying assets, effectively diluting existing shareholders slightly
* to pay for the protocol's ongoing operations.
* @param account The address to receive the minted tip shares
* @param amount The amount of shares to mint as a tip
*/
function _mintTip(
address account,
uint256 amount
) internal virtual override {
_mint(account, amount);
}
/**
* @notice Reallocates all assets based on the provided rebalance data
* @param rebalanceData Array of RebalanceData structs containing information about the reallocation
*/
function _reallocateAllAssets(
RebalanceData[] calldata rebalanceData
) internal {
for (uint256 i = 0; i < rebalanceData.length; i++) {
_reallocateAssets(rebalanceData[i]);
}
emit Rebalanced(_msgSender(), rebalanceData);
}
/* INTERNAL - ARK */
/**
* @notice Approves and boards a specified amount of assets to an Ark
* @param ark The address of the Ark
* @param amount The amount of assets to board
*/
function _board(address ark, uint256 amount) internal {
IERC20(asset()).forceApprove(ark, amount);
IArk(ark).board(amount, bytes(""));
}
/**
* @notice Disembarks a specified amount of assets from an Ark
* @param ark The address of the Ark
* @param amount The amount of assets to disembark
*/
function _disembark(address ark, uint256 amount) internal {
IArk(ark).disembark(amount, bytes(""));
}
/**
* @notice Moves a specified amount of assets from one Ark to another
* @param fromArk The address of the Ark to move assets from
* @param toArk The address of the Ark to move assets to
* @param amount The amount of assets to move
* @param boardData Additional data for the board operation
* @param disembarkData Additional data for the disembark operation
*/
function _move(
address fromArk,
address toArk,
uint256 amount,
bytes memory boardData,
bytes memory disembarkData
) internal {
IArk(fromArk).move(amount, toArk, boardData, disembarkData);
}
/* INTERNAL */
/**
* @notice Reallocates assets from one Ark to another
* @dev This function handles the reallocation of assets between Arks, considering:
* 1. The maximum allocation of the destination Ark
* 2. The current allocation of the destination Ark
* @param data The RebalanceData struct containing information about the reallocation
* @custom:error FleetCommanderEffectiveDepositCapExceeded Thrown when the destination Ark is already at or above
* its maximum
* allocation
*/
function _reallocateAssets(RebalanceData memory data) internal {
IArk toArk = IArk(data.toArk);
IArk fromArk = IArk(data.fromArk);
uint256 amount;
if (data.amount == Constants.MAX_UINT256) {
amount = fromArk.totalAssets();
} else {
amount = data.amount;
}
// The validation has to take into account the actual amount that will be moved
_validateReallocateAssets(data.fromArk, data.toArk, amount);
uint256 toArkDepositCap = getEffectiveArkDepositCap(toArk);
uint256 toArkAllocation = toArk.totalAssets();
if (toArkAllocation + amount > toArkDepositCap) {
revert FleetCommanderEffectiveDepositCapExceeded(
address(toArk),
amount,
toArkDepositCap
);
}
_move(
address(fromArk),
address(toArk),
amount,
data.boardData,
data.disembarkData
);
}
/**
* @notice Calculates the effective deposit cap for an Ark
* @dev This function returns the lower of two caps: a percentage-based cap derived from TVL,
* and the absolute deposit cap set for the Ark
* @param ark The address of the Ark
* @return The effective deposit cap in token units
*/
function getEffectiveArkDepositCap(IArk ark) public view returns (uint256) {
uint256 tvl = this.totalAssets();
uint256 pctBasedCap = tvl.applyPercentage(
ark.maxDepositPercentageOfTVL()
);
return Math.min(pctBasedCap, ark.depositCap());
}
/**
* @notice Withdraws assets from multiple arks in a specific order
* @dev This function attempts to withdraw the requested amount from arks,
* that allow such operations, in the order of total assets held
* @param assets The total amount of assets to withdraw
*/
function _forceDisembarkFromSortedArks(uint256 assets) internal {
ArkData[] memory withdrawableArks = _getWithdrawableArksDataFromCache();
for (uint256 i = 0; i < withdrawableArks.length; i++) {
uint256 assetsInArk = withdrawableArks[i].totalAssets;
if (assetsInArk >= assets) {
_disembark(withdrawableArks[i].arkAddress, assets);
break;
} else if (assetsInArk > 0) {
_disembark(withdrawableArks[i].arkAddress, assetsInArk);
assets -= assetsInArk;
}
}
}
/* INTERNAL - VALIDATIONS */
/**
* @notice Validates the data for adjusting the buffer
* @dev This function checks if all operations in the rebalance data are consistent
* (either all moving to buffer or all moving from buffer) and ensures that
* the buffer balance remains above the minimum required balance.
* When moving to the buffer, using MAX_UINT256 as the amount will move all funds from the source Ark.
* @param rebalanceData An array of RebalanceData structs containing the rebalance operations
* @custom:error FleetCommanderNoExcessFunds Thrown when trying to move funds out of an already minimum buffer
* @custom:error FleetCommanderInsufficientBuffer Thrown when trying to move more funds than available excess
* @custom:error FleetCommanderCantUseMaxUintMovingFromBuffer Thrown when trying to use MAX_UINT256 amount when
* moving from buffer
*/
function _validateAdjustBuffer(
RebalanceData[] calldata rebalanceData
) internal view {
uint256 initialBufferBalance = config.bufferArk.totalAssets();
int256 netBufferChange;
address _bufferArkAddress = address(config.bufferArk);
for (uint256 i = 0; i < rebalanceData.length; i++) {
if (
rebalanceData[i].toArk == _bufferArkAddress ||
rebalanceData[i].fromArk == _bufferArkAddress
) {
bool isMovingToBuffer = rebalanceData[i].toArk ==
_bufferArkAddress;
uint256 amount = rebalanceData[i].amount;
if (amount == Constants.MAX_UINT256) {
if (!isMovingToBuffer) {
revert FleetCommanderCantUseMaxUintMovingFromBuffer();
}
amount = IArk(rebalanceData[i].fromArk).totalAssets();
}
if (isMovingToBuffer) {
netBufferChange += int256(amount);
} else {
netBufferChange -= int256(amount);
}
}
}
if (netBufferChange < 0) {
_validateBufferExcessFunds(
initialBufferBalance,
uint256(-netBufferChange)
);
}
}
/**
* @notice Validates that there are sufficient excess funds in the buffer for withdrawal
* @dev This function checks two conditions:
* 1. The initial buffer balance is greater than the minimum required balance
* 2. The amount to move does not exceed the excess funds in the buffer
* @param initialBufferBalance The current balance of the buffer before the adjustment
* @param totalToMove The total amount of assets to be moved from the buffer
* @custom:error FleetCommanderNoExcessFunds Thrown when the buffer balance is at or below the minimum required
* balance
* @custom:error FleetCommanderInsufficientBuffer Thrown when the amount to move exceeds the available excess funds
* in the buffer
*/
function _validateBufferExcessFunds(
uint256 initialBufferBalance,
uint256 totalToMove
) internal view {
uint256 minimumBufferBalance = config.minimumBufferBalance;
if (initialBufferBalance <= minimumBufferBalance) {
revert FleetCommanderNoExcessFunds();
}
uint256 excessFunds = initialBufferBalance - minimumBufferBalance;
if (totalToMove > excessFunds) {
revert FleetCommanderInsufficientBuffer();
}
}
/**
* @notice Validates the asset reallocation data for correctness and consistency
* @dev This function checks various conditions of the rebalance operations:
* - Number of operations is within limits
* @param rebalanceData An array of RebalanceData structs containing the rebalance operations
*/
function _validateReallocateAllAssets(
RebalanceData[] calldata rebalanceData
) internal view {
if (rebalanceData.length > config.maxRebalanceOperations) {
revert FleetCommanderRebalanceTooManyOperations(
rebalanceData.length
);
}
if (rebalanceData.length == 0) {
revert FleetCommanderRebalanceNoOperations();
}
}
/**
* @notice Validates the reallocation of assets between two ARKs.
* @param fromArk The address of the source ARK.
* @param toArk The address of the destination ARK.
* @param amount The amount of assets to be reallocated.
* @custom:error FleetCommanderRebalanceAmountZero if the amount is zero.
* @custom:error FleetCommanderArkNotFound if the source or destination ARK is not found.
* @custom:error FleetCommanderArkNotActive if the source or destination ARK is not active.
* @custom:error FleetCommanderExceedsMaxOutflow if the amount exceeds the maximum move from limit of the source
* ARK.
* @custom:error FleetCommanderExceedsMaxInflow if the amount exceeds the maximum move to limit of the destination
* ARK.
* @custom:error FleetCommanderArkDepositCapZero if the deposit cap of the destination ARK is zero.
*/
function _validateReallocateAssets(
address fromArk,
address toArk,
uint256 amount
) internal {
if (amount == 0) {
revert FleetCommanderRebalanceAmountZero(toArk);
}
if (toArk == address(0)) {
revert FleetCommanderArkNotFound(toArk);
}
if (fromArk == address(0)) {
revert FleetCommanderArkNotFound(fromArk);
}
if (!isArkActiveOrBufferArk(toArk)) {
revert FleetCommanderArkNotActive(toArk);
}
if (!isArkActiveOrBufferArk(fromArk)) {
revert FleetCommanderArkNotActive(fromArk);
}
if (IArk(toArk).depositCap() == 0) {
revert FleetCommanderArkDepositCapZero(toArk);
}
(
uint256 inflowBalance,
uint256 outflowBalance,
uint256 maxRebalanceInflow,
uint256 maxRebalanceOutflow
) = _cacheArkFlow(fromArk, toArk, amount);
if (outflowBalance > maxRebalanceOutflow) {
revert FleetCommanderExceedsMaxOutflow(
fromArk,
outflowBalance,
maxRebalanceOutflow
);
}
if (inflowBalance > maxRebalanceInflow) {
revert FleetCommanderExceedsMaxInflow(
toArk,
inflowBalance,
maxRebalanceInflow
);
}
}
/**
* @notice Validates the withdraw request
* @dev This function checks two conditions:
* 1. The caller is authorized to withdraw on behalf of the owner
* 2. The withdrawal amount does not exceed the maximum allowed
* @param assets The amount of assets to withdraw
* @param shares The number of shares to redeem
* @param owner The address of the owner of the assets
* @custom:error FleetCommanderUnauthorizedWithdrawal Thrown when the caller is not authorized to withdraw
* @custom:error IERC4626ExceededMaxWithdraw Thrown when the withdrawal amount exceeds the maximum allowed
* @custom:error FleetCommanderZeroAmount Thrown when the withdrawal amount is zero
*/
function _validateBufferWithdraw(
uint256 assets,
uint256 shares,
address owner
) internal view {
if (shares == 0) {
revert FleetCommanderZeroAmount();
}
if (
_msgSender() != owner &&
IERC20(address(this)).allowance(owner, _msgSender()) < shares
) {
revert FleetCommanderUnauthorizedWithdrawal(_msgSender(), owner);
}
uint256 maxAssets = maxBufferWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
}
/**
* @notice Validates the redemption request
* @dev This function checks two conditions:
* 1. The caller is authorized to redeem on behalf of the owner
* 2. The redemption amount does not exceed the maximum allowed
* @param shares The number of shares to redeem
* @param owner The address of the owner of the shares
* @custom:error FleetCommanderUnauthorizedRedemption Thrown when the caller is not authorized to redeem
* @custom:error IERC4626ExceededMaxRedeem Thrown when the redemption amount exceeds the maximum allowed
* @custom:error FleetCommanderZeroAmount Thrown when the redemption amount is zero
*/
function _validateBufferRedeem(
uint256 shares,
address owner
) internal view {
if (shares == 0) {
revert FleetCommanderZeroAmount();
}
if (
_msgSender() != owner &&
IERC20(address(this)).allowance(owner, _msgSender()) < shares
) {
revert FleetCommanderUnauthorizedRedemption(_msgSender(), owner);
}
uint256 maxShares = maxBufferRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
}
/**
* @notice Validates the deposit request
* @dev This function checks if the requested deposit amount exceeds the maximum allowed
* @param assets The amount of assets to deposit
* @param owner The address of the account making the deposit
* @custom:error FleetCommanderZeroAmount Thrown when the deposit amount is zero
* @custom:error IERC4626ExceededMaxDeposit Thrown when the deposit amount exceeds the maximum allowed
*/
function _validateDeposit(uint256 assets, address owner) internal view {
if (assets == 0) {
revert FleetCommanderZeroAmount();
}
uint256 maxAssets = maxDeposit(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(owner, assets, maxAssets);
}
}
/**
* @notice Validates the mint request
* @dev This function checks if the requested mint amount exceeds the maximum allowed
* @param shares The number of shares to mint
* @param owner The address of the account minting the shares
* @custom:error FleetCommanderZeroAmount Thrown when the mint amount is zero
* @custom:error IERC4626ExceededMaxMint Thrown when the mint amount exceeds the maximum allowed
*/
function _validateMint(uint256 shares, address owner) internal view {
if (shares == 0) {
revert FleetCommanderZeroAmount();
}
uint256 maxShares = maxMint(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(owner, shares, maxShares);
}
}
/**
* @notice Validates the force withdraw request
* @dev This function checks two conditions:
* 1. The caller is authorized to withdraw on behalf of the owner
* 2. The withdrawal amount does not exceed the maximum allowed
* @param assets The amount of assets to withdraw
* @param shares The amount of shares to redeem
* @param owner The address of the owner of the assets
* @custom:error FleetCommanderUnauthorizedWithdrawal Thrown when the caller is not authorized to withdraw
* @custom:error IERC4626ExceededMaxWithdraw Thrown when the withdrawal amount exceeds the maximum allowed
* @custom:error FleetCommanderZeroAmount Thrown when the withdrawal amount is zero
*/
function _validateWithdrawFromArks(
uint256 assets,
uint256 shares,
address owner
) internal view {
if (shares == 0) {
revert FleetCommanderZeroAmount();
}
if (
_msgSender() != owner &&
IERC20(address(this)).allowance(owner, _msgSender()) < shares
) {
revert FleetCommanderUnauthorizedWithdrawal(_msgSender(), owner);
}
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
}
/**
* @notice Validates the force redeem request
* @dev This function checks two conditions:
* 1. The caller is authorized to redeem on behalf of the owner
* 2. The redemption amount does not exceed the maximum allowed
* @param shares The amount of shares to redeem
* @param owner The address of the owner of the assets
* @custom:error FleetCommanderUnauthorizedRedemption Thrown when the caller is not authorized to redeem
* @custom:error IERC4626ExceededMaxRedeem Thrown when the redemption amount exceeds the maximum allowed
* @custom:error FleetCommanderZeroAmount Thrown when the redemption amount is zero
*/
function _validateRedeemFromArks(
uint256 shares,
address owner
) internal view {
if (shares == 0) {
revert FleetCommanderZeroAmount();
}
if (
_msgSender() != owner &&
IERC20(address(this)).allowance(owner, _msgSender()) < shares
) {
revert FleetCommanderUnauthorizedRedemption(_msgSender(), owner);
}
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
}
function _getActiveArksAddresses()
internal
view
override(FleetCommanderCache)
returns (address[] memory)
{
return getActiveArks();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @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 to signal 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.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
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.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC4626.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/ERC20Wrapper.sol)
pragma solidity ^0.8.20;
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
/**
* @dev Extension of the ERC-20 token contract to support token wrapping.
*
* Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful
* in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the
* wrapping of an existing "basic" ERC-20 into a governance token.
*
* WARNING: Any mechanism in which the underlying token changes the {balanceOf} of an account without an explicit transfer
* may desynchronize this contract's supply and its underlying balance. Please exercise caution when wrapping tokens that
* may undercollateralize the wrapper (i.e. wrapper's total supply is higher than its underlying balance). See {_recover}
* for recovering value accrued to the wrapper.
*/
abstract contract ERC20Wrapper is ERC20 {
IERC20 private immutable _underlying;
/**
* @dev The underlying token couldn't be wrapped.
*/
error ERC20InvalidUnderlying(address token);
constructor(IERC20 underlyingToken) {
if (underlyingToken == this) {
revert ERC20InvalidUnderlying(address(this));
}
_underlying = underlyingToken;
}
/// @inheritdoc IERC20Metadata
function decimals() public view virtual override returns (uint8) {
try IERC20Metadata(address(_underlying)).decimals() returns (uint8 value) {
return value;
} catch {
return super.decimals();
}
}
/**
* @dev Returns the address of the underlying ERC-20 token that is being wrapped.
*/
function underlying() public view returns (IERC20) {
return _underlying;
}
/**
* @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
*/
function depositFor(address account, uint256 value) public virtual returns (bool) {
address sender = _msgSender();
if (sender == address(this)) {
revert ERC20InvalidSender(address(this));
}
if (account == address(this)) {
revert ERC20InvalidReceiver(account);
}
SafeERC20.safeTransferFrom(_underlying, sender, address(this), value);
_mint(account, value);
return true;
}
/**
* @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
*/
function withdrawTo(address account, uint256 value) public virtual returns (bool) {
if (account == address(this)) {
revert ERC20InvalidReceiver(account);
}
_burn(_msgSender(), value);
SafeERC20.safeTransfer(_underlying, account, value);
return true;
}
/**
* @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake or acquired from
* rebasing mechanisms. Internal function that can be exposed with access control if desired.
*/
function _recover(address account) internal virtual returns (uint256) {
uint256 value = _underlying.balanceOf(address(this)) - totalSupply();
_mint(account, value);
return value;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {Math} from "../../../utils/math/Math.sol";
/**
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
* The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
* and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
* itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
* offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
* of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
* With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
* underlying math can be found xref:ROOT:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626 is ERC20, IERC4626 {
using Math for uint256;
IERC20 private immutable _asset;
uint8 private immutable _underlyingDecimals;
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
*/
constructor(IERC20 asset_) {
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
_underlyingDecimals = success ? assetDecimals : 18;
_asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
return _underlyingDecimals + _decimalsOffset();
}
/// @inheritdoc IERC4626
function asset() public view virtual returns (address) {
return address(_asset);
}
/// @inheritdoc IERC4626
function totalAssets() public view virtual returns (uint256) {
return IERC20(asset()).balanceOf(address(this));
}
/// @inheritdoc IERC4626
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/// @inheritdoc IERC4626
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/// @inheritdoc IERC4626
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/// @inheritdoc IERC4626
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/// @inheritdoc IERC4626
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/// @inheritdoc IERC4626
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/// @inheritdoc IERC4626
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/// @inheritdoc IERC4626
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/// @inheritdoc IERC4626
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/// @inheritdoc IERC4626
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
// If asset() is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom(IERC20(asset()), caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If asset() is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer(IERC20(asset()), receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
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.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}// 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.4.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 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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.3.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 Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = 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 = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @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 {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(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 {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 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 low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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 ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, 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 high into low.
low |= high * 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 high
// is no longer required.
result = low * 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 Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @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.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/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)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";
/**
* @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.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* The following types are supported:
*
* - `bytes32` (`Bytes32Set`) since v3.3.0
* - `address` (`AddressSet`) since v3.3.0
* - `uint256` (`UintSet`) since v3.3.0
* - `string` (`StringSet`) since v5.4.0
* - `bytes` (`BytesSet`) since v5.4.0
*
* [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 Removes all the values from a set. O(n).
*
* WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
* using it may render the function uncallable if the set grows to the point where clearing it consumes too much
* gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) private view returns (bytes32[] memory) {
unchecked {
end = Math.min(end, _length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
// 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @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;
}
/**
* @dev Return a slice of the 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, uint256 start, uint256 end) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
struct StringSet {
// Storage of set values
string[] _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(string 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(StringSet storage set, string memory value) internal 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(StringSet storage set, string memory value) internal 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) {
string memory 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(StringSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(StringSet storage set, string memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(StringSet storage set) internal 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(StringSet storage set, uint256 index) internal view returns (string memory) {
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(StringSet storage set) internal view returns (string[] memory) {
return set._values;
}
/**
* @dev Return a slice of the 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(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
string[] memory result = new string[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
struct BytesSet {
// Storage of set values
bytes[] _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(bytes 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(BytesSet storage set, bytes memory value) internal 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(BytesSet storage set, bytes memory value) internal 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) {
bytes memory 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 Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(BytesSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(BytesSet storage set) internal 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(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
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(BytesSet storage set) internal view returns (bytes[] memory) {
return set._values;
}
/**
* @dev Return a slice of the 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(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes[] memory result = new bytes[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IAccessControlErrors} from "../interfaces/IAccessControlErrors.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title LimitedAccessControl
* @dev This contract extends OpenZeppelin's AccessControl, disabling direct role granting and revoking.
* It's designed to be used as a base contract for more specific access control implementations.
* @dev This contract overrides the grantRole and revokeRole functions from AccessControl to disable direct role
* granting and revoking.
* @dev It doesn't override the renounceRole function, so it can be used to renounce roles for compromised accounts.
*/
abstract contract LimitedAccessControl is AccessControl, IAccessControlErrors {
/**
* @dev Overrides the grantRole function from AccessControl to disable direct role granting.
* @notice This function always reverts with a DirectGrantIsDisabled error.
*/
function grantRole(bytes32, address) public view override {
revert DirectGrantIsDisabled(msg.sender);
}
/**
* @dev Overrides the revokeRole function from AccessControl to disable direct role revoking.
* @notice This function always reverts with a DirectRevokeIsDisabled error.
*/
function revokeRole(bytes32, address) public view override {
revert DirectRevokeIsDisabled(msg.sender);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IAccessControlErrors} from "../interfaces/IAccessControlErrors.sol";
import {ContractSpecificRoles, IProtocolAccessManager} from "../interfaces/IProtocolAccessManager.sol";
import {ProtocolAccessManager} from "./ProtocolAccessManager.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @title ProtocolAccessManaged
* @notice This contract provides role-based access control functionality for protocol contracts
* by interfacing with a central ProtocolAccessManager.
*
* @dev This contract is meant to be inherited by other protocol contracts that need
* role-based access control. It provides modifiers and utilities to check various roles.
*
* The contract supports several key roles through modifiers:
* 1. GOVERNOR_ROLE: System-wide administrators
* 2. KEEPER_ROLE: Routine maintenance operators (contract-specific)
* 3. SUPER_KEEPER_ROLE: Advanced maintenance operators (global)
* 4. CURATOR_ROLE: Fleet-specific managers
* 5. GUARDIAN_ROLE: Emergency response operators
* 6. DECAY_CONTROLLER_ROLE: Specific role for decay management
* 7. ADMIRALS_QUARTERS_ROLE: Specific role for admirals quarters bundler contract
*
* Usage:
* - Inherit from this contract to gain access to role-checking modifiers
* - Use modifiers like onlyGovernor, onlyKeeper, etc. to protect functions
* - Access the internal _accessManager to perform custom role checks
*
* Security Considerations:
* - The contract validates the access manager address during construction
* - All role checks are performed against the immutable access manager instance
* - Contract-specific roles are generated using the contract's address to prevent conflicts
*/
contract ProtocolAccessManaged is IAccessControlErrors, Context {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role identifier for protocol governors - highest privilege level with admin capabilities
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
/// @notice Role identifier for super keepers who can globally perform fleet maintanence roles
bytes32 public constant SUPER_KEEPER_ROLE = keccak256("SUPER_KEEPER_ROLE");
/**
* @notice Role identifier for protocol guardians
* @dev Guardians have emergency powers across multiple protocol components:
* - Can pause/unpause Fleet operations for security
* - Can pause/unpause TipJar operations
* - Can cancel governance proposals on SummerGovernor even if they don't meet normal cancellation requirements
* - Can cancel TipJar proposals
*
* The guardian role serves as an emergency backstop to protect the protocol, but with less
* privilege than governors.
*/
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/**
* @notice Role identifier for decay controller
* @dev This role allows the decay controller to manage the decay of user voting power
*/
bytes32 public constant DECAY_CONTROLLER_ROLE =
keccak256("DECAY_CONTROLLER_ROLE");
/**
* @notice Role identifier for admirals quarters bundler contract
* @dev This role allows Admirals Quarters to unstake and withdraw assets from fleets, on behalf of users
* @dev Withdrawn tokens go straight to users wallet, lowering the risk of manipulation if the role is compromised
*/
bytes32 public constant ADMIRALS_QUARTERS_ROLE =
keccak256("ADMIRALS_QUARTERS_ROLE");
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/// @notice The ProtocolAccessManager instance used for access control
ProtocolAccessManager internal immutable _accessManager;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the ProtocolAccessManaged contract
* @param accessManager Address of the ProtocolAccessManager contract
* @dev Validates the provided accessManager address and initializes the _accessManager
*/
constructor(address accessManager) {
if (accessManager == address(0)) {
revert InvalidAccessManagerAddress(address(0));
}
if (
!IERC165(accessManager).supportsInterface(
type(IProtocolAccessManager).interfaceId
)
) {
revert InvalidAccessManagerAddress(accessManager);
}
_accessManager = ProtocolAccessManager(accessManager);
}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Modifier to restrict access to governors only
*
* @dev Modifier to check that the caller has the Governor role
* @custom:internal-logic
* - Checks if the caller has the GOVERNOR_ROLE in the access manager
* @custom:effects
* - Reverts if the caller doesn't have the GOVERNOR_ROLE
* - Allows the function to proceed if the caller has the role
* @custom:security-considerations
* - Ensures that only authorized governors can access critical functions
* - Relies on the correct setup of the access manager
*/
modifier onlyGovernor() {
if (!_accessManager.hasRole(GOVERNOR_ROLE, msg.sender)) {
revert CallerIsNotGovernor(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to keepers only
* @dev Modifier to check that the caller has the Keeper role
* @custom:internal-logic
* - Checks if the caller has either the contract-specific KEEPER_ROLE or the SUPER_KEEPER_ROLE
* @custom:effects
* - Reverts if the caller doesn't have either of the required roles
* - Allows the function to proceed if the caller has one of the roles
* @custom:security-considerations
* - Ensures that only authorized keepers can access maintenance functions
* - Allows for both contract-specific and super keepers
* @custom:gas-considerations
* - Performs two role checks, which may impact gas usage
*/
modifier onlyKeeper() {
if (
!_accessManager.hasRole(
generateRole(ContractSpecificRoles.KEEPER_ROLE, address(this)),
msg.sender
) && !_accessManager.hasRole(SUPER_KEEPER_ROLE, msg.sender)
) {
revert CallerIsNotKeeper(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to super keepers only
* @dev Modifier to check that the caller has the Super Keeper role
* @custom:internal-logic
* - Checks if the caller has the SUPER_KEEPER_ROLE in the access manager
* @custom:effects
* - Reverts if the caller doesn't have the SUPER_KEEPER_ROLE
* - Allows the function to proceed if the caller has the role
* @custom:security-considerations
* - Ensures that only authorized super keepers can access advanced maintenance functions
* - Relies on the correct setup of the access manager
*/
modifier onlySuperKeeper() {
if (!_accessManager.hasRole(SUPER_KEEPER_ROLE, msg.sender)) {
revert CallerIsNotSuperKeeper(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to curators only
* @param fleetAddress The address of the fleet to check the curator role for
* @dev Checks if the caller has the contract-specific CURATOR_ROLE
*/
modifier onlyCurator(address fleetAddress) {
if (
fleetAddress == address(0) ||
!_accessManager.hasRole(
generateRole(ContractSpecificRoles.CURATOR_ROLE, fleetAddress),
msg.sender
)
) {
revert CallerIsNotCurator(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to guardians only
* @dev Modifier to check that the caller has the Guardian role
* @custom:internal-logic
* - Checks if the caller has the GUARDIAN_ROLE in the access manager
* @custom:effects
* - Reverts if the caller doesn't have the GUARDIAN_ROLE
* - Allows the function to proceed if the caller has the role
* @custom:security-considerations
* - Ensures that only authorized guardians can access emergency functions
* - Relies on the correct setup of the access manager
*/
modifier onlyGuardian() {
if (!_accessManager.hasRole(GUARDIAN_ROLE, msg.sender)) {
revert CallerIsNotGuardian(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to either guardians or governors
* @dev Modifier to check that the caller has either the Guardian or Governor role
* @custom:internal-logic
* - Checks if the caller has either the GUARDIAN_ROLE or the GOVERNOR_ROLE
* @custom:effects
* - Reverts if the caller doesn't have either of the required roles
* - Allows the function to proceed if the caller has one of the roles
* @custom:security-considerations
* - Ensures that only authorized guardians or governors can access certain functions
* - Provides flexibility for functions that can be accessed by either role
* @custom:gas-considerations
* - Performs two role checks, which may impact gas usage
*/
modifier onlyGuardianOrGovernor() {
if (
!_accessManager.hasRole(GUARDIAN_ROLE, msg.sender) &&
!_accessManager.hasRole(GOVERNOR_ROLE, msg.sender)
) {
revert CallerIsNotGuardianOrGovernor(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to decay controllers only
*/
modifier onlyDecayController() {
if (!_accessManager.hasRole(DECAY_CONTROLLER_ROLE, msg.sender)) {
revert CallerIsNotDecayController(msg.sender);
}
_;
}
/**
* @notice Modifier to restrict access to foundation only
* @dev Modifier to check that the caller has the Foundation role
* @custom:security-considerations
* - Ensures that only the Foundation can access vesting and related functions
* - Relies on the correct setup of the access manager
*/
modifier onlyFoundation() {
if (
!_accessManager.hasRole(
_accessManager.FOUNDATION_ROLE(),
msg.sender
)
) {
revert CallerIsNotFoundation(msg.sender);
}
_;
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Generates a role identifier for a specific contract and role
* @param roleName The name of the role
* @param roleTargetContract The address of the contract the role is for
* @return The generated role identifier
* @dev This function is used to create unique role identifiers for contract-specific roles
*/
function generateRole(
ContractSpecificRoles roleName,
address roleTargetContract
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(roleName, roleTargetContract));
}
/**
* @notice Checks if an account has the Admirals Quarters role
* @param account The address to check
* @return bool True if the account has the Admirals Quarters role
*/
function hasAdmiralsQuartersRole(
address account
) public view returns (bool) {
return _accessManager.hasRole(ADMIRALS_QUARTERS_ROLE, account);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Helper function to check if an address has the Governor role
* @param account The address to check
* @return bool True if the address has the Governor role
*/
function _isGovernor(address account) internal view returns (bool) {
return _accessManager.hasRole(GOVERNOR_ROLE, account);
}
function _isDecayController(address account) internal view returns (bool) {
return _accessManager.hasRole(DECAY_CONTROLLER_ROLE, account);
}
/**
* @notice Helper function to check if an address has the Foundation role
* @param account The address to check
* @return bool True if the address has the Foundation role
*/
function _isFoundation(address account) internal view returns (bool) {
return
_accessManager.hasRole(_accessManager.FOUNDATION_ROLE(), account);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ContractSpecificRoles, IProtocolAccessManager} from "../interfaces/IProtocolAccessManager.sol";
import {LimitedAccessControl} from "./LimitedAccessControl.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @title ProtocolAccessManager
* @notice This contract is the central authority for access control within the protocol.
* It defines and manages various roles that govern different aspects of the system.
*
* @dev This contract extends LimitedAccessControl, which restricts direct role management.
* Roles are typically assigned during deployment or through governance proposals.
*
* The contract defines four main roles:
* 1. GOVERNOR_ROLE: System-wide administrators
* 2. KEEPER_ROLE: Routine maintenance operators
* 3. SUPER_KEEPER_ROLE: Advanced maintenance operators
* 4. COMMANDER_ROLE: Managers of specific protocol components (Arks)
* 5. ADMIRALS_QUARTERS_ROLE: Specific role for admirals quarters bundler contract
* Role Hierarchy and Management:
* - The GOVERNOR_ROLE is at the top of the hierarchy and can manage all other roles.
* - Other roles cannot manage roles directly due to LimitedAccessControl restrictions.
* - Role assignments are typically done through governance proposals or during initial setup.
*
* Usage in the System:
* - Other contracts in the system inherit from ProtocolAccessManaged, which checks permissions
* against this ProtocolAccessManager.
* - Critical functions in various contracts are protected by role-based modifiers
* (e.g., onlyGovernor, onlyKeeper, etc.) which query this contract for permissions.
*
* Security Considerations:
* - The GOVERNOR_ROLE has significant power and should be managed carefully, potentially
* through a multi-sig wallet or governance contract.
* - The SUPER_KEEPER_ROLE has elevated privileges and should be assigned judiciously.
* - The COMMANDER_ROLE is not directly manageable through this contract but is used
* in other parts of the system for specific access control.
*/
contract ProtocolAccessManager is IProtocolAccessManager, LimitedAccessControl {
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role identifier for protocol governors - highest privilege level with admin capabilities
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
/// @notice Role identifier for super keepers who can globally perform fleet maintanence roles
bytes32 public constant SUPER_KEEPER_ROLE = keccak256("SUPER_KEEPER_ROLE");
/**
* @notice Role identifier for protocol guardians
* @dev Guardians have emergency powers across multiple protocol components:
* - Can pause/unpause Fleet operations for security
* - Can pause/unpause TipJar operations
* - Can cancel governance proposals on SummerGovernor even if they don't meet normal cancellation requirements
* - Can cancel TipJar proposals
*
* The guardian role serves as an emergency backstop to protect the protocol, but with less
* privilege than governors.
*/
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/**
* @notice Role identifier for decay controller
* @dev This role allows the decay controller to manage the decay of user voting power
*/
bytes32 public constant DECAY_CONTROLLER_ROLE =
keccak256("DECAY_CONTROLLER_ROLE");
/**
* @notice Role identifier for admirals quarters bundler contract
* @dev This role allows Admirals Quarters to unstake and withdraw assets from fleets, on behalf of users
* @dev Withdrawn tokens go straight to users wallet, lowering the risk of manipulation if the role is compromised
*/
bytes32 public constant ADMIRALS_QUARTERS_ROLE =
keccak256("ADMIRALS_QUARTERS_ROLE");
/// @notice Minimum allowed guardian expiration period (7 days)
uint256 public constant MIN_GUARDIAN_EXPIRY = 7 days;
/// @notice Maximum allowed guardian expiration period (180 days)
uint256 public constant MAX_GUARDIAN_EXPIRY = 180 days;
/// @notice Role identifier for the Foundation which manages vesting wallets and related operations
bytes32 public constant FOUNDATION_ROLE = keccak256("FOUNDATION_ROLE");
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the ProtocolAccessManager contract
* @param governor Address of the initial governor
* @dev Grants the governor address the GOVERNOR_ROLE
*/
constructor(address governor) {
_grantRole(GOVERNOR_ROLE, governor);
}
/**
* @dev Modifier to check that the caller has the Governor role
*/
modifier onlyGovernor() {
if (!hasRole(GOVERNOR_ROLE, msg.sender)) {
revert CallerIsNotGovernor(msg.sender);
}
_;
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if the contract supports a given interface
* @dev Overrides the supportsInterface function from AccessControl
* @param interfaceId The interface identifier, as specified in ERC-165
* @return bool True if the contract supports the interface, false otherwise
*
* This function supports:
* - IProtocolAccessManager interface
* - All interfaces supported by the parent AccessControl contract
*/
function supportsInterface(
bytes4 interfaceId
) public view override returns (bool) {
return
interfaceId == type(IProtocolAccessManager).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc IProtocolAccessManager
function grantGovernorRole(address account) external onlyGovernor {
_grantRole(GOVERNOR_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeGovernorRole(address account) external onlyGovernor {
_revokeRole(GOVERNOR_ROLE, account);
}
/*//////////////////////////////////////////////////////////////
EXTERNAL GOVERNOR FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IProtocolAccessManager
function grantSuperKeeperRole(address account) external onlyGovernor {
_grantRole(SUPER_KEEPER_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function grantGuardianRole(address account) external onlyGovernor {
_grantRole(GUARDIAN_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeGuardianRole(address account) external onlyGovernor {
_revokeRole(GUARDIAN_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeSuperKeeperRole(address account) external onlyGovernor {
_revokeRole(SUPER_KEEPER_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function grantContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address roleOwner
) public onlyGovernor {
bytes32 role = generateRole(roleName, roleTargetContract);
_grantRole(role, roleOwner);
}
/// @inheritdoc IProtocolAccessManager
function revokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address roleOwner
) public onlyGovernor {
bytes32 role = generateRole(roleName, roleTargetContract);
_revokeRole(role, roleOwner);
}
/// @inheritdoc IProtocolAccessManager
function grantCuratorRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
grantContractSpecificRole(
ContractSpecificRoles.CURATOR_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function revokeCuratorRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
revokeContractSpecificRole(
ContractSpecificRoles.CURATOR_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function grantKeeperRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
grantContractSpecificRole(
ContractSpecificRoles.KEEPER_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function revokeKeeperRole(
address fleetCommanderAddress,
address account
) public onlyGovernor {
revokeContractSpecificRole(
ContractSpecificRoles.KEEPER_ROLE,
fleetCommanderAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function grantCommanderRole(
address arkAddress,
address account
) public onlyGovernor {
grantContractSpecificRole(
ContractSpecificRoles.COMMANDER_ROLE,
arkAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function revokeCommanderRole(
address arkAddress,
address account
) public onlyGovernor {
revokeContractSpecificRole(
ContractSpecificRoles.COMMANDER_ROLE,
arkAddress,
account
);
}
/// @inheritdoc IProtocolAccessManager
function grantDecayControllerRole(address account) public onlyGovernor {
_grantRole(DECAY_CONTROLLER_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeDecayControllerRole(address account) public onlyGovernor {
_revokeRole(DECAY_CONTROLLER_ROLE, account);
}
/*//////////////////////////////////////////////////////////////
PUBLIC FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IProtocolAccessManager
function selfRevokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract
) public {
bytes32 role = generateRole(roleName, roleTargetContract);
if (!hasRole(role, msg.sender)) {
revert CallerIsNotContractSpecificRole(msg.sender, role);
}
_revokeRole(role, msg.sender);
}
/// @inheritdoc IProtocolAccessManager
function generateRole(
ContractSpecificRoles roleName,
address roleTargetContract
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(roleName, roleTargetContract));
}
/// @inheritdoc IProtocolAccessManager
function grantAdmiralsQuartersRole(
address account
) external onlyRole(GOVERNOR_ROLE) {
_grantRole(ADMIRALS_QUARTERS_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeAdmiralsQuartersRole(
address account
) external onlyRole(GOVERNOR_ROLE) {
_revokeRole(ADMIRALS_QUARTERS_ROLE, account);
}
mapping(address guardian => uint256 expirationTimestamp)
public guardianExpirations;
/**
* @notice Checks if an account is an active guardian (has role and not expired)
* @param account Address to check
* @return bool True if account is an active guardian
*/
function isActiveGuardian(address account) public view returns (bool) {
return
hasRole(GUARDIAN_ROLE, account) &&
guardianExpirations[account] > block.timestamp;
}
/**
* @notice Sets the expiration timestamp for a guardian
* @param account Guardian address
* @param expiration Timestamp when guardian powers expire
* @dev The expiration period (time from now until expiration) must be between MIN_GUARDIAN_EXPIRY and MAX_GUARDIAN_EXPIRY
* This ensures guardians can't be immediately removed (protecting against malicious proposals) while still
* allowing for their eventual phase-out (protecting against malicious guardians)
*/
function setGuardianExpiration(
address account,
uint256 expiration
) external onlyRole(GOVERNOR_ROLE) {
if (!hasRole(GUARDIAN_ROLE, account)) {
revert CallerIsNotGuardian(account);
}
uint256 expiryPeriod = expiration - block.timestamp;
if (
expiryPeriod < MIN_GUARDIAN_EXPIRY ||
expiryPeriod > MAX_GUARDIAN_EXPIRY
) {
revert InvalidGuardianExpiryPeriod(
expiryPeriod,
MIN_GUARDIAN_EXPIRY,
MAX_GUARDIAN_EXPIRY
);
}
guardianExpirations[account] = expiration;
emit GuardianExpirationSet(account, expiration);
}
/**
* @inheritdoc IProtocolAccessManager
*/
function hasRole(
bytes32 role,
address account
)
public
view
virtual
override(IProtocolAccessManager, AccessControl)
returns (bool)
{
return super.hasRole(role, account);
}
/// @inheritdoc IProtocolAccessManager
function getGuardianExpiration(
address account
) external view returns (uint256 expiration) {
if (!hasRole(GUARDIAN_ROLE, account)) {
revert CallerIsNotGuardian(account);
}
return guardianExpirations[account];
}
/// @inheritdoc IProtocolAccessManager
function grantFoundationRole(address account) external onlyGovernor {
_grantRole(FOUNDATION_ROLE, account);
}
/// @inheritdoc IProtocolAccessManager
function revokeFoundationRole(address account) external onlyGovernor {
_revokeRole(FOUNDATION_ROLE, account);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IAccessControlErrors
* @dev This file contains custom error definitions for access control in the system.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IAccessControlErrors {
/**
* @notice Thrown when a caller does not have the required role.
*/
error CallerIsNotContractSpecificRole(address caller, bytes32 role);
/**
* @notice Thrown when a caller is not the curator.
*/
error CallerIsNotCurator(address caller);
/**
* @notice Thrown when a caller is not the governor.
*/
error CallerIsNotGovernor(address caller);
/**
* @notice Thrown when a caller is not a keeper.
*/
error CallerIsNotKeeper(address caller);
/**
* @notice Thrown when a caller is not a super keeper.
*/
error CallerIsNotSuperKeeper(address caller);
/**
* @notice Thrown when a caller is not the commander.
*/
error CallerIsNotCommander(address caller);
/**
* @notice Thrown when a caller is neither the Raft nor the commander.
*/
error CallerIsNotRaftOrCommander(address caller);
/**
* @notice Thrown when a caller is not the Raft.
*/
error CallerIsNotRaft(address caller);
/**
* @notice Thrown when a caller is not an admin.
*/
error CallerIsNotAdmin(address caller);
/**
* @notice Thrown when a caller is not the guardian.
*/
error CallerIsNotGuardian(address caller);
/**
* @notice Thrown when a caller is not the guardian or governor.
*/
error CallerIsNotGuardianOrGovernor(address caller);
/**
* @notice Thrown when a caller is not the decay controller.
*/
error CallerIsNotDecayController(address caller);
/**
* @notice Thrown when a caller is not authorized to board.
*/
error CallerIsNotAuthorizedToBoard(address caller);
/**
* @notice Thrown when direct grant is disabled.
*/
error DirectGrantIsDisabled(address caller);
/**
* @notice Thrown when direct revoke is disabled.
*/
error DirectRevokeIsDisabled(address caller);
/**
* @notice Thrown when an invalid access manager address is provided.
*/
error InvalidAccessManagerAddress(address invalidAddress);
/**
* @notice Error thrown when a caller is not the Foundation
* @param caller The address that attempted the operation
*/
error CallerIsNotFoundation(address caller);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
/**
* @dev Dynamic roles are roles that are not hardcoded in the contract but are defined by the protocol
* Members of this enum are treated as prefixes to the role generated using prefix and target contract address
* e.g generateRole(ContractSpecificRoles.CURATOR_ROLE, address(this)) for FleetCommander, to generate the CURATOR_ROLE
* for the curator of the FleetCommander contract
*/
enum ContractSpecificRoles {
CURATOR_ROLE,
KEEPER_ROLE,
COMMANDER_ROLE
}
/**
* @title IProtocolAccessManager
* @notice Defines system roles and provides role based remote-access control for
* contracts that inherit from ProtocolAccessManaged contract
*/
interface IProtocolAccessManager {
/**
* @notice Grants the Governor role to a given account
*
* @param account The account to which the Governor role will be granted
*/
function grantGovernorRole(address account) external;
/**
* @notice Revokes the Governor role from a given account
*
* @param account The account from which the Governor role will be revoked
*/
function revokeGovernorRole(address account) external;
/**
* @notice Grants the Super Keeper role to a given account
*
* @param account The account to which the Super Keeper role will be granted
*/
function grantSuperKeeperRole(address account) external;
/**
* @notice Revokes the Super Keeper role from a given account
*
* @param account The account from which the Super Keeper role will be revoked
*/
function revokeSuperKeeperRole(address account) external;
/**
* @dev Generates a unique role identifier based on the role name and target contract address
* @param roleName The name of the role (from ContractSpecificRoles enum)
* @param roleTargetContract The address of the contract the role is for
* @return bytes32 The generated role identifier
* @custom:internal-logic
* - Combines the roleName and roleTargetContract using abi.encodePacked
* - Applies keccak256 hash function to generate a unique bytes32 identifier
* @custom:effects
* - Does not modify any state, pure function
* @custom:security-considerations
* - Ensures unique role identifiers for different contracts
* - Relies on the uniqueness of contract addresses and role names
*/
function generateRole(
ContractSpecificRoles roleName,
address roleTargetContract
) external pure returns (bytes32);
/**
* @notice Grants a contract specific role to a given account
* @param roleName The name of the role to grant
* @param roleTargetContract The address of the contract to grant the role for
* @param account The account to which the role will be granted
*/
function grantContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address account
) external;
/**
* @notice Revokes a contract specific role from a given account
* @param roleName The name of the role to revoke
* @param roleTargetContract The address of the contract to revoke the role for
* @param account The account from which the role will be revoked
*/
function revokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract,
address account
) external;
/**
* @notice Grants the Curator role to a given account
* @param fleetCommanderAddress The address of the fleet commander to grant the role for
* @param account The account to which the role will be granted
*/
function grantCuratorRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Revokes the Curator role from a given account
* @param fleetCommanderAddress The address of the fleet commander to revoke the role for
* @param account The account from which the role will be revoked
*/
function revokeCuratorRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Grants the Keeper role to a given account
* @param fleetCommanderAddress The address of the fleet commander to grant the role for
* @param account The account to which the role will be granted
*/
function grantKeeperRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Revokes the Keeper role from a given account
* @param fleetCommanderAddress The address of the fleet commander to revoke the role for
* @param account The account from which the role will be revoked
*/
function revokeKeeperRole(
address fleetCommanderAddress,
address account
) external;
/**
* @notice Grants the Commander role for a specific Ark
* @param arkAddress Address of the Ark contract
* @param account Address to grant the Commander role to
*/
function grantCommanderRole(address arkAddress, address account) external;
/**
* @notice Revokes the Commander role for a specific Ark
* @param arkAddress Address of the Ark contract
* @param account Address to revoke the Commander role from
*/
function revokeCommanderRole(address arkAddress, address account) external;
/**
* @notice Revokes a contract specific role from the caller
* @param roleName The name of the role to revoke
* @param roleTargetContract The address of the contract to revoke the role for
*/
function selfRevokeContractSpecificRole(
ContractSpecificRoles roleName,
address roleTargetContract
) external;
/**
* @notice Grants the Guardian role to a given account
*
* @param account The account to which the Guardian role will be granted
*/
function grantGuardianRole(address account) external;
/**
* @notice Revokes the Guardian role from a given account
*
* @param account The account from which the Guardian role will be revoked
*/
function revokeGuardianRole(address account) external;
/**
* @notice Grants the Decay Controller role to a given account
* @param account The account to which the Decay Controller role will be granted
*/
function grantDecayControllerRole(address account) external;
/**
* @notice Revokes the Decay Controller role from a given account
* @param account The account from which the Decay Controller role will be revoked
*/
function revokeDecayControllerRole(address account) external;
/**
* @notice Grants the ADMIRALS_QUARTERS_ROLE to an address
* @param account The address to grant the role to
*/
function grantAdmiralsQuartersRole(address account) external;
/**
* @notice Revokes the ADMIRALS_QUARTERS_ROLE from an address
* @param account The address to revoke the role from
*/
function revokeAdmiralsQuartersRole(address account) external;
/*//////////////////////////////////////////////////////////////
ROLE CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Role identifier for the Governor role
function GOVERNOR_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Guardian role
function GUARDIAN_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Super Keeper role
function SUPER_KEEPER_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Decay Controller role
function DECAY_CONTROLLER_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Admirals Quarters role
function ADMIRALS_QUARTERS_ROLE() external pure returns (bytes32);
/// @notice Role identifier for the Foundation, responsible for managing vesting wallets and related operations
function FOUNDATION_ROLE() external pure returns (bytes32);
/**
* @notice Checks if an account has a specific role
* @param role The role identifier to check
* @param account The account to check the role for
* @return bool True if the account has the role, false otherwise
*/
function hasRole(
bytes32 role,
address account
) external view returns (bool);
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/**
* @notice Emitted when a guardian's expiration is set
* @param account The address of the guardian
* @param expiration The timestamp until which the guardian powers are valid
*/
event GuardianExpirationSet(address indexed account, uint256 expiration);
/*//////////////////////////////////////////////////////////////
GUARDIAN FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Checks if an account is an active guardian (has role and not expired)
* @param account Address to check
* @return bool True if account is an active guardian
*/
function isActiveGuardian(address account) external view returns (bool);
/**
* @notice Sets the expiration timestamp for a guardian
* @param account Guardian address
* @param expiration Timestamp when guardian powers expire
*/
function setGuardianExpiration(
address account,
uint256 expiration
) external;
/**
* @notice Gets the expiration timestamp for a guardian
* @param account Guardian address
* @return uint256 Timestamp when guardian powers expire
*/
function guardianExpirations(
address account
) external view returns (uint256);
/**
* @notice Gets the expiration timestamp for a guardian
* @param account Guardian address
* @return expiration Timestamp when guardian powers expire
*/
function getGuardianExpiration(
address account
) external view returns (uint256 expiration);
/**
* @notice Emitted when an invalid guardian expiry period is set
* @param expiryPeriod The expiry period that was set
* @param minExpiryPeriod The minimum allowed expiry period
* @param maxExpiryPeriod The maximum allowed expiry period
*/
error InvalidGuardianExpiryPeriod(
uint256 expiryPeriod,
uint256 minExpiryPeriod,
uint256 maxExpiryPeriod
);
/**
* @notice Grants the Foundation role to a given account. The Foundation is responsible for
* managing vesting wallets and related operations.
* @param account The account to which the Foundation role will be granted
*/
function grantFoundationRole(address account) external;
/**
* @notice Revokes the Foundation role from a given account
* @param account The account from which the Foundation role will be revoked
*/
function revokeFoundationRole(address account) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IConfigurationManaged} from "../interfaces/IConfigurationManaged.sol";
import {IConfigurationManager} from "../interfaces/IConfigurationManager.sol";
/**
* @title ConfigurationManaged
* @notice Base contract for contracts that need to read from the ConfigurationManager
* @custom:see IConfigurationManaged
*/
abstract contract ConfigurationManaged is IConfigurationManaged {
IConfigurationManager public immutable configurationManager;
/**
* @notice Constructs the ConfigurationManaged contract
* @param _configurationManager The address of the ConfigurationManager contract
*/
constructor(address _configurationManager) {
if (_configurationManager == address(0)) {
revert ConfigurationManagerZeroAddress();
}
configurationManager = IConfigurationManager(_configurationManager);
}
/// @inheritdoc IConfigurationManaged
function raft() public view virtual returns (address) {
return configurationManager.raft();
}
/// @inheritdoc IConfigurationManaged
function tipJar() public view virtual returns (address) {
return configurationManager.tipJar();
}
/// @inheritdoc IConfigurationManaged
function treasury() public view virtual returns (address) {
return configurationManager.treasury();
}
/// @inheritdoc IConfigurationManaged
function harborCommand() public view virtual returns (address) {
return configurationManager.harborCommand();
}
/// @inheritdoc IConfigurationManaged
function fleetCommanderRewardsManagerFactory()
public
view
virtual
returns (address)
{
return configurationManager.fleetCommanderRewardsManagerFactory();
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IConfigurationManagerErrors
* @dev This file contains custom error definitions for the ConfigurationManager contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IConfigurationManagerErrors {
/**
* @notice Thrown when ConfigurationManager was already initialized.
*/
error ConfigurationManagerAlreadyInitialized();
/**
* @notice Thrown when the Raft address is not set.
*/
error RaftNotSet();
/**
* @notice Thrown when the TipJar address is not set.
*/
error TipJarNotSet();
/**
* @notice Thrown when the Treasury address is not set.
*/
error TreasuryNotSet();
/**
* @notice Thrown when constructor address is set to the zero address.
*/
error AddressZero();
/**
* @notice Thrown when the HarborCommand address is not set.
*/
error HarborCommandNotSet();
/**
* @notice Thrown when a feature is not supported.
*/
error NotSupported();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IConfigurationManagerEvents
* @notice Interface for events emitted by the Configuration Manager
*/
interface IConfigurationManagerEvents {
/**
* @notice Emitted when the Raft address is updated
* @param newRaft The address of the new Raft
*/
event RaftUpdated(address oldRaft, address newRaft);
/**
* @notice Emitted when the tip jar address is updated
* @param newTipJar The address of the new tip jar
*/
event TipJarUpdated(address oldTipJar, address newTipJar);
/**
* @notice Emitted when the tip rate is updated
* @param newTipRate The new tip rate value
*/
event TipRateUpdated(uint8 oldTipRate, uint8 newTipRate);
/**
* @notice Emitted when the Treasury address is updated
* @param newTreasury The address of the new Treasury
*/
event TreasuryUpdated(address oldTreasury, address newTreasury);
/**
* @notice Emitted when the Harbor Command address is updated
* @param oldHarborCommand The address of the old Harbor Command
* @param newHarborCommand The address of the new Harbor Command
*/
event HarborCommandUpdated(
address oldHarborCommand,
address newHarborCommand
);
/**
* @notice Emitted when the Fleet Commander Rewards Manager Factory address is updated
* @param oldFleetCommanderRewardsManagerFactory The address of the old Fleet Commander Rewards Manager Factory
* @param newFleetCommanderRewardsManagerFactory The address of the new Fleet Commander Rewards Manager Factory
*/
event FleetCommanderRewardsManagerFactoryUpdated(
address oldFleetCommanderRewardsManagerFactory,
address newFleetCommanderRewardsManagerFactory
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IConfigurationManager} from "./IConfigurationManager.sol";
/**
* @title IConfigurationManaged
* @notice Interface for contracts that need to read from the ConfigurationManager
* @dev This interface defines the standard methods for accessing configuration values
* from the ConfigurationManager. It should be implemented by contracts that
* need to read these configurations.
*/
interface IConfigurationManaged {
/**
* @notice Gets the address of the ConfigurationManager contract
* @return The address of the ConfigurationManager contract
*/
function configurationManager()
external
view
returns (IConfigurationManager);
/**
* @notice Gets the address of the Raft contract
* @return The address of the Raft contract
*/
function raft() external view returns (address);
/**
* @notice Gets the address of the TipJar contract
* @return The address of the TipJar contract
*/
function tipJar() external view returns (address);
/**
* @notice Gets the address of the Treasury contract
* @return The address of the Treasury contract
*/
function treasury() external view returns (address);
/**
* @notice Gets the address of the HarborCommand contract
* @return The address of the HarborCommand contract
*/
function harborCommand() external view returns (address);
/**
* @notice Gets the address of the Fleet Commander Rewards Manager Factory contract
* @return The address of the Fleet Commander Rewards Manager Factory contract
*/
function fleetCommanderRewardsManagerFactory()
external
view
returns (address);
error ConfigurationManagerZeroAddress();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IConfigurationManagerErrors} from "../errors/IConfigurationManagerErrors.sol";
import {IConfigurationManagerEvents} from "../events/IConfigurationManagerEvents.sol";
import {ConfigurationManagerParams} from "../types/ConfigurationManagerTypes.sol";
/**
* @title IConfigurationManager
* @notice Interface for the ConfigurationManager contract, which manages system-wide parameters
* @dev This interface defines the getters and setters for system-wide parameters
*/
interface IConfigurationManager is
IConfigurationManagerEvents,
IConfigurationManagerErrors
{
/**
* @notice Initialize the configuration with the given parameters
* @param params The parameters to initialize the configuration with
* @dev Can only be called by the governor
*/
function initializeConfiguration(
ConfigurationManagerParams memory params
) external;
/**
* @notice Get the address of the Raft contract
* @return The address of the Raft contract
* @dev This is where rewards and farmed tokens are sent for processing
*/
function raft() external view returns (address);
/**
* @notice Get the current tip jar address
* @return The current tip jar address
* @dev This is the contract that owns tips and is responsible for
* dispensing them to claimants
*/
function tipJar() external view returns (address);
/**
* @notice Get the current treasury address
* @return The current treasury address
* @dev This is the contract that owns the treasury and is responsible for
* dispensing funds to the protocol's operations
*/
function treasury() external view returns (address);
/**
* @notice Get the address of theHarbor command
* @return The address of theHarbor command
* @dev This is the contract that's the registry of all Fleet Commanders
*/
function harborCommand() external view returns (address);
/**
* @notice Get the address of the Fleet Commander Rewards Manager Factory contract
* @return The address of the Fleet Commander Rewards Manager Factory contract
*/
function fleetCommanderRewardsManagerFactory()
external
view
returns (address);
/**
* @notice Set a new address for the Raft contract
* @param newRaft The new address for the Raft contract
* @dev Can only be called by the governor
*/
function setRaft(address newRaft) external;
/**
* @notice Set a new tip ar address
* @param newTipJar The address of the new tip jar
* @dev Can only be called by the governor
*/
function setTipJar(address newTipJar) external;
/**
* @notice Set a new treasury address
* @param newTreasury The address of the new treasury
* @dev Can only be called by the governor
*/
function setTreasury(address newTreasury) external;
/**
* @notice Set a new harbor command address
* @param newHarborCommand The address of the new harbor command
* @dev Can only be called by the governor
*/
function setHarborCommand(address newHarborCommand) external;
/**
* @notice Set a new fleet commander rewards manager factory address
* @param newFleetCommanderRewardsManagerFactory The address of the new fleet commander rewards manager factory
* @dev Can only be called by the governor
*/
function setFleetCommanderRewardsManagerFactory(
address newFleetCommanderRewardsManagerFactory
) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @notice Initialization parameters for the ConfigurationManager contract
*/
struct ConfigurationManagerParams {
address raft;
address tipJar;
address treasury;
address harborCommand;
address fleetCommanderRewardsManagerFactory;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Constants {
// WAD: Common unit, stands for "18 decimals"
uint256 public constant WAD = 1e18;
// RAY: Higher precision unit, "27 decimals"
uint256 public constant RAY = 1e27;
// Conversion factor from WAD to RAY
uint256 public constant WAD_TO_RAY = 1e9;
// Number of seconds in a day
uint256 public constant SECONDS_PER_DAY = 1 days;
// Number of seconds in a year (assuming 365 days)
uint256 public constant SECONDS_PER_YEAR = 365 days;
// Maximum value for uint256
uint256 public constant MAX_UINT256 = type(uint256).max;
// AAVE V3 POOL CONFIG DATA MASK
uint256 internal constant ACTIVE_MASK =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF;
uint256 internal constant FROZEN_MASK =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF;
uint256 internal constant PAUSED_MASK =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFF;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* Since version 5.1, this library also support writing and reading value types to and from transient storage.
*
* * Example using transient storage:
* ```solidity
* contract Lock {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(
bytes32 slot
) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(
bytes32 slot
) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(
bytes32 slot
) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(
bytes32 slot
) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(
bytes32 slot
) internal pure returns (Int256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(
bytes32 slot
) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(
string storage store
) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(
bytes32 slot
) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(
bytes storage store
) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlotType.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlotType) {
return AddressSlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlotType.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlotType) {
return BooleanSlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32SlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32SlotType.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32SlotType) {
return Bytes32SlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256SlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256SlotType.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256SlotType) {
return Uint256SlotType.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256SlotType is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256SlotType.
*/
function asInt256(bytes32 slot) internal pure returns (Int256SlotType) {
return Int256SlotType.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlotType slot) internal view returns (address value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlotType slot, address value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlotType slot) internal view returns (bool value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlotType slot, bool value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32SlotType slot) internal view returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32SlotType slot, bytes32 value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256SlotType slot) internal view returns (uint256 value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256SlotType slot, uint256 value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256SlotType slot) internal view returns (int256 value) {
/// @solidity memory-safe-assembly
assembly {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256SlotType slot, int256 value) internal {
/// @solidity memory-safe-assembly
assembly {
tstore(slot, value)
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title Percentage
* @author Roberto Cano
* @notice Custom type for Percentage values with associated utility functions
* @dev This contract defines a custom Percentage type and overloaded operators
* to perform arithmetic and comparison operations on Percentage values.
*/
/**
* @dev Custom percentage type as uint256
* @notice This type is used to represent percentage values with high precision
*/
type Percentage is uint256;
/**
* @dev Overridden operators declaration for Percentage
* @notice These operators allow for intuitive arithmetic and comparison operations
* on Percentage values
*/
using {
add as +,
subtract as -,
multiply as *,
divide as /,
lessOrEqualThan as <=,
lessThan as <,
greaterOrEqualThan as >=,
greaterThan as >,
equalTo as ==
} for Percentage global;
/**
* @dev The number of decimals used for the percentage
* This constant defines the precision of the Percentage type
*/
uint256 constant PERCENTAGE_DECIMALS = 18;
/**
* @dev The factor used to scale the percentage
* This constant is used to convert between human-readable percentages
* and the internal representation
*/
uint256 constant PERCENTAGE_FACTOR = 10 ** PERCENTAGE_DECIMALS;
/**
* @dev Percentage of 100% with the given `PERCENTAGE_DECIMALS`
* This constant represents 100% in the Percentage type
*/
Percentage constant PERCENTAGE_100 = Percentage.wrap(100 * PERCENTAGE_FACTOR);
/**
* @dev Percentage of 1 with the given `PERCENTAGE_DECIMALS`
* This constant represents 1 in the Percentage type
*/
Percentage constant PERCENTAGE_1 = Percentage.wrap(PERCENTAGE_FACTOR);
/**
* OPERATOR FUNCTIONS
*/
/**
* @dev Adds two Percentage values
* @param a The first Percentage value
* @param b The second Percentage value
* @return The sum of a and b as a Percentage
*/
function add(Percentage a, Percentage b) pure returns (Percentage) {
return Percentage.wrap(Percentage.unwrap(a) + Percentage.unwrap(b));
}
/**
* @dev Subtracts one Percentage value from another
* @param a The Percentage value to subtract from
* @param b The Percentage value to subtract
* @return The difference between a and b as a Percentage
*/
function subtract(Percentage a, Percentage b) pure returns (Percentage) {
return Percentage.wrap(Percentage.unwrap(a) - Percentage.unwrap(b));
}
/**
* @dev Multiplies two Percentage values
* @param a The first Percentage value
* @param b The second Percentage value
* @return The product of a and b as a Percentage, scaled appropriately
*/
function multiply(Percentage a, Percentage b) pure returns (Percentage) {
return
Percentage.wrap(
(Percentage.unwrap(a) * Percentage.unwrap(b)) /
Percentage.unwrap(PERCENTAGE_100)
);
}
/**
* @dev Divides one Percentage value by another
* @param a The Percentage value to divide
* @param b The Percentage value to divide by
* @return The quotient of a divided by b as a Percentage, scaled appropriately
*/
function divide(Percentage a, Percentage b) pure returns (Percentage) {
return
Percentage.wrap(
(Percentage.unwrap(a) * Percentage.unwrap(PERCENTAGE_100)) /
Percentage.unwrap(b)
);
}
/**
* @dev Checks if one Percentage value is less than or equal to another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is less than or equal to b, false otherwise
*/
function lessOrEqualThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) <= Percentage.unwrap(b);
}
/**
* @dev Checks if one Percentage value is less than another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is less than b, false otherwise
*/
function lessThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) < Percentage.unwrap(b);
}
/**
* @dev Checks if one Percentage value is greater than or equal to another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is greater than or equal to b, false otherwise
*/
function greaterOrEqualThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) >= Percentage.unwrap(b);
}
/**
* @dev Checks if one Percentage value is greater than another
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is greater than b, false otherwise
*/
function greaterThan(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) > Percentage.unwrap(b);
}
/**
* @dev Checks if two Percentage values are equal
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is equal to b, false otherwise
*/
function equalTo(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) == Percentage.unwrap(b);
}
/**
* @dev Alias for equalTo function
* @param a The first Percentage value
* @param b The second Percentage value
* @return True if a is equal to b, false otherwise
*/
function equals(Percentage a, Percentage b) pure returns (bool) {
return Percentage.unwrap(a) == Percentage.unwrap(b);
}
/**
* @dev Converts a uint256 value to a Percentage
* @param value The uint256 value to convert
* @return The input value as a Percentage
*/
function toPercentage(uint256 value) pure returns (Percentage) {
return Percentage.wrap(value * PERCENTAGE_FACTOR);
}
/**
* @dev Converts a Percentage value to a uint256
* @param value The Percentage value to convert
* @return The Percentage value as a uint256
*/
function fromPercentage(Percentage value) pure returns (uint256) {
return Percentage.unwrap(value) / PERCENTAGE_FACTOR;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {PERCENTAGE_100, PERCENTAGE_FACTOR, Percentage, toPercentage} from "./Percentage.sol";
/**
* @title PercentageUtils
* @author Roberto Cano
* @notice Utility library to apply percentage calculations to input amounts
* @dev This library provides functions for adding, subtracting, and applying
* percentages to amounts, as well as utility functions for working with
* percentages.
*/
library PercentageUtils {
/**
* @notice Adds the percentage to the given amount and returns the result
* @param amount The base amount to which the percentage will be added
* @param percentage The percentage to add to the amount
* @return The amount after the percentage is applied
* @dev It performs the following operation: (100.0% + percentage) * amount
*/
function addPercentage(
uint256 amount,
Percentage percentage
) internal pure returns (uint256) {
return applyPercentage(amount, PERCENTAGE_100 + percentage);
}
/**
* @notice Subtracts the percentage from the given amount and returns the result
* @param amount The base amount from which the percentage will be subtracted
* @param percentage The percentage to subtract from the amount
* @return The amount after the percentage is applied
* @dev It performs the following operation: (100.0% - percentage) * amount
*/
function subtractPercentage(
uint256 amount,
Percentage percentage
) internal pure returns (uint256) {
return applyPercentage(amount, PERCENTAGE_100 - percentage);
}
/**
* @notice Applies the given percentage to the given amount and returns the result
* @param amount The amount to apply the percentage to
* @param percentage The percentage to apply to the amount
* @return The amount after the percentage is applied
* @dev This function is used internally by addPercentage and subtractPercentage
*/
function applyPercentage(
uint256 amount,
Percentage percentage
) internal pure returns (uint256) {
return
(amount * Percentage.unwrap(percentage)) /
Percentage.unwrap(PERCENTAGE_100);
}
/**
* @notice Checks if the given percentage is in range, this is, if it is between 0 and 100
* @param percentage The percentage to check
* @return True if the percentage is in range, false otherwise
* @dev This function is useful for validating input percentages
*/
function isPercentageInRange(
Percentage percentage
) internal pure returns (bool) {
return percentage <= PERCENTAGE_100;
}
/**
* @notice Converts the given fraction into a percentage with the right number of decimals
* @param numerator The numerator of the fraction
* @param denominator The denominator of the fraction
* @return The percentage with `PERCENTAGE_DECIMALS` decimals
* @dev This function is useful for converting ratios to percentages
* For example, fromFraction(1, 2) returns 50%
*/
function fromFraction(
uint256 numerator,
uint256 denominator
) internal pure returns (Percentage) {
return
Percentage.wrap(
(numerator * PERCENTAGE_FACTOR * 100) / denominator
);
}
/**
* @notice Converts the given integer into a percentage
* @param percentage The percentage in human-readable format, i.e., 50 for 50%
* @return The percentage with `PERCENTAGE_DECIMALS` decimals
* @dev This function is useful for converting human-readable percentages to the internal representation
*/
function fromIntegerPercentage(
uint256 percentage
) internal pure returns (Percentage) {
return toPercentage(percentage);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title StakingRewardsManager
* @notice Contract for managing staking rewards with multiple reward tokens in the Summer protocol
* @dev Implements IStakingRewards interface and inherits from ReentrancyGuardTransient and ProtocolAccessManaged
* @dev Inspired by Synthetix's StakingRewards contract:
* https://github.com/Synthetixio/synthetix/blob/v2.101.3/contracts/StakingRewards.sol
*/
import {IStakingRewardsManagerBase} from "../interfaces/IStakingRewardsManagerBase.sol";
import {ProtocolAccessManaged} from "@summerfi/access-contracts/contracts/ProtocolAccessManaged.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/interfaces/IERC20Metadata.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Constants} from "@summerfi/constants/Constants.sol";
import {ERC20Wrapper} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Wrapper.sol";
/**
* @title StakingRewards
* @notice Contract for managing staking rewards with multiple reward tokens in the Summer protocol
* @dev Implements IStakingRewards interface and inherits from ReentrancyGuardTransient and ProtocolAccessManaged
*/
abstract contract StakingRewardsManagerBase is
IStakingRewardsManagerBase,
ReentrancyGuardTransient,
ProtocolAccessManaged
{
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
struct RewardData {
uint256 periodFinish;
uint256 rewardRate;
uint256 rewardsDuration;
uint256 lastUpdateTime;
uint256 rewardPerTokenStored;
}
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/* @notice List of all reward tokens supported by this contract */
EnumerableSet.AddressSet internal _rewardTokensList;
/* @notice The token that users stake to earn rewards */
address public immutable stakingToken;
/* @notice Mapping of reward token to its reward distribution data */
mapping(address rewardToken => RewardData data) public rewardData;
/* @notice Tracks the last reward per token paid to each user for each reward token */
mapping(address rewardToken => mapping(address account => uint256 rewardPerTokenPaid))
public userRewardPerTokenPaid;
/* @notice Tracks the unclaimed rewards for each user for each reward token */
mapping(address rewardToken => mapping(address account => uint256 rewardAmount))
public rewards;
/* @notice Total amount of tokens staked in the contract */
uint256 public totalSupply;
mapping(address account => uint256 balance) internal _balances;
uint256 private constant MAX_REWARD_DURATION = 360 days; // 1 year
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
modifier updateReward(address account) virtual {
_updateReward(account);
_;
}
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the StakingRewards contract
* @param accessManager The address of the access manager
*/
constructor(address accessManager) ProtocolAccessManaged(accessManager) {}
/*//////////////////////////////////////////////////////////////
VIEWS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IStakingRewardsManagerBase
function rewardTokens(
uint256 index
) external view override returns (address) {
if (index >= _rewardTokensList.length()) revert IndexOutOfBounds();
address rewardTokenAddress = _rewardTokensList.at(index);
return rewardTokenAddress;
}
/// @inheritdoc IStakingRewardsManagerBase
function rewardTokensLength() external view returns (uint256) {
return _rewardTokensList.length();
}
/// @inheritdoc IStakingRewardsManagerBase
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/// @inheritdoc IStakingRewardsManagerBase
function lastTimeRewardApplicable(
address rewardToken
) public view returns (uint256) {
return
block.timestamp < rewardData[rewardToken].periodFinish
? block.timestamp
: rewardData[rewardToken].periodFinish;
}
/// @inheritdoc IStakingRewardsManagerBase
function rewardPerToken(address rewardToken) public view returns (uint256) {
if (totalSupply == 0) {
return rewardData[rewardToken].rewardPerTokenStored;
}
return
rewardData[rewardToken].rewardPerTokenStored +
((lastTimeRewardApplicable(rewardToken) -
rewardData[rewardToken].lastUpdateTime) *
rewardData[rewardToken].rewardRate) /
totalSupply;
}
/// @inheritdoc IStakingRewardsManagerBase
function earned(
address account,
address rewardToken
) public view virtual returns (uint256) {
return _earned(account, rewardToken);
}
/// @inheritdoc IStakingRewardsManagerBase
function getRewardForDuration(
address rewardToken
) external view returns (uint256) {
RewardData storage data = rewardData[rewardToken];
if (block.timestamp >= data.periodFinish) {
return (data.rewardRate * data.rewardsDuration) / Constants.WAD;
}
// For active periods, calculate remaining rewards plus any new rewards
uint256 remaining = data.periodFinish - block.timestamp;
return (data.rewardRate * remaining) / Constants.WAD;
}
/// @inheritdoc IStakingRewardsManagerBase
function isRewardToken(address rewardToken) external view returns (bool) {
return _isRewardToken(rewardToken);
}
/*//////////////////////////////////////////////////////////////
MUTATIVE FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IStakingRewardsManagerBase
function stake(uint256 amount) external virtual updateReward(_msgSender()) {
_stake(_msgSender(), _msgSender(), amount);
}
/// @inheritdoc IStakingRewardsManagerBase
function unstake(
uint256 amount
) external virtual updateReward(_msgSender()) {
_unstake(_msgSender(), _msgSender(), amount);
}
/// @inheritdoc IStakingRewardsManagerBase
function getReward() public virtual nonReentrant {
uint256 rewardTokenCount = _rewardTokensList.length();
for (uint256 i = 0; i < rewardTokenCount; i++) {
address rewardTokenAddress = _rewardTokensList.at(i);
_getReward(_msgSender(), rewardTokenAddress);
}
}
/// @inheritdoc IStakingRewardsManagerBase
function getReward(address rewardToken) public virtual nonReentrant {
if (!_isRewardToken(rewardToken)) revert RewardTokenDoesNotExist();
_getReward(_msgSender(), rewardToken);
}
/// @inheritdoc IStakingRewardsManagerBase
function exit() external virtual {
getReward();
_unstake(_msgSender(), _msgSender(), _balances[_msgSender()]);
}
/// @notice Claims rewards for a specific account
/// @param account The address to claim rewards for
function getRewardFor(address account) public virtual nonReentrant {
uint256 rewardTokenCount = _rewardTokensList.length();
for (uint256 i = 0; i < rewardTokenCount; i++) {
address rewardTokenAddress = _rewardTokensList.at(i);
_getReward(account, rewardTokenAddress);
}
}
/// @notice Claims rewards for a specific account and specific reward token
/// @param account The address to claim rewards for
/// @param rewardToken The address of the reward token to claim
function getRewardFor(
address account,
address rewardToken
) public virtual nonReentrant {
if (!_isRewardToken(rewardToken)) revert RewardTokenDoesNotExist();
_getReward(account, rewardToken);
}
/*//////////////////////////////////////////////////////////////
RESTRICTED FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IStakingRewardsManagerBase
function notifyRewardAmount(
address rewardToken,
uint256 reward,
uint256 newRewardsDuration
) external virtual onlyGovernor updateReward(address(0)) {
_notifyRewardAmount(rewardToken, reward, newRewardsDuration);
}
/// @inheritdoc IStakingRewardsManagerBase
function setRewardsDuration(
address rewardToken,
uint256 _rewardsDuration
) external onlyGovernor {
if (!_isRewardToken(rewardToken)) {
revert RewardTokenDoesNotExist();
}
if (_rewardsDuration == 0) {
revert RewardsDurationCannotBeZero();
}
if (_rewardsDuration > MAX_REWARD_DURATION) {
revert RewardsDurationTooLong();
}
RewardData storage data = rewardData[rewardToken];
if (block.timestamp <= data.periodFinish) {
revert RewardPeriodNotComplete();
}
data.rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(address(rewardToken), _rewardsDuration);
}
/// @notice Removes a reward token from the list of reward tokens
/// @param rewardToken The address of the reward token to remove
function removeRewardToken(address rewardToken) external onlyGovernor {
if (!_isRewardToken(rewardToken)) {
revert RewardTokenDoesNotExist();
}
if (block.timestamp <= rewardData[rewardToken].periodFinish) {
revert RewardPeriodNotComplete();
}
// Check if all tokens have been claimed, allowing a small dust balance
uint256 remainingBalance = IERC20(rewardToken).balanceOf(address(this));
uint256 dustThreshold;
try IERC20Metadata(address(rewardToken)).decimals() returns (
uint8 decimals
) {
// For tokens with 4 or fewer decimals, use a minimum threshold of 1
// For tokens with more decimals, use 0.01% of 1 token
if (decimals <= 4) {
dustThreshold = 1;
} else {
dustThreshold = 10 ** (decimals - 4); // 0.01% of 1 token
}
} catch {
dustThreshold = 1e14; // Default threshold for tokens without decimals
}
if (remainingBalance > dustThreshold) {
revert RewardTokenStillHasBalance(remainingBalance);
}
// Remove the token from the rewardTokens map
bool success = _rewardTokensList.remove(address(rewardToken));
if (!success) revert RewardTokenDoesNotExist();
emit RewardTokenRemoved(address(rewardToken));
}
/// @inheritdoc IStakingRewardsManagerBase
function rescueToken(
address _token,
address _to
) public virtual onlyGovernor {
// Sweep entire token balance to the target; used for emergency recovery only
IERC20(_token).safeTransfer(
_to,
IERC20(_token).balanceOf(address(this))
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
function _isRewardToken(address rewardToken) internal view returns (bool) {
return _rewardTokensList.contains(rewardToken);
}
function _stake(
address staker,
address receiver,
uint256 amount
) internal virtual {
if (receiver == address(0)) revert CannotStakeToZeroAddress();
if (amount == 0) revert CannotStakeZero();
if (address(stakingToken) == address(0)) {
revert StakingTokenNotInitialized();
}
totalSupply += amount;
_balances[receiver] += amount;
IERC20(stakingToken).safeTransferFrom(staker, address(this), amount);
emit Staked(staker, receiver, amount);
}
function _unstake(
address staker,
address receiver,
uint256 amount
) internal virtual {
if (amount == 0) revert CannotUnstakeZero();
totalSupply -= amount;
_balances[staker] -= amount;
IERC20(stakingToken).safeTransfer(receiver, amount);
emit Unstaked(staker, receiver, amount);
}
/*
* @notice Internal function to calculate earned rewards for an account
* @param account The address to calculate earnings for
* @param rewardToken The reward token to calculate earnings for
* @return The amount of reward tokens earned
*/
function _earned(
address account,
address rewardToken
) internal view returns (uint256) {
return
(_balances[account] *
(rewardPerToken(rewardToken) -
userRewardPerTokenPaid[rewardToken][account])) /
Constants.WAD +
rewards[rewardToken][account];
}
function _updateReward(address account) internal {
uint256 rewardTokenCount = _rewardTokensList.length();
for (uint256 i = 0; i < rewardTokenCount; i++) {
address rewardTokenAddress = _rewardTokensList.at(i);
RewardData storage rewardTokenData = rewardData[rewardTokenAddress];
rewardTokenData.rewardPerTokenStored = rewardPerToken(
rewardTokenAddress
);
rewardTokenData.lastUpdateTime = lastTimeRewardApplicable(
rewardTokenAddress
);
if (account != address(0)) {
rewards[rewardTokenAddress][account] = earned(
account,
rewardTokenAddress
);
userRewardPerTokenPaid[rewardTokenAddress][
account
] = rewardTokenData.rewardPerTokenStored;
}
}
}
/**
* @notice Internal function to claim rewards for an account for a specific token
* @param account The address to claim rewards for
* @param rewardTokenAddress The address of the reward token to claim
* @dev rewards go straight to the user's wallet
*/
function _getReward(
address account,
address rewardTokenAddress
) internal virtual updateReward(account) {
uint256 reward = rewards[rewardTokenAddress][account];
if (reward > 0) {
rewards[rewardTokenAddress][account] = 0;
IERC20(rewardTokenAddress).safeTransfer(account, reward);
emit RewardPaid(account, rewardTokenAddress, reward);
}
}
/**
* @dev Internal implementation of notifyRewardAmount
* @param rewardToken The token to distribute as rewards
* @param reward The amount of reward tokens to distribute
* @param newRewardsDuration The duration for new reward tokens (only used for first time)
*/
function _notifyRewardAmount(
address rewardToken,
uint256 reward,
uint256 newRewardsDuration
) internal {
RewardData storage rewardTokenData = rewardData[rewardToken];
if (newRewardsDuration == 0) {
revert RewardsDurationCannotBeZero();
}
if (newRewardsDuration > MAX_REWARD_DURATION) {
revert RewardsDurationTooLong();
}
// For existing reward tokens, check if current period is complete
if (_isRewardToken(rewardToken)) {
if (newRewardsDuration != rewardTokenData.rewardsDuration) {
revert CannotChangeRewardsDuration();
}
} else {
// First time setup for new reward token
bool success = _rewardTokensList.add(rewardToken);
if (!success) revert RewardTokenAlreadyExists();
rewardTokenData.rewardsDuration = newRewardsDuration;
emit RewardTokenAdded(rewardToken, rewardTokenData.rewardsDuration);
}
// Transfer exact amount needed for new rewards
IERC20(rewardToken).safeTransferFrom(msg.sender, address(this), reward);
// Calculate new reward rate
rewardTokenData.rewardRate =
(reward * Constants.WAD) /
rewardTokenData.rewardsDuration;
rewardTokenData.lastUpdateTime = block.timestamp;
rewardTokenData.periodFinish =
block.timestamp +
rewardTokenData.rewardsDuration;
emit RewardAdded(address(rewardToken), reward);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IStakingRewardsManagerBaseErrors} from "./IStakingRewardsManagerBaseErrors.sol";
/* @title IStakingRewardsManagerBase
* @notice Interface for the Staking Rewards Manager contract
* @dev Manages staking and distribution of multiple reward tokens
*/
interface IStakingRewardsManagerBase is IStakingRewardsManagerBaseErrors {
// Views
/* @notice Get the total amount of staked tokens
* @return The total supply of staked tokens
*/
function totalSupply() external view returns (uint256);
/* @notice Get the staked balance of a specific account
* @param account The address of the account to check
* @return The staked balance of the account
*/
function balanceOf(address account) external view returns (uint256);
/* @notice Get the last time the reward was applicable for a specific reward token
* @param rewardToken The address of the reward token
* @return The timestamp of the last applicable reward time
*/
function lastTimeRewardApplicable(
address rewardToken
) external view returns (uint256);
/* @notice Get the reward per token for a specific reward token
* @param rewardToken The address of the reward token
* @return The reward amount per staked token (WAD-scaled)
* @dev Returns a WAD-scaled value (1e18) to maintain precision in calculations
* @dev This value represents: (rewardRate * timeElapsed * WAD) / totalSupply
*/
function rewardPerToken(
address rewardToken
) external view returns (uint256);
/* @notice Calculate the earned reward for an account and a specific reward token
* @param account The address of the account
* @param rewardToken The address of the reward token
* @return The amount of reward tokens earned (not WAD-scaled)
* @dev Calculated as: (balance * (rewardPerToken - userRewardPerTokenPaid)) / WAD + rewards
*/
function earned(
address account,
address rewardToken
) external view returns (uint256);
/* @notice Get the reward for the entire duration for a specific reward token
* @param rewardToken The address of the reward token
* @return The total reward amount for the duration (not WAD-scaled)
* @dev Calculated as: (rewardRate * rewardsDuration) / WAD
*/
function getRewardForDuration(
address rewardToken
) external view returns (uint256);
/* @notice Get the address of the staking token
* @return The address of the staking token
*/
function stakingToken() external view returns (address);
/* @notice Get the reward token at a specific index
* @param index The index of the reward token
* @return The address of the reward token
* @dev Reverts with IndexOutOfBounds if index >= rewardTokensLength()
*/
function rewardTokens(uint256 index) external view returns (address);
/* @notice Get the total number of reward tokens
* @return The length of the reward tokens list
*/
function rewardTokensLength() external view returns (uint256);
/* @notice Check if a token is in the list of reward tokens
* @param rewardToken The address to check
* @return bool True if the token is a reward token, false otherwise
*/
function isRewardToken(address rewardToken) external view returns (bool);
// Mutative functions
/* @notice Stake tokens for an account
* @param amount The amount of tokens to stake
*/
function stake(uint256 amount) external;
/* @notice Stake tokens for an account on behalf of another account
* @param receiver The address of the account to stake for
* @param amount The amount of tokens to stake
*/
function stakeOnBehalfOf(address receiver, uint256 amount) external;
/* @notice Unstake staked tokens on behalf of another account
* @param owner The address of the account to unstake from
* @param amount The amount of tokens to unstake
* @param claimRewards Whether to claim rewards before unstaking
*/
function unstakeAndWithdrawOnBehalfOf(
address owner,
uint256 amount,
bool claimRewards
) external;
/* @notice Unstake staked tokens
* @param amount The amount of tokens to unstake
*/
function unstake(uint256 amount) external;
/* @notice Claim accumulated rewards for all reward tokens */
function getReward() external;
/* @notice Claim accumulated rewards for a specific reward token
* @param rewardToken The address of the reward token to claim
*/
function getReward(address rewardToken) external;
/* @notice Withdraw all staked tokens and claim rewards */
function exit() external;
// Admin functions
/* @notice Notify the contract about new reward amount
* @param rewardToken The address of the reward token
* @param reward The amount of new reward (not WAD-scaled)
* @param newRewardsDuration The duration for rewards distribution (only used when adding a new reward token)
* @dev Internally sets rewardRate as (reward * WAD) / duration to maintain precision
*/
function notifyRewardAmount(
address rewardToken,
uint256 reward,
uint256 newRewardsDuration
) external;
/* @notice Set the duration for rewards distribution
* @param rewardToken The address of the reward token
* @param _rewardsDuration The new duration for rewards
*/
function setRewardsDuration(
address rewardToken,
uint256 _rewardsDuration
) external;
/* @notice Removes a reward token from the list of reward tokens
* @dev Can only be called by governor
* @dev Can only be called after reward period is complete
* @dev Can only be called if remaining balance is below dust threshold
* @dev Can be multi-called by governor preceded by rescueToken for each reward token
* @param rewardToken The address of the reward token to remove
*/
function removeRewardToken(address rewardToken) external;
/* @notice Rescues a token from the contract
* @dev Can only be called by governor
* @dev Can be multi-called by governor followed by removeRewardToken for each token
* @dev To clean the dust balance, call rescueToken for each token
* @param _token The address of the token to rescue
* @param _to The address to send the rescued tokens to
*/
function rescueToken(address _token, address _to) external;
// Events
/* @notice Emitted when a new reward is added
* @param rewardToken The address of the reward token
* @param reward The amount of reward added
*/
event RewardAdded(address indexed rewardToken, uint256 reward);
/* @notice Emitted when tokens are staked
* @param staker The address that provided the tokens for staking
* @param receiver The address whose staking balance was updated
* @param amount The amount of tokens added to the staking position
*/
event Staked(
address indexed staker,
address indexed receiver,
uint256 amount
);
/* @notice Emitted when tokens are unstaked
* @param staker The address whose tokens were unstaked
* @param receiver The address receiving the unstaked tokens
* @param amount The amount of tokens unstaked
*/
event Unstaked(
address indexed staker,
address indexed receiver,
uint256 amount
);
/* @notice Emitted when tokens are withdrawn
* @param user The address of the user that withdrew
* @param amount The amount of tokens withdrawn
*/
event Withdrawn(address indexed user, uint256 amount);
/* @notice Emitted when rewards are paid out
* @param user The address of the user receiving the reward
* @param rewardToken The address of the reward token
* @param reward The amount of reward paid
*/
event RewardPaid(
address indexed user,
address indexed rewardToken,
uint256 reward
);
/* @notice Emitted when the rewards duration is updated
* @param rewardToken The address of the reward token
* @param newDuration The new duration for rewards
*/
event RewardsDurationUpdated(
address indexed rewardToken,
uint256 newDuration
);
/* @notice Emitted when a new reward token is added
* @param rewardToken The address of the new reward token
* @param rewardsDuration The duration for the new reward token
*/
event RewardTokenAdded(address rewardToken, uint256 rewardsDuration);
/* @notice Emitted when a reward token is removed
* @param rewardToken The address of the reward token
*/
event RewardTokenRemoved(address rewardToken);
/* @notice Claims rewards for a specific account
* @param account The address to claim rewards for
*/
function getRewardFor(address account) external;
/* @notice Claims rewards for a specific account and specific reward token
* @param account The address to claim rewards for
* @param rewardToken The address of the reward token to claim
*/
function getRewardFor(address account, address rewardToken) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/* @title IStakingRewardsManagerBaseErrors
* @notice Interface defining custom errors for the Staking Rewards Manager
*/
interface IStakingRewardsManagerBaseErrors {
/* @notice Thrown when attempting to stake zero tokens */
error CannotStakeZero();
/* @notice Thrown when attempting to withdraw zero tokens */
error CannotWithdrawZero();
/* @notice Thrown when the provided reward amount is too high */
error ProvidedRewardTooHigh();
/* @notice Thrown when trying to set rewards before the current period is complete */
error RewardPeriodNotComplete();
/* @notice Thrown when there are no reward tokens set */
error NoRewardTokens();
/* @notice Thrown when trying to add a reward token that already exists */
error RewardTokenAlreadyExists();
/* @notice Thrown when setting an invalid rewards duration */
error InvalidRewardsDuration();
/* @notice Thrown when trying to interact with a reward token that hasn't been initialized */
error RewardTokenNotInitialized();
/* @notice Thrown when the reward amount is invalid for the given duration
* @param rewardToken The address of the reward token
* @param rewardsDuration The duration for which the reward is invalid
*/
error InvalidRewardAmount(address rewardToken, uint256 rewardsDuration);
/* @notice Thrown when trying to interact with the staking token before it's initialized */
error StakingTokenNotInitialized();
/* @notice Thrown when trying to remove a reward token that doesn't exist */
error RewardTokenDoesNotExist();
/* @notice Thrown when trying to change the rewards duration of a reward token */
error CannotChangeRewardsDuration();
/* @notice Thrown when a reward token still has a balance */
error RewardTokenStillHasBalance(uint256 balance);
/* @notice Thrown when the index is out of bounds */
error IndexOutOfBounds();
/* @notice Thrown when the rewards duration is zero */
error RewardsDurationCannotBeZero();
/* @notice Thrown when attempting to unstake zero tokens */
error CannotUnstakeZero();
/* @notice Thrown when the rewards duration is too long */
error RewardsDurationTooLong();
/**
* @notice Thrown when the receiver is the zero address
*/
error CannotStakeToZeroAddress();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArk} from "../interfaces/IArk.sol";
import {IFleetCommander} from "../interfaces/IFleetCommander.sol";
import {ArkConfig, ArkParams} from "../types/ArkTypes.sol";
import {ArkConfigProvider} from "./ArkConfigProvider.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IDistributor} from "../interfaces/merkl/IDistributor.sol";
import {Constants} from "@summerfi/constants/Constants.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
/**
* @title Ark
* @author SummerFi
* @notice This contract implements the core functionality for the Ark system,
* handling asset boarding, disembarking, and harvesting operations.
* @dev This is an abstract contract that should be inherited by specific Ark implementations.
* Inheriting contracts must implement the abstract functions defined here.
*/
abstract contract Ark is IArk, ArkConfigProvider, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
IDistributor constant MERKL_DISTRIBUTOR =
IDistributor(0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae);
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(ArkParams memory _params) ArkConfigProvider(_params) {}
/*//////////////////////////////////////////////////////////////
MODIFIERS
//////////////////////////////////////////////////////////////*/
/**
* @notice Modifier to validate board data.
* @dev This modifier calls `_validateCommonData` and `_validateBoardData` to ensure the data is valid.
* In the base Ark contract, we use generic bytes for the data. It is the responsibility of the Ark
* implementing contract to override the `_validateBoardData` function to provide specific validation logic.
* @param data The data to be validated.
*/
modifier validateBoardData(bytes calldata data) {
_validateCommonData(data);
_validateBoardData(data);
_;
}
/**
* @notice Modifier to validate disembark data.
* @dev This modifier calls `_validateCommonData` and `_validateDisembarkData` to ensure the data is valid.
* In the base Ark contract, we use generic bytes for the data. It is the responsibility of the Ark
* implementing contract to override the `_validateDisembarkData` function to provide specific validation logic.
* @param data The data to be validated.
*/
modifier validateDisembarkData(bytes calldata data) {
_validateCommonData(data);
_validateDisembarkData(data);
_;
}
/*//////////////////////////////////////////////////////////////
EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IArk
function totalAssets() external view virtual returns (uint256) {}
/// @inheritdoc IArk
function withdrawableTotalAssets() external view returns (uint256) {
if (config.requiresKeeperData) {
return 0;
}
return _withdrawableTotalAssets();
}
/// @inheritdoc IArk
function harvest(
bytes calldata additionalData
)
external
onlyRaft
nonReentrant
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts)
{
(rewardTokens, rewardAmounts) = _harvest(additionalData);
emit ArkHarvested(rewardTokens, rewardAmounts);
}
/// @inheritdoc IArk
function sweep(
address[] memory tokens
)
external
onlyRaft
nonReentrant
returns (address[] memory sweptTokens, uint256[] memory sweptAmounts)
{
sweptTokens = new address[](tokens.length);
sweptAmounts = new uint256[](tokens.length);
IERC20 asset = config.asset;
address bufferArk = address(
IFleetCommander(config.commander).bufferArk()
);
if (asset.balanceOf(address(this)) > 0 && address(this) != bufferArk) {
asset.forceApprove(bufferArk, asset.balanceOf(address(this)));
IArk(bufferArk).board(asset.balanceOf(address(this)), bytes(""));
}
for (uint256 i = 0; i < tokens.length; i++) {
uint256 amount = IERC20(tokens[i]).balanceOf(address(this));
if (amount > 0) {
IERC20(tokens[i]).safeTransfer(
raft(),
IERC20(tokens[i]).balanceOf(address(this))
);
sweptTokens[i] = tokens[i];
sweptAmounts[i] = amount;
}
}
emit ArkSwept(sweptTokens, sweptAmounts);
}
function whitelistMerklOperator(address operator) external onlyKeeper {
MERKL_DISTRIBUTOR.toggleOperator(address(this), operator);
}
/// @inheritdoc IArk
function board(
uint256 amount,
bytes calldata boardData
)
external
nonReentrant
onlyAuthorizedToBoard(this.commander())
validateBoardData(boardData)
{
address msgSender = msg.sender;
IERC20 asset = config.asset;
asset.safeTransferFrom(msgSender, address(this), amount);
_board(amount, boardData);
emit Boarded(msgSender, address(asset), amount);
}
/// @inheritdoc IArk
function disembark(
uint256 amount,
bytes calldata disembarkData
) external onlyCommander nonReentrant validateDisembarkData(disembarkData) {
address msgSender = msg.sender;
IERC20 asset = config.asset;
_disembark(amount, disembarkData);
asset.safeTransfer(msgSender, amount);
emit Disembarked(msgSender, address(asset), amount);
}
/// @inheritdoc IArk
function move(
uint256 amount,
address receiverArk,
bytes calldata boardData,
bytes calldata disembarkData
) external onlyCommander validateDisembarkData(disembarkData) {
_disembark(amount, disembarkData);
IERC20 asset = config.asset;
asset.forceApprove(receiverArk, amount);
IArk(receiverArk).board(amount, boardData);
emit Moved(address(this), receiverArk, address(asset), amount);
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Internal function to get the total assets that are withdrawable
* @dev This function should be implemented by derived contracts to define specific withdrawability logic
* @dev The Ark is withdrawable if it doesnt require keeper data and _withdrawableTotalAssets returns a non-zero
* value
* @return uint256 The total assets that are withdrawable
*/
function _withdrawableTotalAssets() internal view virtual returns (uint256);
/**
* @notice Internal function to handle the boarding (depositing) of assets
* @dev This function should be implemented by derived contracts to define specific boarding logic
* @param amount The amount of assets to board
* @param data Additional data for boarding, interpreted by the specific Ark implementation
*/
function _board(uint256 amount, bytes calldata data) internal virtual;
/**
* @notice Internal function to handle the disembarking (withdrawing) of assets
* @dev This function should be implemented by derived contracts to define specific disembarking logic
* @param amount The amount of assets to disembark
* @param data Additional data for disembarking, interpreted by the specific Ark implementation
*/
function _disembark(uint256 amount, bytes calldata data) internal virtual;
/**
* @notice Internal function to handle the harvesting of rewards
* @dev This function should be implemented by derived contracts to define specific harvesting logic
* @param additionalData Additional data for harvesting, interpreted by the specific Ark implementation
* @return rewardTokens The addresses of the reward tokens harvested
* @return rewardAmounts The amounts of the reward tokens harvested
*/
function _harvest(
bytes calldata additionalData
)
internal
virtual
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts);
/**
* @notice Internal function to validate boarding data
* @dev This function should be implemented by derived contracts to define specific boarding data validation
* @param data The boarding data to validate
*/
function _validateBoardData(bytes calldata data) internal virtual;
/**
* @notice Internal function to validate disembarking data
* @dev This function should be implemented by derived contracts to define specific disembarking data validation
* @param data The disembarking data to validate
*/
function _validateDisembarkData(bytes calldata data) internal virtual;
/**
* @notice Internal function to validate the presence or absence of additional data based on withdrawal restrictions
* @dev This function checks if the data length is consistent with the Ark's withdrawal restrictions
* @param data The data to validate
*/
function _validateCommonData(bytes calldata data) internal view {
if (data.length > 0 && !config.requiresKeeperData) {
revert CannotUseKeeperDataWhenNotRequired();
}
if (data.length == 0 && config.requiresKeeperData) {
revert KeeperDataRequired();
}
}
/**
* @notice Internal function to get the balance of the Ark's asset
* @dev This function returns the balance of the Ark's token held by this contract
* @return The balance of the Ark's asset
*/
function _balanceOfAsset() internal view virtual returns (uint256) {
return config.asset.balanceOf(address(this));
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArkAccessManaged} from "../interfaces/IArkAccessManaged.sol";
import {IConfigurationManaged} from "@summerfi/config-contracts/interfaces/IConfigurationManaged.sol";
import {IFleetCommander} from "../interfaces/IFleetCommander.sol";
import {ContractSpecificRoles} from "@summerfi/access-contracts/interfaces/IProtocolAccessManager.sol";
import {ProtocolAccessManaged} from "@summerfi/access-contracts/contracts/ProtocolAccessManaged.sol";
/**
* @title ArkAccessManaged
* @author SummerFi
* @notice This contract manages access control for Ark-related operations.
* @dev Inherits from ProtocolAccessManaged and implements IArkAccessManaged.
* @custom:see IArkAccessManaged
*/
contract ArkAccessManaged is IArkAccessManaged, ProtocolAccessManaged {
/**
* @notice Initializes the ArkAccessManaged contract.
* @param accessManager The address of the access manager contract.
*/
constructor(address accessManager) ProtocolAccessManaged(accessManager) {}
/**
* @notice Checks if the caller is authorized to board funds.
* @dev This modifier allows the Commander, RAFT contract, or active Arks to proceed.
* @param commander The address of the FleetCommander contract.
* @custom:internal-logic
* - Checks if the caller is the registered commander
* - If not, checks if the caller is the RAFT contract
* - If not, checks if the caller is an active Ark in the FleetCommander
* @custom:effects
* - Reverts if the caller doesn't have the necessary permissions
* - Allows the function to proceed if the caller is authorized
* @custom:security-considerations
* - Ensures that only authorized entities can board funds
* - Relies on the correct setup of the FleetCommander and RAFT contracts
*/
modifier onlyAuthorizedToBoard(address commander) {
if (commander != _msgSender()) {
address msgSender = _msgSender();
bool isRaft = msgSender ==
IConfigurationManaged(address(this)).raft();
if (!isRaft) {
bool isArk = IFleetCommander(commander).isArkActiveOrBufferArk(
msgSender
);
if (!isArk) {
revert CallerIsNotAuthorizedToBoard(msgSender);
}
}
}
_;
}
/**
* @notice Restricts access to only the RAFT contract.
* @dev Modifier to check that the caller is the RAFT contract
* @custom:internal-logic
* - Retrieves the RAFT address from the ConfigurationManaged contract
* - Compares the caller's address with the RAFT address
* @custom:effects
* - Reverts if the caller is not the RAFT contract
* - Allows the function to proceed if the caller is the RAFT contract
* @custom:security-considerations
* - Ensures that only the RAFT contract can call certain functions
* - Relies on the correct setup of the ConfigurationManaged contract
*/
modifier onlyRaft() {
if (_msgSender() != IConfigurationManaged(address(this)).raft()) {
revert CallerIsNotRaft(_msgSender());
}
_;
}
/**
* @notice Checks if the caller has the Commander role.
* @dev Internal function to check if the caller has the Commander role
* @return bool True if the caller has the Commander role, false otherwise
* @custom:internal-logic
* - Generates the Commander role identifier for this contract
* - Checks if the caller has the generated role in the access manager
* @custom:effects
* - Does not modify any state, view function only
* @custom:security-considerations
* - Relies on the correct setup of the access manager
* - Assumes that the Commander role is properly assigned
*/
function _hasCommanderRole() internal view returns (bool) {
return
_accessManager.hasRole(
generateRole(
ContractSpecificRoles.COMMANDER_ROLE,
address(this)
),
_msgSender()
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ArkConfig, ArkParams} from "../types/ArkTypes.sol";
import {IArkConfigProvider} from "../interfaces/IArkConfigProvider.sol";
import {ArkAccessManaged} from "./ArkAccessManaged.sol";
import {ConfigurationManaged} from "@summerfi/config-contracts/contracts/ConfigurationManaged.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Percentage, PercentageUtils} from "@summerfi/percentage-solidity/contracts/PercentageUtils.sol";
/**
* @title ArkConfigProvider
* @author SummerFi
* @notice This contract manages the configuration for Ark contracts.
* @dev Inherits from IArkConfigProvider, ArkAccessManaged, and ConfigurationManaged.
* @custom:see IArkConfigProvider
*/
abstract contract ArkConfigProvider is
IArkConfigProvider,
ArkAccessManaged,
ConfigurationManaged
{
ArkConfig public config;
/**
* @notice Initializes the ArkConfigProvider contract.
* @param _params The initial parameters for the Ark configuration.
* @dev Validates input parameters and sets up the initial configuration.
*/
constructor(
ArkParams memory _params
)
ArkAccessManaged(_params.accessManager)
ConfigurationManaged(_params.configurationManager)
{
if (_params.asset == address(0)) {
revert CannotDeployArkWithoutToken();
}
if (bytes(_params.name).length == 0) {
revert CannotDeployArkWithEmptyName();
}
if (raft() == address(0)) {
revert CannotDeployArkWithoutRaft();
}
if (
!PercentageUtils.isPercentageInRange(
_params.maxDepositPercentageOfTVL
)
) {
revert MaxDepositPercentageOfTVLTooHigh();
}
config = ArkConfig({
asset: IERC20(_params.asset),
commander: address(0), // Commander is initially set to address(0)
raft: raft(),
depositCap: _params.depositCap,
maxRebalanceOutflow: _params.maxRebalanceOutflow,
maxRebalanceInflow: _params.maxRebalanceInflow,
name: _params.name,
details: _params.details,
requiresKeeperData: _params.requiresKeeperData,
maxDepositPercentageOfTVL: _params.maxDepositPercentageOfTVL
});
// The commander address is initially set to address(0).
// This allows the FleetCommander contract to self-register with the Ark later,
// using the `registerFleetCommander()` function. This approach ensures that:
// 1. The FleetCommander's address is not hardcoded during deployment.
// 2. Only the authorized FleetCommander can register itself.
// 3. The Ark remains flexible for potential commander changes in the future.
// See the `registerFleetCommander()` function for the actual registration process.
}
/// @inheritdoc IArkConfigProvider
function name() external view returns (string memory) {
return config.name;
}
/// @inheritdoc IArkConfigProvider
function details() external view returns (string memory) {
return config.details;
}
/// @inheritdoc IArkConfigProvider
function depositCap() external view returns (uint256) {
return config.depositCap;
}
/// @inheritdoc IArkConfigProvider
function asset() external view returns (IERC20) {
return config.asset;
}
function maxDepositPercentageOfTVL() external view returns (Percentage) {
return config.maxDepositPercentageOfTVL;
}
/// @inheritdoc IArkConfigProvider
function commander() public view returns (address) {
return config.commander;
}
/// @inheritdoc IArkConfigProvider
function maxRebalanceOutflow() external view returns (uint256) {
return config.maxRebalanceOutflow;
}
/// @inheritdoc IArkConfigProvider
function maxRebalanceInflow() external view returns (uint256) {
return config.maxRebalanceInflow;
}
/// @inheritdoc IArkConfigProvider
function requiresKeeperData() external view returns (bool) {
return config.requiresKeeperData;
}
/// @inheritdoc IArkConfigProvider
function getConfig() external view returns (ArkConfig memory) {
return config;
}
/// @inheritdoc IArkConfigProvider
function setDepositCap(uint256 newDepositCap) external onlyCommander {
config.depositCap = newDepositCap;
emit DepositCapUpdated(newDepositCap);
}
/// @inheritdoc IArkConfigProvider
function setMaxDepositPercentageOfTVL(
Percentage newMaxDepositPercentageOfTVL
) external onlyCommander {
if (
!PercentageUtils.isPercentageInRange(newMaxDepositPercentageOfTVL)
) {
revert MaxDepositPercentageOfTVLTooHigh();
}
config.maxDepositPercentageOfTVL = newMaxDepositPercentageOfTVL;
emit MaxDepositPercentageOfTVLUpdated(newMaxDepositPercentageOfTVL);
}
/// @inheritdoc IArkConfigProvider
function setMaxRebalanceOutflow(
uint256 newMaxRebalanceOutflow
) external onlyCommander {
config.maxRebalanceOutflow = newMaxRebalanceOutflow;
emit MaxRebalanceOutflowUpdated(newMaxRebalanceOutflow);
}
/// @inheritdoc IArkConfigProvider
function setMaxRebalanceInflow(
uint256 newMaxRebalanceInflow
) external onlyCommander {
config.maxRebalanceInflow = newMaxRebalanceInflow;
emit MaxRebalanceInflowUpdated(newMaxRebalanceInflow);
}
function registerFleetCommander() external {
if (!_hasCommanderRole()) {
revert CallerIsNotCommander(msg.sender);
}
if (config.commander != address(0)) {
revert FleetCommanderAlreadyRegistered();
}
config.commander = msg.sender;
emit FleetCommanderRegistered(msg.sender);
}
function unregisterFleetCommander() external {
if (_msgSender() != config.commander) {
revert FleetCommanderNotRegistered();
}
config.commander = address(0);
emit FleetCommanderUnregistered(msg.sender);
}
modifier onlyCommander() {
if (_msgSender() != config.commander) {
revert CallerIsNotCommander(_msgSender());
}
_;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import "../Ark.sol";
/**
* @title BufferArk
* @notice Specialized Ark contract for Fleet Buffer operations.
* @dev This contract holds a certain percentage of total assets in a buffer,
* which are not deployed and not subject to yield-generating strategies.
* The buffer ensures quick disembarkation of assets when needed.
*
* Key features:
* - Maintains a minimum buffer balance as per FleetCommander configuration
* - Does not deploy assets to any yield-generating strategies
* - Provides quick access to funds for disembarkation
* (see {IFleetCommanderConfigProvider-config-minimumBufferBalance})
*/
contract BufferArk is Ark {
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the BufferArk
* @param _params The ArkParams struct containing initialization parameters
* @param commanderAddress The address of the Fleet Commander
*/
constructor(
ArkParams memory _params,
address commanderAddress
) Ark(_params) {
config.commander = commanderAddress;
}
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @inheritdoc IArk
* @dev For BufferArk, total assets are simply the token balance of this contract,
* as no assets are deployed to external strategies.
*/
function totalAssets() public view override returns (uint256) {
return config.asset.balanceOf(address(this));
}
/**
* @notice Internal function to get the total assets that are withdrawable
* @dev For Buffer Ark, the total assets are always withdrawable
*/
function _withdrawableTotalAssets()
internal
view
override
returns (uint256)
{
return totalAssets();
}
/**
* @notice No-op for board function
* @dev This function is intentionally left empty because the BufferArk doesn't need to perform any
* additional actions when boarding tokens. The actual token transfer is handled by the Ark.board() function,
* and the BufferArk simply holds these tokens without deploying them to any strategy.
* @param amount The amount of tokens being boarded (unused in this implementation)
* @param data Additional data for boarding (unused in this implementation)
*/
function _board(uint256 amount, bytes calldata data) internal override {}
/**
* @notice No-op for disembark function
* @dev This function is intentionally left empty because the BufferArk doesn't need to perform any
* additional actions when disembarking tokens. The actual token transfer is handled by the Ark.disembark()
* function,
* and the BufferArk simply releases these tokens without any complex withdrawal process.
* @param amount The amount of tokens being disembarked (unused in this implementation)
* @param data Additional data for disembarking (unused in this implementation)
*/
function _disembark(
uint256 amount,
bytes calldata data
) internal override {}
/**
* @notice No-op for harvest function
* @dev This function is intentionally left empty and returns empty arrays because the BufferArk
* does not generate any rewards. It's a simple holding contract for tokens, not an investment strategy.
* @param data Additional data for harvesting (unused in this implementation)
* @return rewardTokens An empty array of reward token addresses
* @return rewardAmounts An empty array of reward amounts
*/
function _harvest(
bytes calldata data
)
internal
override
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts)
{}
/**
* @notice No-op for validateBoardData function
* @dev This function is intentionally left empty because the BufferArk doesn't require any
* specific validation for boarding data. It accepts any data without validation.
* @param data The boarding data to validate (unused in this implementation)
*/
function _validateBoardData(bytes calldata data) internal override {}
/**
* @notice No-op for validateDisembarkData function
* @dev This function is intentionally left empty because the BufferArk doesn't require any
* specific validation for disembarking data. It accepts any data without validation.
* @param data The disembarking data to validate (unused in this implementation)
*/
function _validateDisembarkData(bytes calldata data) internal override {}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {StorageSlot} from "@summerfi/dependencies/openzeppelin-next/StorageSlot.sol";
import {IArk} from "../interfaces/IArk.sol";
import {ArkData} from "../types/FleetCommanderTypes.sol";
import {StorageSlots} from "./libraries/StorageSlots.sol";
/**
* @title FleetCommanderCache - Caching System
* @dev This contract implements a caching mechanism
* for efficient asset tracking and operations.
*
* Caching System:
* 1. Purpose: The caching system is designed to optimize gas costs and improve performance
* for operations that require frequent access to total assets and ark data.
*
* 2. Key Components:
* - FleetCommanderCache: A contract that this FleetCommander inherits from, providing
* caching functionality.
* - Cache Modifiers: 'useDepositCache' and 'useWithdrawCache' are used to manage the
* caching lifecycle for deposit and withdrawal operations.
*
* 3. Caching Mechanism:
* - Before Operation: The cache is populated with current ark data.
* - During Operation: The contract uses cached data instead of making repeated calls to arks.
* - After Operation: The cache is flushed to ensure data freshness for subsequent operations.
*
* 4. Benefits:
* - Gas Optimization: Reduces the number of external calls to arks, saving gas.
* - Consistency: Ensures that a single operation uses consistent data throughout its execution.
*
* 5. Cache Usage:
* - Deposit Operations: Uses 'useDepositCache' modifier to cache all ark data.
* - Withdrawal Operations: Uses 'useWithdrawCache' modifier to cache data for withdrawable arks.
* - Rebalance Operations: Does not use cache as it directly interacts with arks.
*
* 6. Cache Management:
* - Cache population: Performed by '_getArksData' and '_getWithdrawableArksData' functions.
* - Cache flushing: Done by '_flushCache' function after each operation.
*
* This caching system is crucial for maintaining efficient operations in the FleetCommander,
* especially when dealing with multiple arks and frequent asset calculations.
*/
contract FleetCommanderCache {
using StorageSlot for *;
/**
* @dev Checks if the FleetCommander is currently performing a trnsaction that includes a tip
* @return bool True if collecting tips, false otherwise
*/
function _isCollectingTip() internal view returns (bool) {
return StorageSlots.TIP_TAKEN_STORAGE.asBoolean().tload();
}
/**
* @dev Sets the isCollectingTip flag
* @param value The value to set the flag to
*/
function _setIsCollectingTip(bool value) internal {
StorageSlots.TIP_TAKEN_STORAGE.asBoolean().tstore(value);
}
/**
* @dev Calculates the total assets across all arks
* @param bufferArk The buffer ark instance
* @return total The sum of total assets across all arks
* @custom:internal-logic
* - Checks if total assets are cached
* - If cached, returns the cached value
* - If not cached, calculates the sum of total assets across all arks
* @custom:effects
* - No state changes
* @custom:security-considerations
* - Relies on accurate reporting of total assets by individual arks
* - Caching mechanism must be properly managed to ensure data freshness
* - Assumes no changes in total assets throughout the execution of function that use this cache
*/
function _totalAssets(
IArk bufferArk
) internal view returns (uint256 total) {
bool isTotalAssetsCached = StorageSlots
.IS_TOTAL_ASSETS_CACHED_STORAGE
.asBoolean()
.tload();
if (isTotalAssetsCached) {
return StorageSlots.TOTAL_ASSETS_STORAGE.asUint256().tload();
}
return
_sumTotalAssets(_getAllArks(_getActiveArksAddresses(), bufferArk));
}
/**
* @dev Calculates the total assets of withdrawable arks
* @param bufferArk The buffer ark instance
* @return withdrawableTotalAssets The sum of total assets across withdrawable arks
* - arks that don't require additional data to be boarded or disembarked from.
* @custom:internal-logic
* - Checks if withdrawable total assets are cached
* - If cached, returns the cached value
* - If not cached, calculates the sum of total assets across withdrawable arks
* @custom:effects
* - No state changes
* @custom:security-considerations
* - Relies on accurate reporting of total assets by individual arks
* - Depends on the correctness of the withdrawableTotalAssets function
*/
function _withdrawableTotalAssets(
IArk bufferArk
) internal view returns (uint256 withdrawableTotalAssets) {
bool isWithdrawableTotalAssetsCached = StorageSlots
.IS_WITHDRAWABLE_ARKS_TOTAL_ASSETS_CACHED_STORAGE
.asBoolean()
.tload();
if (isWithdrawableTotalAssetsCached) {
return
StorageSlots
.WITHDRAWABLE_ARKS_TOTAL_ASSETS_STORAGE
.asUint256()
.tload();
}
IArk[] memory allArks = _getAllArks(
_getActiveArksAddresses(),
bufferArk
);
for (uint256 i = 0; i < allArks.length; i++) {
uint256 withdrawableAssets = IArk(allArks[i])
.withdrawableTotalAssets();
if (withdrawableAssets > 0) {
withdrawableTotalAssets += withdrawableAssets;
}
}
}
/**
* @dev Retrieves an array of all Arks, including regular Arks and the buffer Ark
* @param arks Array of regular ark addresses
* @param bufferArk The buffer ark instance
* @return An array of IArk interfaces representing all Arks in the system
* @custom:internal-logic
* - Creates a new array with length of regular arks plus one (for buffer ark)
* - Populates the array with regular arks and appends the buffer ark
* @custom:effects
* - No state changes
* @custom:security-considerations
* - Ensures the buffer ark is always included at the end of the array
*/
function _getAllArks(
address[] memory arks,
IArk bufferArk
) private pure returns (IArk[] memory) {
IArk[] memory allArks = new IArk[](arks.length + 1);
for (uint256 i = 0; i < arks.length; i++) {
allArks[i] = IArk(arks[i]);
}
allArks[arks.length] = IArk(bufferArk);
return allArks;
}
/**
* @dev Calculates the sum of total assets across all provided Arks
* @param _arks An array of IArk interfaces representing the Arks to sum assets from
* @return total The sum of total assets across all provided Arks
* @custom:internal-logic
* - Iterates through the provided array of Arks
* - Accumulates the total assets from each Ark
* @custom:effects
* - No state changes
* @custom:security-considerations
* - Relies on accurate reporting of total assets by individual arks
* - Vulnerable to integer overflow if total assets become extremely large
*/
function _sumTotalAssets(
IArk[] memory _arks
) private view returns (uint256 total) {
for (uint256 i = 0; i < _arks.length; i++) {
total += _arks[i].totalAssets();
}
}
/**
* @dev Flushes the cache for all arks and related data
* @custom:internal-logic
* - Resets the cached data for all arks and related data
* @custom:effects
* - Sets IS_TOTAL_ASSETS_CACHED_STORAGE to false
* - Sets IS_WITHDRAWABLE_ARKS_TOTAL_ASSETS_CACHED_STORAGE to false
* - Resets WITHDRAWABLE_ARKS_LENGTH_STORAGE to 0
* - Resets ARKS_LENGTH_STORAGE to 0
* @custom:security-considerations
* - Ensures that the next call to totalAssets or withdrawableTotalAssets recalculates values
* - Critical for maintaining data freshness and preventing stale cache issues
* - Flushes cache in case of reentrancy
* - That also allows efficient testing using Forge (transient storage is persistent during single test)
*/
function _flushCache() internal {
StorageSlots.IS_TOTAL_ASSETS_CACHED_STORAGE.asBoolean().tstore(false);
StorageSlots
.IS_WITHDRAWABLE_ARKS_TOTAL_ASSETS_CACHED_STORAGE
.asBoolean()
.tstore(false);
StorageSlots.WITHDRAWABLE_ARKS_LENGTH_STORAGE.asUint256().tstore(0);
StorageSlots.ARKS_LENGTH_STORAGE.asUint256().tstore(0);
}
/**
* @dev Retrieves the data (address, totalAssets) for all arks and the buffer ark
* @param bufferArk The buffer ark instance
* @return _arksData An array of ArkData structs containing the ark addresses and their total assets
* @custom:internal-logic
* - Initializes data for all arks including the buffer ark
* - Populates data for regular arks and buffer ark
* - Caches the total assets and ark data
* - buffer ark is always at the end of the array
* @custom:effects
* - Caches total assets and ark data
* - Modifies storage slots related to ark data
* @custom:security-considerations
* - Relies on accurate reporting of total assets by individual arks
*/
function _getArksData(
IArk bufferArk
) internal returns (ArkData[] memory _arksData) {
if (StorageSlots.IS_TOTAL_ASSETS_CACHED_STORAGE.asBoolean().tload()) {
return _getAllArksDataFromCache();
}
address[] memory arks = _getActiveArksAddresses();
// Initialize data for all arks
_arksData = new ArkData[](arks.length + 1); // +1 for buffer ark
uint256 totalAssets = 0;
// Populate data for regular arks
for (uint256 i = 0; i < arks.length; i++) {
uint256 arkAssets = IArk(arks[i]).totalAssets();
_arksData[i] = ArkData(arks[i], arkAssets);
totalAssets += arkAssets;
}
// Add buffer ark data
uint256 bufferArkAssets = bufferArk.totalAssets();
_arksData[arks.length] = ArkData(address(bufferArk), bufferArkAssets);
totalAssets += bufferArkAssets;
_cacheAllArksTotalAssets(totalAssets);
_cacheAllArks(_arksData);
}
/**
* @notice Retrieves a storage slot based on the provided prefix and index
* @param prefix The prefix for the storage slot
* @param index The index for the storage slot
* @return bytes32 The storage slot value
*/
function _getStorageSlot(
bytes32 prefix,
uint256 index
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(prefix, index));
}
/**
* @dev Caches the inflow and outflow balances for the specified Ark addresses.
* Updates the maximum inflow and outflow balances if they are not set.
* @param outflowArkAddress The address of the Ark from which the outflow is occurring.
* @param inflowArkAddress The address of the Ark to which the inflow is occurring.
* @param amount The amount to be added to both inflow and outflow balances.
* @return newInflowBalance The updated inflow balance for the inflow Ark.
* @return newOutflowBalance The updated outflow balance for the outflow Ark.
* @return maxInflow The maximum inflow balance for the inflow Ark.
* @return maxOutflow The maximum outflow balance for the outflow Ark.
*/
function _cacheArkFlow(
address outflowArkAddress,
address inflowArkAddress,
uint256 amount
)
internal
returns (
uint256 newInflowBalance,
uint256 newOutflowBalance,
uint256 maxInflow,
uint256 maxOutflow
)
{
bytes32 inflowSlot = _getStorageSlot(
StorageSlots.ARK_INFLOW_BALANCE_STORAGE,
uint256(uint160(inflowArkAddress))
);
bytes32 outflowSlot = _getStorageSlot(
StorageSlots.ARK_OUTFLOW_BALANCE_STORAGE,
uint256(uint160(outflowArkAddress))
);
bytes32 maxInflowSlot = _getStorageSlot(
StorageSlots.ARK_MAX_INFLOW_BALANCE_STORAGE,
uint256(uint160(inflowArkAddress))
);
bytes32 maxOutflowSlot = _getStorageSlot(
StorageSlots.ARK_MAX_OUTFLOW_BALANCE_STORAGE,
uint256(uint160(outflowArkAddress))
);
maxInflow = maxInflowSlot.asUint256().tload();
maxOutflow = maxOutflowSlot.asUint256().tload();
if (maxInflow == 0) {
maxInflow = IArk(inflowArkAddress).maxRebalanceInflow();
maxInflowSlot.asUint256().tstore(maxInflow);
}
if (maxOutflow == 0) {
maxOutflow = IArk(outflowArkAddress).maxRebalanceOutflow();
maxOutflowSlot.asUint256().tstore(maxOutflow);
}
// Load current balance (if it's the first time, it will be 0)
newInflowBalance = inflowSlot.asUint256().tload() + amount;
newOutflowBalance = outflowSlot.asUint256().tload() + amount;
inflowSlot.asUint256().tstore(newInflowBalance);
outflowSlot.asUint256().tstore(newOutflowBalance);
}
/**
* @notice Retrieves the data (address, totalAssets) for all withdrawable arks from cache
* @return arksData An array of ArkData structs containing the ark addresses and their total assets
*/
function _getWithdrawableArksDataFromCache()
internal
view
returns (ArkData[] memory arksData)
{
uint256 arksLength = StorageSlots
.WITHDRAWABLE_ARKS_LENGTH_STORAGE
.asUint256()
.tload();
arksData = new ArkData[](arksLength);
for (uint256 i = 0; i < arksLength; i++) {
address arkAddress = _getStorageSlot(
StorageSlots.WITHDRAWABLE_ARKS_ADDRESS_ARRAY_STORAGE,
i
).asAddress().tload();
uint256 totalAssets = _getStorageSlot(
StorageSlots.WITHDRAWABLE_ARKS_TOTAL_ASSETS_ARRAY_STORAGE,
i
).asUint256().tload();
arksData[i] = ArkData(arkAddress, totalAssets);
}
}
function _getAllArksDataFromCache()
internal
view
returns (ArkData[] memory arksData)
{
uint256 arksLength = StorageSlots
.ARKS_LENGTH_STORAGE
.asUint256()
.tload();
arksData = new ArkData[](arksLength);
for (uint256 i = 0; i < arksLength; i++) {
address arkAddress = _getStorageSlot(
StorageSlots.ARKS_ADDRESS_ARRAY_STORAGE,
i
).asAddress().tload();
uint256 totalAssets = _getStorageSlot(
StorageSlots.ARKS_TOTAL_ASSETS_ARRAY_STORAGE,
i
).asUint256().tload();
arksData[i] = ArkData(arkAddress, totalAssets);
}
}
/**
* @notice Caches the data for all arks in the specified storage slots
* @param arksData The array of ArkData structs containing the ark addresses and their total assets
* @param totalAssetsPrefix The prefix for the ark total assets storage slot
* @param addressPrefix The prefix for the ark addresses storage slot
* @param lengthSlot The storage slot containing the number of arks
*/
function _cacheArks(
ArkData[] memory arksData,
bytes32 totalAssetsPrefix,
bytes32 addressPrefix,
bytes32 lengthSlot
) internal {
for (uint256 i = 0; i < arksData.length; i++) {
_getStorageSlot(totalAssetsPrefix, i).asUint256().tstore(
arksData[i].totalAssets
);
_getStorageSlot(addressPrefix, i).asAddress().tstore(
arksData[i].arkAddress
);
}
lengthSlot.asUint256().tstore(arksData.length);
}
/**
* @notice Caches the data for all arks in the specified storage slots
* @param _arksData The array of ArkData structs containing the ark addresses and their total assets
*/
function _cacheAllArks(ArkData[] memory _arksData) internal {
_cacheArks(
_arksData,
StorageSlots.ARKS_TOTAL_ASSETS_ARRAY_STORAGE,
StorageSlots.ARKS_ADDRESS_ARRAY_STORAGE,
StorageSlots.ARKS_LENGTH_STORAGE
);
}
/**
* @notice Caches the data for all withdrawable arks in the specified storage slots
* @param _withdrawableArksData The array of ArkData structs containing the ark addresses and their total assets
*/
function _cacheWithdrawableArksTotalAssetsArray(
ArkData[] memory _withdrawableArksData
) internal {
_cacheArks(
_withdrawableArksData,
StorageSlots.WITHDRAWABLE_ARKS_TOTAL_ASSETS_ARRAY_STORAGE,
StorageSlots.WITHDRAWABLE_ARKS_ADDRESS_ARRAY_STORAGE,
StorageSlots.WITHDRAWABLE_ARKS_LENGTH_STORAGE
);
}
/**
* @dev Retrieves and processes data for withdrawable arks
* @param bufferArk The buffer ark instance
* @custom:internal-logic
* - Fetches data for all arks using _getArksData
* - Filters arks based on withdrawability
* - Accumulates total assets of withdrawable arks
* - Resizes the array to remove empty slots
* - Sorts the withdrawable arks by total assets
* - Caches the processed data
* - checks if the arks are cached, if yes skips the rest of the function
* - cache check is important for nested calls e.g. withdraw (withdrawFromArks)
* @custom:effects
* - Modifies storage by caching withdrawable arks data
* - Updates the total assets of withdrawable arks in storage
* @custom:security-considerations
* - Assumes the withdrawableTotalAssets function is correctly implemented by Ark contracts
* - Uses assembly for array resizing, which bypasses Solidity's safety checks
* - Relies on the correctness of _getArksData, _cacheWithdrawableArksTotalAssets,
* _sortArkDataByTotalAssets, and _cacheWithdrawableArksTotalAssetsArray functions
*/
function _getWithdrawableArksData(IArk bufferArk) internal {
if (
StorageSlots
.IS_WITHDRAWABLE_ARKS_TOTAL_ASSETS_CACHED_STORAGE
.asBoolean()
.tload()
) {
return;
}
ArkData[] memory _arksData = _getArksData(bufferArk);
// Initialize data for withdrawable arks
ArkData[] memory _withdrawableArksData = new ArkData[](
_arksData.length
);
uint256 withdrawableTotalAssets = 0;
uint256 withdrawableCount = 0;
// Populate data for withdrawable arks
for (uint256 i = 0; i < _arksData.length; i++) {
uint256 withdrawableAssets = IArk(_arksData[i].arkAddress)
.withdrawableTotalAssets();
if (withdrawableAssets > 0) {
// overwrite the ArkData struct with the withdrawable assets
_withdrawableArksData[withdrawableCount] = ArkData(
_arksData[i].arkAddress,
withdrawableAssets
);
withdrawableTotalAssets += withdrawableAssets;
withdrawableCount++;
}
}
// Resize _withdrawableArksData array to remove empty slots
assembly {
mstore(_withdrawableArksData, withdrawableCount)
}
_cacheWithdrawableArksTotalAssets(withdrawableTotalAssets);
_sortArkDataByTotalAssets(_withdrawableArksData);
_cacheWithdrawableArksTotalAssetsArray(_withdrawableArksData);
}
/**
* @notice Caches the total assets for all arks in the specified storage slot
* @param totalAssets The total assets to cache
*/
function _cacheAllArksTotalAssets(uint256 totalAssets) internal {
StorageSlots.TOTAL_ASSETS_STORAGE.asUint256().tstore(totalAssets);
StorageSlots.IS_TOTAL_ASSETS_CACHED_STORAGE.asBoolean().tstore(true);
}
/**
* @notice Caches the total assets for all withdrawable arks in the specified storage slot
* @param withdrawableTotalAssets The total assets to cache
*/
function _cacheWithdrawableArksTotalAssets(
uint256 withdrawableTotalAssets
) internal {
StorageSlots.WITHDRAWABLE_ARKS_TOTAL_ASSETS_STORAGE.asUint256().tstore(
withdrawableTotalAssets
);
StorageSlots
.IS_WITHDRAWABLE_ARKS_TOTAL_ASSETS_CACHED_STORAGE
.asBoolean()
.tstore(true);
}
/**
* @dev Sorts the ArkData structs based on their total assets in ascending order
* @param arkDataArray An array of ArkData structs to be sorted
* @custom:internal-logic
* - Implements a simple bubble sort algorithm
* - Compares adjacent elements and swaps them if they are in the wrong order
* - Continues until no more swaps are needed
* @custom:effects
* - Modifies the input array in-place, sorting it by totalAssets
* @custom:security-considerations
* - Time complexity is O(n^2), which may be inefficient for large arrays
* - Assumes that the totalAssets values fit within uint256 and won't overflow during comparisons
*/
function _sortArkDataByTotalAssets(
ArkData[] memory arkDataArray
) internal pure {
for (uint256 i = 0; i < arkDataArray.length; i++) {
for (uint256 j = i + 1; j < arkDataArray.length; j++) {
if (arkDataArray[i].totalAssets > arkDataArray[j].totalAssets) {
(arkDataArray[i], arkDataArray[j]) = (
arkDataArray[j],
arkDataArray[i]
);
}
}
}
}
/**
* @notice Returns an array of addresses for all currently active Arks in the fleet
* @dev This is an abstract internal function that must be implemented by the FleetCommander contract
* It serves as a critical component in the caching system for efficient ark management
*
* @return address[] An array containing the addresses of all active Arks
*
* @custom:purpose
* - Provides the foundation for the caching system by identifying which Arks are currently active
* - Used by _getArksData and _getWithdrawableArksData to populate cache data
* - Essential for operations that need to iterate over or manage all active Arks
* - Defined as virtual to be overridden by the FleetCommander contract and avoid calling it before it's required
*
* @custom:implementation-notes
* - Must be implemented by the inheriting FleetCommander contract
* - Should return a fresh array of addresses each time it's called
* - Buffer Ark should NOT be included in this list (it's handled separately)
* - Only truly active and operational Arks should be included
*
* @custom:related-functions
* - _getArksData: Uses this function to get data for all active Arks
* - _getWithdrawableArksData: Uses this function to identify withdrawable Arks
* - _getAllArks: Combines these addresses with the buffer Ark
*/
function _getActiveArksAddresses()
internal
view
virtual
returns (address[] memory)
{}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArk} from "../interfaces/IArk.sol";
import {FleetCommanderParams} from "../types/FleetCommanderTypes.sol";
import {FleetCommanderPausable} from "./FleetCommanderPausable.sol";
import {IFleetCommanderConfigProvider} from "../interfaces/IFleetCommanderConfigProvider.sol";
import {IFleetCommanderRewardsManagerFactory} from "../interfaces/IFleetCommanderRewardsManagerFactory.sol";
import {FleetConfig} from "../types/FleetCommanderTypes.sol";
import {ConfigurationManaged} from "@summerfi/config-contracts/contracts/ConfigurationManaged.sol";
import {FleetCommanderRewardsManager} from "./FleetCommanderRewardsManager.sol";
import {ArkParams, BufferArk} from "./arks/BufferArk.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {ProtocolAccessManaged} from "@summerfi/access-contracts/contracts/ProtocolAccessManaged.sol";
import {ContractSpecificRoles, IProtocolAccessManager} from "@summerfi/access-contracts/interfaces/IProtocolAccessManager.sol";
import {Constants} from "@summerfi/constants/Constants.sol";
import {PERCENTAGE_100, Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title FleetCommanderConfigProvider
* @author SummerFi
* @notice This contract provides configuration management for the FleetCommander
* @custom:see IFleetCommanderConfigProvider
*/
contract FleetCommanderConfigProvider is
ProtocolAccessManaged,
FleetCommanderPausable,
ConfigurationManaged,
IFleetCommanderConfigProvider
{
using EnumerableSet for EnumerableSet.AddressSet;
FleetConfig public config;
string public details;
EnumerableSet.AddressSet private _activeArks;
uint256 public constant MAX_REBALANCE_OPERATIONS = 50;
uint256 public constant INITIAL_MINIMUM_PAUSE_TIME = 2 days;
bool public transfersEnabled;
constructor(
FleetCommanderParams memory params
)
ProtocolAccessManaged(params.accessManager)
FleetCommanderPausable(INITIAL_MINIMUM_PAUSE_TIME)
ConfigurationManaged(params.configurationManager)
{
BufferArk _bufferArk = new BufferArk(
ArkParams({
name: "BufferArk",
details: "BufferArk details",
accessManager: address(params.accessManager),
asset: params.asset,
configurationManager: address(params.configurationManager),
depositCap: Constants.MAX_UINT256,
maxRebalanceOutflow: Constants.MAX_UINT256,
maxRebalanceInflow: Constants.MAX_UINT256,
requiresKeeperData: false,
maxDepositPercentageOfTVL: PERCENTAGE_100
}),
address(this)
);
emit ArkAdded(address(_bufferArk));
config = FleetConfig({
bufferArk: IArk(address(_bufferArk)),
minimumBufferBalance: params.initialMinimumBufferBalance,
depositCap: params.depositCap,
maxRebalanceOperations: MAX_REBALANCE_OPERATIONS,
stakingRewardsManager: IFleetCommanderRewardsManagerFactory(
fleetCommanderRewardsManagerFactory()
).createRewardsManager(address(_accessManager), address(this))
});
details = params.details;
}
/**
* @dev Modifier to restrict function access to only active Arks (excluding the buffer ark)
* @param arkAddress The address of the Ark to check
* @custom:internal-logic
* - Checks if the provided arkAddress is in the _activeArks set
* - If not found, reverts with FleetCommanderArkNotFound error
* - If the arkAddress is the buffer ark, it will revert, due to the buffer ark being a special case
* @custom:effects
* - No direct state changes, but may revert the transaction
* @custom:security-considerations
* - Ensures that only active Arks can perform certain operations
* - Prevents unauthorized access from inactive or non-existent Arks
* - Critical for maintaining the integrity and security of Ark-specific operations
*/
modifier onlyActiveArk(address arkAddress) {
if (!_activeArks.contains(arkAddress)) {
revert FleetCommanderArkNotFound(arkAddress);
}
_;
}
///@inheritdoc IFleetCommanderConfigProvider
function isArkActiveOrBufferArk(
address arkAddress
) public view returns (bool) {
return
_activeArks.contains(arkAddress) ||
arkAddress == address(config.bufferArk);
}
///@inheritdoc IFleetCommanderConfigProvider
function arks(uint256 index) public view returns (address) {
return _activeArks.at(index);
}
///@inheritdoc IFleetCommanderConfigProvider
function getActiveArks() public view returns (address[] memory) {
return _activeArks.values();
}
///@inheritdoc IFleetCommanderConfigProvider
function getConfig() external view override returns (FleetConfig memory) {
return config;
}
///@inheritdoc IFleetCommanderConfigProvider
function bufferArk() external view returns (address) {
return address(config.bufferArk);
}
// ARK MANAGEMENT
///@inheritdoc IFleetCommanderConfigProvider
function addArk(address ark) external onlyGovernor whenNotPaused {
_addArk(ark);
}
///@inheritdoc IFleetCommanderConfigProvider
function removeArk(address ark) external onlyGovernor whenNotPaused {
_removeArk(ark);
}
///@inheritdoc IFleetCommanderConfigProvider
function setArkDepositCap(
address ark,
uint256 newDepositCap
) external onlyCurator(address(this)) onlyActiveArk(ark) whenNotPaused {
IArk(ark).setDepositCap(newDepositCap);
}
///@inheritdoc IFleetCommanderConfigProvider
function setArkMaxDepositPercentageOfTVL(
address ark,
Percentage newMaxDepositPercentageOfTVL
) external onlyCurator(address(this)) onlyActiveArk(ark) whenNotPaused {
IArk(ark).setMaxDepositPercentageOfTVL(newMaxDepositPercentageOfTVL);
}
///@inheritdoc IFleetCommanderConfigProvider
function setArkMaxRebalanceOutflow(
address ark,
uint256 newMaxRebalanceOutflow
) external onlyCurator(address(this)) onlyActiveArk(ark) whenNotPaused {
IArk(ark).setMaxRebalanceOutflow(newMaxRebalanceOutflow);
}
///@inheritdoc IFleetCommanderConfigProvider
function setArkMaxRebalanceInflow(
address ark,
uint256 newMaxRebalanceInflow
) external onlyCurator(address(this)) onlyActiveArk(ark) whenNotPaused {
IArk(ark).setMaxRebalanceInflow(newMaxRebalanceInflow);
}
///@inheritdoc IFleetCommanderConfigProvider
function setMinimumBufferBalance(
uint256 newMinimumBalance
) external onlyCurator(address(this)) whenNotPaused {
config.minimumBufferBalance = newMinimumBalance;
emit FleetCommanderminimumBufferBalanceUpdated(newMinimumBalance);
}
///@inheritdoc IFleetCommanderConfigProvider
function setFleetDepositCap(
uint256 newCap
) external onlyCurator(address(this)) whenNotPaused {
config.depositCap = newCap;
emit FleetCommanderDepositCapUpdated(newCap);
}
///@inheritdoc IFleetCommanderConfigProvider
function updateStakingRewardsManager()
external
onlyCurator(address(this))
whenNotPaused
{
config.stakingRewardsManager = IFleetCommanderRewardsManagerFactory(
fleetCommanderRewardsManagerFactory()
).createRewardsManager(address(_accessManager), address(this));
emit FleetCommanderStakingRewardsUpdated(config.stakingRewardsManager);
}
///@inheritdoc IFleetCommanderConfigProvider
function setMaxRebalanceOperations(
uint256 newMaxRebalanceOperations
) external onlyCurator(address(this)) whenNotPaused {
if (newMaxRebalanceOperations > MAX_REBALANCE_OPERATIONS) {
revert FleetCommanderMaxRebalanceOperationsTooHigh(
newMaxRebalanceOperations
);
}
config.maxRebalanceOperations = newMaxRebalanceOperations;
emit FleetCommanderMaxRebalanceOperationsUpdated(
newMaxRebalanceOperations
);
}
///@inheritdoc IFleetCommanderConfigProvider
function setFleetTokenTransferability()
external
onlyGovernor
whenNotPaused
{
if (!transfersEnabled) {
transfersEnabled = true;
emit TransfersEnabled();
}
}
// INTERNAL FUNCTIONS
/**
* @dev Internal function to add a new Ark to the fleet
* @param ark The address of the Ark to be added
* @custom:internal-logic
* - Checks if the ark address is valid (not zero)
* - Verifies the ark is not already active
* - Sets the ark as active and determines its withdrawability
* - Checks if the ark already has a commander
* - Registers this contract as the ark's FleetCommander
* - Adds the ark to the list of active arks
* @custom:effects
* - Modifies isArkActiveOrBufferArk mapping
* - Updates the arks array
* - Emits an ArkAdded event
* @custom:security-considerations
* - Ensures no duplicate arks are added
* - Prevents adding arks that already have a commander
* - Only callable internally, typically by privileged roles
*/
function _addArk(address ark) internal {
if (ark == address(0)) {
revert FleetCommanderInvalidArkAddress();
}
if (isArkActiveOrBufferArk(ark)) {
revert FleetCommanderArkAlreadyExists(ark);
}
if (address(IArk(ark).asset()) != IERC4626(address(this)).asset()) {
revert FleetCommanderAssetMismatch();
}
IArk(ark).registerFleetCommander();
_activeArks.add(ark);
emit ArkAdded(ark);
}
/**
* @dev Internal function to remove an Ark from the fleet
* @param ark The address of the Ark to be removed
* @custom:internal-logic
* - Checks if the ark is currently active
* - Locates and removes the ark from the active arks list
* - Validates that the ark can be safely removed
* - Marks the ark as inactive
* - Unregisters this contract as the ark's FleetCommander
* - Revokes the COMMANDER_ROLE for this contract on the ark
* @custom:effects
* - Modifies the isArkActiveOrBufferArk mapping
* - Updates the arks array
* - Changes the ark's FleetCommander status
* - Revokes a role in the access manager
* - Emits an ArkRemoved event
* @custom:security-considerations
* - Ensures only active arks can be removed
* - Validates ark state before removal to prevent inconsistencies
* - Only callable internally, typically by privileged roles
*/
function _removeArk(address ark) internal onlyActiveArk(ark) {
_validateArkRemoval(ark);
_activeArks.remove(ark);
IArk(ark).unregisterFleetCommander();
_accessManager.selfRevokeContractSpecificRole(
ContractSpecificRoles.COMMANDER_ROLE,
address(ark)
);
emit ArkRemoved(ark);
}
/**
* @dev Internal function to validate if an Ark can be safely removed
* @param ark The address of the Ark to be validated for removal
* @custom:internal-logic
* - Checks if the ark's deposit cap is zero
* - Verifies that the ark holds no assets
* @custom:effects
* - No direct state changes, but may revert the transaction
* @custom:security-considerations
* - Prevents removal of arks with non-zero deposit caps or assets
* - Ensures arks are in a safe state before removal
* - Critical for maintaining the integrity of the fleet
*/
function _validateArkRemoval(address ark) internal view {
IArk _ark = IArk(ark);
if (_ark.depositCap() > 0) {
revert FleetCommanderArkDepositCapGreaterThanZero(ark);
}
if (_ark.totalAssets() != 0) {
revert FleetCommanderArkAssetsNotZero(ark);
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
/// @title FleetCommanderPausable
/// @notice An abstract contract that extends OpenZeppelin's Pausable with a minimum pause time functionality
/// @dev This contract should be inherited by other contracts that require a minimum pause duration
abstract contract FleetCommanderPausable is Pausable {
/// @notice The minimum duration that the contract must remain paused
uint256 public minimumPauseTime;
/// @notice The timestamp when the contract was last paused
uint256 public pauseStartTime;
/// @notice The minimum duration that the contract must remain paused
uint256 constant MINIMUM_PAUSE_TIME_SECONDS = 2 days;
/// @notice Emitted when the minimum pause time is updated
/// @param newMinimumPauseTime The new minimum pause time value
event MinimumPauseTimeUpdated(uint256 newMinimumPauseTime);
/// @notice Error thrown when trying to unpause before the minimum pause time has elapsed
error FleetCommanderPausableMinimumPauseTimeNotElapsed();
/// @notice Error thrown when trying to set a minimum pause time that is too short
error FleetCommanderPausableMinimumPauseTimeTooShort();
/**
* @notice Initializes the FleetCommanderPausable contract with a specified minimum pause time
* @param _initialMinimumPauseTime The initial minimum pause time in seconds
*/
constructor(uint256 _initialMinimumPauseTime) {
if (_initialMinimumPauseTime < MINIMUM_PAUSE_TIME_SECONDS) {
revert FleetCommanderPausableMinimumPauseTimeTooShort();
}
minimumPauseTime = _initialMinimumPauseTime;
emit MinimumPauseTimeUpdated(_initialMinimumPauseTime);
}
/**
* @notice Internal function to pause the contract
* @dev Overrides the _pause function from OpenZeppelin's Pausable
*/
function _pause() internal override {
super._pause();
pauseStartTime = block.timestamp;
}
/**
* @notice Internal function to unpause the contract
* @dev Overrides the _unpause function from OpenZeppelin's Pausable
* @dev Reverts if the minimum pause time has not elapsed
*/
function _unpause() internal override {
if (block.timestamp < pauseStartTime + minimumPauseTime) {
revert FleetCommanderPausableMinimumPauseTimeNotElapsed();
}
super._unpause();
}
/**
* @notice Internal function to set a new minimum pause time
* @param _newMinimumPauseTime The new minimum pause time in seconds
* @dev Emits a MinimumPauseTimeUpdated event
*/
function _setMinimumPauseTime(uint256 _newMinimumPauseTime) internal {
if (_newMinimumPauseTime < MINIMUM_PAUSE_TIME_SECONDS) {
revert FleetCommanderPausableMinimumPauseTimeTooShort();
}
minimumPauseTime = _newMinimumPauseTime;
emit MinimumPauseTimeUpdated(_newMinimumPauseTime);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IFleetCommander} from "../interfaces/IFleetCommander.sol";
import {IFleetCommanderRewardsManager} from "../interfaces/IFleetCommanderRewardsManager.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {StakingRewardsManagerBase, EnumerableSet} from "@summerfi/rewards-contracts/contracts/StakingRewardsManagerBase.sol";
import {IStakingRewardsManagerBase} from "@summerfi/rewards-contracts/interfaces/IStakingRewardsManagerBase.sol";
/**
* @title FleetCommanderRewardsManager
* @notice Contract for managing staking rewards specific to the Fleet system
* @dev Extends StakingRewardsManagerBase with Fleet-specific functionality
*/
contract FleetCommanderRewardsManager is
IFleetCommanderRewardsManager,
StakingRewardsManagerBase
{
using EnumerableSet for EnumerableSet.AddressSet;
address public immutable fleetCommander;
/**
* @notice Initializes the FleetStakingRewardsManager contract
* @param _accessManager Address of the AccessManager contract
* @param _fleetCommander Address of the FleetCommander contract
*/
constructor(
address _accessManager,
address _fleetCommander
) StakingRewardsManagerBase(_accessManager) {
fleetCommander = _fleetCommander;
stakingToken = fleetCommander;
}
/// @inheritdoc IStakingRewardsManagerBase
function stakeOnBehalfOf(
address receiver,
uint256 amount
) external override updateReward(receiver) {
_stake(_msgSender(), receiver, amount);
}
/// @inheritdoc IStakingRewardsManagerBase
function notifyRewardAmount(
address rewardToken,
uint256 reward,
uint256 newRewardsDuration
)
external
override(StakingRewardsManagerBase, IStakingRewardsManagerBase)
onlyGovernor
updateReward(address(0))
{
if (address(rewardToken) == address(stakingToken)) {
revert CantAddStakingTokenAsReward();
}
_notifyRewardAmount(rewardToken, reward, newRewardsDuration);
}
function unstakeAndWithdrawOnBehalfOf(
address owner,
uint256 amount,
bool claimRewards
) external override updateReward(owner) {
// Check if the caller is the same as the 'owner' address or has the required role
if (_msgSender() != owner && !hasAdmiralsQuartersRole(_msgSender())) {
revert CallerNotAdmiralsQuarters();
}
_unstake(owner, address(this), amount);
IFleetCommander(fleetCommander).redeem(amount, owner, address(this));
if (claimRewards) {
uint256 rewardTokenCount = _rewardTokensList.length();
for (uint256 i = 0; i < rewardTokenCount; i++) {
address rewardTokenAddress = _rewardTokensList.at(i);
_getReward(owner, rewardTokenAddress);
}
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @dev This library defines storage slots using the technique described in EIP-1967.
* @notice The subtraction of 1 from the keccak256 hash is used to avoid potential conflicts
* with Solidity's default storage slot allocation for state variables.
* @dev For more information, see: https://eips.ethereum.org/EIPS/eip-1967
*/
library StorageSlots {
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 public constant TOTAL_ASSETS_STORAGE =
keccak256(
abi.encode(
uint256(keccak256("fleetCommander.storage.totalAssets")) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant IS_TOTAL_ASSETS_CACHED_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256("fleetCommander.storage.isTotalAssetsCached")
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARKS_TOTAL_ASSETS_ARRAY_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256("fleetCommander.storage.arksTotalAssetsArray")
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARKS_ADDRESS_ARRAY_STORAGE =
keccak256(
abi.encode(
uint256(keccak256("fleetCommander.storage.arksAddressArray")) -
1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARKS_LENGTH_STORAGE =
keccak256(
abi.encode(
uint256(keccak256("fleetCommander.storage.arksLength")) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant WITHDRAWABLE_ARKS_TOTAL_ASSETS_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256(
"fleetCommander.storage.withdrawableArksTotalAssets"
)
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant WITHDRAWABLE_ARKS_TOTAL_ASSETS_ARRAY_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256(
"fleetCommander.storage.withdrawableArksTotalAssetsArray"
)
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant WITHDRAWABLE_ARKS_ADDRESS_ARRAY_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256(
"fleetCommander.storage.withdrawableArksAddressArray"
)
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant WITHDRAWABLE_ARKS_LENGTH_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256("fleetCommander.storage.withdrawableArksLength")
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant IS_WITHDRAWABLE_ARKS_TOTAL_ASSETS_CACHED_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256(
"fleetCommander.storage.isWithdrawableArksTotalAssetsCached"
)
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARK_INFLOW_BALANCE_STORAGE =
keccak256(
abi.encode(
uint256(keccak256("fleetCommander.storage.arkInflowBalance")) -
1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARK_OUTFLOW_BALANCE_STORAGE =
keccak256(
abi.encode(
uint256(keccak256("fleetCommander.storage.arkOutflowBalance")) -
1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARK_MAX_INFLOW_BALANCE_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256("fleetCommander.storage.arkMaxInflowBalance")
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant ARK_MAX_OUTFLOW_BALANCE_STORAGE =
keccak256(
abi.encode(
uint256(
keccak256("fleetCommander.storage.arkMaxOutflowBalance")
) - 1
)
) & ~bytes32(uint256(0xff));
bytes32 public constant TIP_TAKEN_STORAGE =
keccak256(
abi.encode(
uint256(keccak256("fleetCommander.storage._isCollectingTip")) -
1
)
) & ~bytes32(uint256(0xff));
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ITipper} from "../interfaces/ITipper.sol";
import {IERC20, IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {Constants} from "@summerfi/constants/Constants.sol";
import {PERCENTAGE_100, Percentage, toPercentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
import {PercentageUtils} from "@summerfi/percentage-solidity/contracts/PercentageUtils.sol";
/**
* @title Tipper
* @notice Contract implementing tip accrual functionality
* @dev This contract is designed to be inherited by ERC20-compliant contracts.
* It relies on the inheriting contract to implement ERC20 functionality,
* particularly the totalSupply() function.
*
* Important:
* 1. The inheriting contract MUST be ERC20-compliant.
* 2. The inheriting contract MUST implement the _mintTip function.
* 3. The contract uses its own address as the token for calculations,
* assuming it represents shares in the system.
* @custom:see ITipper
*/
abstract contract Tipper is ITipper {
using PercentageUtils for uint256;
/// @notice The maximum tip rate is 5%
Percentage immutable MAX_TIP_RATE = Percentage.wrap(5 * 1e18);
/*//////////////////////////////////////////////////////////////
STATE VARIABLES
//////////////////////////////////////////////////////////////*/
/// @notice The current tip rate (as Percentage)
/// @dev Percentages have 18 decimals of precision
Percentage public tipRate;
/// @notice The timestamp of the last tip accrual
uint256 public lastTipTimestamp;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Initializes the Tipper contract
* @param initialTipRate The initial tip rate for the Fleet
*/
constructor(Percentage initialTipRate) {
if (initialTipRate > MAX_TIP_RATE) {
revert TipRateCannotExceedFivePercent();
}
tipRate = initialTipRate;
lastTipTimestamp = block.timestamp;
}
/*//////////////////////////////////////////////////////////////
INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Abstract function to mint new shares as tips
* @dev This function is meant to be overridden by inheriting contracts.
* It is called internally by the _accrueTip function to mint new shares as tips.
* The implementation should create new shares for the specified account
* without requiring additional underlying assets.
* @param account The address to receive the minted tip shares
* @param amount The amount of shares to mint as a tip
*/
function _mintTip(address account, uint256 amount) internal virtual;
/**
* @notice Sets a new tip rate
* @dev Only callable by the FleetCommander. Accrues tips before changing the rate.
* @param newTipRate The new tip rate to set, as a Percentage type (defined in Percentage.sol)
* @param tipJar The address of the tip jar
* @param totalSupply The total supply of the shares
* @custom:internal-logic
* - Validates that the new tip rate is within the valid percentage range using PercentageUtils.sol
* - Accrues tips based on the current rate before updating
* - Updates the tip rate to the new value
* @custom:effects
* - May mint new tip shares (via _accrueTip)
* - Updates the tipRate state variable
* @custom:security-considerations
* - Ensures the new tip rate is within valid bounds (0-100%) using PercentageUtils.isPercentageInRange
* - Accrues tips before changing the rate to prevent loss of accrued tips
* @custom:note The newTipRate should be sized according to the PERCENTAGE_FACTOR in Percentage.sol.
* For example, 1% would be represented as 1 * 10^18 (assuming PERCENTAGE_DECIMALS is 18).
*/
function _setTipRate(
Percentage newTipRate,
address tipJar,
uint256 totalSupply
) internal {
if (newTipRate > MAX_TIP_RATE) {
revert TipRateCannotExceedFivePercent();
}
_accrueTip(tipJar, totalSupply); // Accrue tips before changing the rate
tipRate = newTipRate;
emit TipRateUpdated(newTipRate);
}
/**
* @notice Previews the amount of tip that would be accrued if _accrueTip was called
* @param tipJar The address of the tip jar
* @param totalSupply The total supply of the shares
* @return tippedShares The amount of tips that would be accrued in shares
*/
function previewTip(
address tipJar,
uint256 totalSupply
) public view returns (uint256 tippedShares) {
uint256 timeElapsed = block.timestamp - lastTipTimestamp;
if (timeElapsed == 0) return 0;
if (tipRate == toPercentage(0)) return 0;
uint256 totalShares = totalSupply -
IERC20(address(this)).balanceOf(tipJar);
tippedShares = _calculateTip(totalShares, timeElapsed);
return tippedShares;
}
/**
* @notice Accrues tips based on the current tip rate and time elapsed
* @dev Only callable by the FleetCommander
* @param tipJar The address of the tip jar
* @param totalSupply The total supply of the tip jar
* @return tippedShares The amount of tips accrued in shares
* @custom:internal-logic
* - Calculates the time elapsed since the last tip accrual
* - Computes the amount of new shares to mint based on the tip rate and time elapsed
* - Mints new shares to the tip jar if the calculated amount is greater than zero
* - Updates the lastTipTimestamp to the current block timestamp
* @custom:effects
* - May mint new tip shares (via _mintTip)
* - Updates the lastTipTimestamp state variable
* @custom:security-considerations
* - Handles the case where tipRate is zero to prevent unnecessary computations
* - Uses a custom power function for precise calculations
*/
function _accrueTip(
address tipJar,
uint256 totalSupply
) internal returns (uint256 tippedShares) {
if (tipRate == toPercentage(0)) {
lastTipTimestamp = block.timestamp;
return 0;
}
tippedShares = previewTip(tipJar, totalSupply);
if (tippedShares > 0) {
lastTipTimestamp = block.timestamp;
_mintTip(tipJar, tippedShares);
emit TipAccrued(tippedShares);
}
}
/**
* @notice Calculates the amount of tip to be accrued
* @param totalShares The total number of shares in the system
* @param timeElapsed The time elapsed since the last tip accrual
* @return The amount of new shares to be minted as tip
* @custom:internal-logic
* - Calculates a time-adjusted rate by scaling the annual tip rate by the elapsed time
* - Applies this adjusted rate to the total shares to determine tip amount
* @custom:effects
* - Does not modify any state, pure function
*/
function _calculateTip(
uint256 totalShares,
uint256 timeElapsed
) internal view returns (uint256) {
Percentage timeAdjustedRate = Percentage.wrap(
((timeElapsed * Percentage.unwrap(tipRate)) /
Constants.SECONDS_PER_YEAR)
);
return totalShares.applyPercentage(timeAdjustedRate);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkConfigProviderErrors
* @dev This file contains custom error definitions for the ArkConfigProvider contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IArkConfigProviderErrors {
/**
* @notice Thrown when attempting to deploy an Ark without specifying a configuration manager.
*/
error CannotDeployArkWithoutConfigurationManager();
/**
* @notice Thrown when attempting to deploy an Ark without specifying a Raft address.
*/
error CannotDeployArkWithoutRaft();
/**
* @notice Thrown when attempting to deploy an Ark without specifying a token address.
*/
error CannotDeployArkWithoutToken();
/**
* @notice Thrown when attempting to deploy an Ark with an empty name.
*/
error CannotDeployArkWithEmptyName();
/**
* @notice Thrown when an invalid vault address is provided.
*/
error InvalidVaultAddress();
/**
* @notice Thrown when there's a mismatch between expected and actual assets in an ERC4626 operation.
*/
error ERC4626AssetMismatch();
/**
* @notice Thrown when the max deposit percentage of TVL is greater than 100%.
*/
error MaxDepositPercentageOfTVLTooHigh();
/**
* @notice Thrown when attempting to register a FleetCommander when one is already registered.
*/
error FleetCommanderAlreadyRegistered();
/**
* @notice Thrown when attempting to unregister a FleetCommander by a non-registered address.
*/
error FleetCommanderNotRegistered();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkErrors
* @dev This file contains custom error definitions for the Ark contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IArkErrors {
/**
* @notice Thrown when attempting to remove a commander from an Ark that still has assets.
*/
error CannotRemoveCommanderFromArkWithAssets();
/**
* @notice Thrown when trying to add a commander to an Ark that already has one.
*/
error CannotAddCommanderToArkWithCommander();
/**
* @notice Thrown when attempting to use keeper data when it's not required.
*/
error CannotUseKeeperDataWhenNotRequired();
/**
* @notice Thrown when keeper data is required but not provided.
*/
error KeeperDataRequired();
/**
* @notice Thrown when invalid board data is provided.
*/
error InvalidBoardData();
/**
* @notice Thrown when invalid disembark data is provided.
*/
error InvalidDisembarkData();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IFleetCommanderConfigProviderErrors
* @dev This file contains custom error definitions for the FleetCommanderConfigProvider contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IFleetCommanderConfigProviderErrors {
/**
* @notice Thrown when an operation is attempted on a non-existent Ark
* @param ark The address of the Ark that was not found
*/
error FleetCommanderArkNotFound(address ark);
/**
* @notice Thrown when trying to remove an Ark that still has a non-zero deposit cap
* @param ark The address of the Ark with a non-zero deposit cap
*/
error FleetCommanderArkDepositCapGreaterThanZero(address ark);
/**
* @notice Thrown when attempting to remove an Ark that still holds assets
* @param ark The address of the Ark with non-zero assets
*/
error FleetCommanderArkAssetsNotZero(address ark);
/**
* @notice Thrown when trying to add an Ark that already exists in the system
* @param ark The address of the Ark that already exists
*/
error FleetCommanderArkAlreadyExists(address ark);
/**
* @notice Thrown when an invalid Ark address is provided (e.g., zero address)
*/
error FleetCommanderInvalidArkAddress();
/**
* @notice Thrown when trying to set a StakingRewardsManager to the zero address
*/
error FleetCommanderInvalidStakingRewardsManager();
/**
* @notice Thrown when trying to set a max rebalance operations to a value greater than the max allowed
* @param newMaxRebalanceOperations The new max rebalance operations value
*/
error FleetCommanderMaxRebalanceOperationsTooHigh(
uint256 newMaxRebalanceOperations
);
/**
* @notice Thrown when the asset of the Ark does not match the asset of the FleetCommander
*/
error FleetCommanderAssetMismatch();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IFleetCommanderErrors
* @dev This file contains custom error definitions for the FleetCommander contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface IFleetCommanderErrors {
/**
* @notice Thrown when transfers are disabled.
*/
error FleetCommanderTransfersDisabled();
/**
* @notice Thrown when an operation is attempted on an inactive Ark.
* @param ark The address of the inactive Ark.
*/
error FleetCommanderArkNotActive(address ark);
/**
* @notice Thrown when attempting to rebalance to an invalid Ark.
* @param ark The address of the invalid Ark.
* @param amount Amount of tokens added to target ark
* @param effectiveDepositCap Effective deposit cap of the ark (minimum of % of fleet TVL or arbitrary ark deposit
* cap)
*/
error FleetCommanderEffectiveDepositCapExceeded(
address ark,
uint256 amount,
uint256 effectiveDepositCap
);
/**
* @notice Thrown when there is insufficient buffer for an operation.
*/
error FleetCommanderInsufficientBuffer();
/**
* @notice Thrown when a rebalance operation is attempted with no actual operations.
*/
error FleetCommanderRebalanceNoOperations();
/**
* @notice Thrown when a rebalance operation exceeds the maximum allowed number of operations.
* @param operationsCount The number of operations attempted.
*/
error FleetCommanderRebalanceTooManyOperations(uint256 operationsCount);
/**
* @notice Thrown when a rebalance amount for an Ark is zero.
* @param ark The address of the Ark with zero rebalance amount.
*/
error FleetCommanderRebalanceAmountZero(address ark);
/**
* @notice Thrown when a withdrawal amount exceeds the maximum buffer limit.
*/
error WithdrawalAmountExceedsMaxBufferLimit();
/**
* @notice Thrown when an Ark's deposit cap is zero.
* @param ark The address of the Ark with zero deposit cap.
*/
error FleetCommanderArkDepositCapZero(address ark);
/**
* @notice Thrown when no funds were moved in an operation that expected fund movement.
*/
error FleetCommanderNoFundsMoved();
/**
* @notice Thrown when there are no excess funds to perform an operation.
*/
error FleetCommanderNoExcessFunds();
/**
* @notice Thrown when an invalid source Ark is specified for an operation.
* @param ark The address of the invalid source Ark.
*/
error FleetCommanderInvalidSourceArk(address ark);
/**
* @notice Thrown when an operation attempts to move more funds than available.
*/
error FleetCommanderMovedMoreThanAvailable();
/**
* @notice Thrown when an unauthorized withdrawal is attempted.
* @param caller The address attempting the withdrawal.
* @param owner The address of the authorized owner.
*/
error FleetCommanderUnauthorizedWithdrawal(address caller, address owner);
/**
* @notice Thrown when an unauthorized redemption is attempted.
* @param caller The address attempting the redemption.
* @param owner The address of the authorized owner.
*/
error FleetCommanderUnauthorizedRedemption(address caller, address owner);
/**
* @notice Thrown when attempting to use rebalance on a buffer Ark.
*/
error FleetCommanderCantUseRebalanceOnBufferArk();
/**
* @notice Thrown when attempting to use the maximum uint value for buffer adjustment from buffer.
*/
error FleetCommanderCantUseMaxUintMovingFromBuffer();
/**
* @notice Thrown when a rebalance operation exceeds the maximum outflow for an Ark.
* @param fromArk The address of the Ark from which funds are being moved.
* @param amount The amount being moved.
* @param maxRebalanceOutflow The maximum allowed outflow.
*/
error FleetCommanderExceedsMaxOutflow(
address fromArk,
uint256 amount,
uint256 maxRebalanceOutflow
);
/**
* @notice Thrown when a rebalance operation exceeds the maximum inflow for an Ark.
* @param fromArk The address of the Ark to which funds are being moved.
* @param amount The amount being moved.
* @param maxRebalanceInflow The maximum allowed inflow.
*/
error FleetCommanderExceedsMaxInflow(
address fromArk,
uint256 amount,
uint256 maxRebalanceInflow
);
/**
* @notice Thrown when the staking rewards manager is not set.
*/
error FleetCommanderStakingRewardsManagerNotSet();
/**
* @notice Thrown when user attempts to deposit/mint or withdraw/redeem 0 units
*/
error FleetCommanderZeroAmount();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title ITipperErrors
* @dev This file contains custom error definitions for the Tipper contract.
* @notice These custom errors provide more gas-efficient and informative error handling
* compared to traditional require statements with string messages.
*/
interface ITipperErrors {
/**
* @notice Thrown when an invalid FleetCommander address is provided.
*/
error InvalidFleetCommanderAddress();
/**
* @notice Thrown when an invalid TipJar address is provided.
*/
error InvalidTipJarAddress();
/**
* @notice Thrown when the tip rate exceeds 5%.
*/
error TipRateCannotExceedFivePercent();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IArkConfigProviderEvents
* @notice Interface for events emitted by ArkConfigProvider contracts
*/
interface IArkConfigProviderEvents {
/**
* @notice Emitted when the deposit cap of the Ark is updated
* @param newCap The new deposit cap value
*/
event DepositCapUpdated(uint256 newCap);
/**
* @notice Emitted when the maximum deposit percentage of TVL is updated
* @param newMaxDepositPercentageOfTVL The new maximum deposit percentage of TVL
*/
event MaxDepositPercentageOfTVLUpdated(
Percentage newMaxDepositPercentageOfTVL
);
/**
* @notice Emitted when the Raft address associated with the Ark is updated
* @param newRaft The address of the new Raft
*/
event RaftUpdated(address newRaft);
/**
* @notice Emitted when the maximum outflow limit for the Ark during rebalancing is updated
* @param newMaxOutflow The new maximum amount that can be transferred out of the Ark during a rebalance
*/
event MaxRebalanceOutflowUpdated(uint256 newMaxOutflow);
/**
* @notice Emitted when the maximum inflow limit for the Ark during rebalancing is updated
* @param newMaxInflow The new maximum amount that can be transferred into the Ark during a rebalance
*/
event MaxRebalanceInflowUpdated(uint256 newMaxInflow);
/**
* @notice Emitted when the Fleet Commander is registered
* @param commander The address of the Fleet Commander
*/
event FleetCommanderRegistered(address commander);
/**
* @notice Emitted when the Fleet Commander is unregistered
* @param commander The address of the Fleet Commander
*/
event FleetCommanderUnregistered(address commander);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkEvents
* @notice Interface for events emitted by Ark contracts
*/
interface IArkEvents {
/**
* @notice Emitted when rewards are harvested from an Ark
* @param rewardTokens The addresses of the harvested reward tokens
* @param rewardAmounts The amounts of the harvested reward tokens
*/
event ArkHarvested(
address[] indexed rewardTokens,
uint256[] indexed rewardAmounts
);
/**
* @notice Emitted when tokens are boarded (deposited) into the Ark
* @param commander The address of the FleetCommander initiating the boarding
* @param token The address of the token being boarded
* @param amount The amount of tokens boarded
*/
event Boarded(address indexed commander, address token, uint256 amount);
/**
* @notice Emitted when tokens are disembarked (withdrawn) from the Ark
* @param commander The address of the FleetCommander initiating the disembarking
* @param token The address of the token being disembarked
* @param amount The amount of tokens disembarked
*/
event Disembarked(address indexed commander, address token, uint256 amount);
/**
* @notice Emitted when tokens are moved from one address to another
* @param from Ark being boarded from
* @param to Ark being boarded to
* @param token The address of the token being moved
* @param amount The amount of tokens moved
*/
event Moved(
address indexed from,
address indexed to,
address token,
uint256 amount
);
/**
* @notice Emitted when the Ark is poked and the share price is updated
* @param currentPrice Current share price of the Ark
* @param timestamp The timestamp of the poke
*/
event ArkPoked(uint256 currentPrice, uint256 timestamp);
/**
* @notice Emitted when the Ark is swept
* @param sweptTokens The addresses of the swept tokens
* @param sweptAmounts The amounts of the swept tokens
*/
event ArkSwept(
address[] indexed sweptTokens,
uint256[] indexed sweptAmounts
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
interface IFleetCommanderConfigProviderEvents {
/**
* @notice Emitted when the deposit cap is updated
* @param newCap The new deposit cap value
*/
event FleetCommanderDepositCapUpdated(uint256 newCap);
/**
* @notice Emitted when a new Ark is added
* @param ark The address of the newly added Ark
*/
event ArkAdded(address indexed ark);
/**
* @notice Emitted when an Ark is removed
* @param ark The address of the removed Ark
*/
event ArkRemoved(address indexed ark);
/**
* @notice Emitted when new minimum funds buffer balance is set
* @param newBalance New minimum funds buffer balance
*/
event FleetCommanderminimumBufferBalanceUpdated(uint256 newBalance);
/**
* @notice Emitted when new max allowed rebalance operations is set
* @param newMaxRebalanceOperations Max allowed rebalance operations
*/
event FleetCommanderMaxRebalanceOperationsUpdated(
uint256 newMaxRebalanceOperations
);
/**
* @notice Emitted when the staking rewards contract address is updated
* @param newStakingRewards The address of the new staking rewards contract
*/
event FleetCommanderStakingRewardsUpdated(address newStakingRewards);
/**
* @notice Emitted when the transfer enabled status is updated
*/
event TransfersEnabled();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {RebalanceData} from "../types/FleetCommanderTypes.sol";
interface IFleetCommanderEvents {
/* EVENTS */
/**
* @notice Emitted when a rebalance operation is completed
* @param keeper The address of the keeper who initiated the rebalance
* @param rebalances An array of RebalanceData structs detailing the rebalance operations
*/
event Rebalanced(address indexed keeper, RebalanceData[] rebalances);
/**
* @notice Emitted when queued funds are committed
* @param keeper The address of the keeper who committed the funds
* @param prevBalance The previous balance before committing funds
* @param newBalance The new balance after committing funds
*/
event QueuedFundsCommitted(
address indexed keeper,
uint256 prevBalance,
uint256 newBalance
);
/**
* @notice Emitted when the funds queue is refilled
* @param keeper The address of the keeper who initiated the queue refill
* @param prevBalance The previous balance before refilling
* @param newBalance The new balance after refilling
*/
event FundsQueueRefilled(
address indexed keeper,
uint256 prevBalance,
uint256 newBalance
);
/**
* @notice Emitted when the minimum balance of the funds queue is updated
* @param keeper The address of the keeper who updated the minimum balance
* @param newBalance The new minimum balance
*/
event MinFundsQueueBalanceUpdated(
address indexed keeper,
uint256 newBalance
);
/**
* @notice Emitted when the fee address is updated
* @param newAddress The new fee address
*/
event FeeAddressUpdated(address newAddress);
/**
* @notice Emitted when the funds buffer balance is updated
* @param user The address of the user who triggered the update
* @param prevBalance The previous buffer balance
* @param newBalance The new buffer balance
*/
event FundsBufferBalanceUpdated(
address indexed user,
uint256 prevBalance,
uint256 newBalance
);
/**
* @notice Emitted when funds are withdrawn from Arks
* @param owner The address of the owner who initiated the withdrawal
* @param receiver The address of the receiver of the withdrawn funds
* @param totalWithdrawn The total amount of funds withdrawn
*/
event FleetCommanderWithdrawnFromArks(
address indexed owner,
address receiver,
uint256 totalWithdrawn
);
/**
* @notice Emitted when funds are redeemed from Arks
* @param owner The address of the owner who initiated the redemption
* @param receiver The address of the receiver of the redeemed funds
* @param totalRedeemed The total amount of funds redeemed
*/
event FleetCommanderRedeemedFromArks(
address indexed owner,
address receiver,
uint256 totalRedeemed
);
/**
* @notice Emitted when referee deposits into the FleetCommander
* @param referee The address of the referee who was referred
* @param referralCode The referral code of the referrer
*/
event FleetCommanderReferral(
address indexed referee,
bytes indexed referralCode
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
interface ITipperEvents {
/**
* @notice Emitted when the tip rate is updated
* @param newTipRate The new tip rate value
*/
event TipRateUpdated(Percentage newTipRate);
/**
* @notice Emitted when tips are accrued
* @param tipAmount The amount of tips accrued in the underlying asset's smallest unit
*/
event TipAccrued(uint256 tipAmount);
/**
* @notice Emitted when the tip jar address is updated
* @param newTipJar The new address of the tip jar
*/
event TipJarUpdated(address newTipJar);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArkErrors} from "../errors/IArkErrors.sol";
import {IArkEvents} from "../events/IArkEvents.sol";
import {IArkAccessManaged} from "./IArkAccessManaged.sol";
import {IArkConfigProvider} from "./IArkConfigProvider.sol";
/**
* @title IArk
* @notice Interface for the Ark contract, which manages funds and interacts with Rafts
* @dev Inherits from IArkAccessManaged for access control and IArkEvents for event definitions
*/
interface IArk is
IArkAccessManaged,
IArkEvents,
IArkErrors,
IArkConfigProvider
{
/**
* @notice Returns the current underlying balance of the Ark
* @return The total assets in the Ark, in token precision
*/
function totalAssets() external view returns (uint256);
/**
* @notice Triggers a harvest operation to collect rewards
* @param additionalData Optional bytes that might be required by a specific protocol to harvest
* @return rewardTokens The reward token addresses
* @return rewardAmounts The reward amounts
*/
function harvest(
bytes calldata additionalData
)
external
returns (address[] memory rewardTokens, uint256[] memory rewardAmounts);
/**
* @notice Sweeps tokens from the Ark
* @param tokens The tokens to sweep
* @return sweptTokens The swept tokens
* @return sweptAmounts The swept amounts
*/
function sweep(
address[] calldata tokens
)
external
returns (address[] memory sweptTokens, uint256[] memory sweptAmounts);
/**
* @notice Deposits (boards) tokens into the Ark
* @dev This function is called by the Fleet Commander to deposit assets into the Ark.
* It transfers tokens from the caller to this contract and then calls the internal _board function.
* @param amount The amount of assets to board
* @param boardData Additional data required for boarding, specific to the Ark implementation
* @custom:security-note This function is only callable by authorized entities
*/
function board(uint256 amount, bytes calldata boardData) external;
/**
* @notice Withdraws (disembarks) tokens from the Ark
* @param amount The amount of tokens to withdraw
* @param disembarkData Additional data that might be required by a specific protocol to withdraw funds
*/
function disembark(uint256 amount, bytes calldata disembarkData) external;
/**
* @notice Moves tokens from one ark to another
* @param amount The amount of tokens to move
* @param receiver The address of the Ark the funds will be boarded to
* @param boardData Additional data that might be required by a specific protocol to board funds
* @param disembarkData Additional data that might be required by a specific protocol to disembark funds
*/
function move(
uint256 amount,
address receiver,
bytes calldata boardData,
bytes calldata disembarkData
) external;
/**
* @notice Internal function to get the total assets that are withdrawable
* @return uint256 The total assets that are withdrawable
* @dev _withdrawableTotalAssets is an internal function that should be implemented by derived contracts to define
* specific withdrawability logic
* @dev the ark is withdrawable if it doesnt require keeper data and _isWithdrawable returns true
*/
function withdrawableTotalAssets() external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IArkAccessManaged
* @notice Extends the ProtocolAccessManaged contract with Ark specific AccessControl
* Used to specifically tie one FleetCommander to each Ark
*
* @dev One Ark specific role is defined:
* - Commander: is the fleet commander contract itself and couples an
* Ark to specific Fleet Commander
*
* The Commander role is still declared on the access manager to centralise
* role definitions.
*/
interface IArkAccessManaged {}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArkConfigProviderErrors} from "../errors/IArkConfigProviderErrors.sol";
import {IArkAccessManaged} from "./IArkAccessManaged.sol";
import {IArkConfigProviderEvents} from "../events/IArkConfigProviderEvents.sol";
import {ArkConfig} from "../types/ArkTypes.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IArkConfigProvider
* @notice Interface for configuration of Ark contracts
* @dev Inherits from IArkAccessManaged for access control and IArkConfigProviderEvents for event definitions
*/
interface IArkConfigProvider is
IArkAccessManaged,
IArkConfigProviderErrors,
IArkConfigProviderEvents
{
/**
* @notice Retrieves the current fleet config
*/
function getConfig() external view returns (ArkConfig memory);
/**
* @dev Returns the name of the Ark.
* @return The name of the Ark as a string.
*/
function name() external view returns (string memory);
/**
* @notice Returns the details of the Ark
* @return The details of the Ark as a string
*/
function details() external view returns (string memory);
/**
* @notice Returns the deposit cap for this Ark
* @return The maximum amount of tokens that can be deposited into the Ark
*/
function depositCap() external view returns (uint256);
/**
* @notice Returns the maximum percentage of TVL that can be deposited into the Ark
* @return The maximum percentage of TVL that can be deposited into the Ark
*/
function maxDepositPercentageOfTVL() external view returns (Percentage);
/**
* @notice Returns the maximum amount that can be moved to this Ark in one rebalance
* @return maximum amount that can be moved to this Ark in one rebalance
*/
function maxRebalanceInflow() external view returns (uint256);
/**
* @notice Returns the maximum amount that can be moved from this Ark in one rebalance
* @return maximum amount that can be moved from this Ark in one rebalance
*/
function maxRebalanceOutflow() external view returns (uint256);
/**
* @notice Returns whether the Ark requires keeper data to board/disembark
* @return true if the Ark requires keeper data, false otherwise
*/
function requiresKeeperData() external view returns (bool);
/**
* @notice Returns the ERC20 token managed by this Ark
* @return The IERC20 interface of the managed token
*/
function asset() external view returns (IERC20);
/**
* @notice Returns the address of the Fleet commander managing the ark
* @return address Address of Fleet commander managing the ark if a Commander is assigned, address(0) otherwise
*/
function commander() external view returns (address);
/**
* @notice Sets a new maximum allocation for the Ark
* @param newDepositCap The new maximum allocation amount
*/
function setDepositCap(uint256 newDepositCap) external;
/**
* @notice Sets a new maximum deposit percentage of TVL for the Ark
* @param newMaxDepositPercentageOfTVL The new maximum deposit percentage of TVL
*/
function setMaxDepositPercentageOfTVL(
Percentage newMaxDepositPercentageOfTVL
) external;
/**
* @notice Sets a new maximum amount that can be moved from the Ark in one rebalance
* @param newMaxRebalanceOutflow The new maximum amount that can be moved from the Ark
*/
function setMaxRebalanceOutflow(uint256 newMaxRebalanceOutflow) external;
/**
* @notice Sets a new maximum amount that can be moved to the Ark in one rebalance
* @param newMaxRebalanceInflow The new maximum amount that can be moved to the Ark
*/
function setMaxRebalanceInflow(uint256 newMaxRebalanceInflow) external;
/**
* @notice Registers the Fleet commander for the Ark
* @dev This function is used to register the Fleet commander for the Ark
* it's called by the FleetCommander when ark is added to the fleet
*/
function registerFleetCommander() external;
/**
* @notice Unregisters the Fleet commander for the Ark
* @dev This function is used to unregister the Fleet commander for the Ark
* it's called by the FleetCommander when ark is removed from the fleet
* all balance checks are done within the FleetCommander
*/
function unregisterFleetCommander() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IFleetCommanderErrors} from "../errors/IFleetCommanderErrors.sol";
import {IFleetCommanderEvents} from "../events/IFleetCommanderEvents.sol";
import {RebalanceData} from "../types/FleetCommanderTypes.sol";
import {IFleetCommanderConfigProvider} from "./IFleetCommanderConfigProvider.sol";
import {IERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IFleetCommander Interface
* @notice Interface for the FleetCommander contract, which manages asset allocation across multiple Arks
*/
interface IFleetCommander is
IERC4626,
IFleetCommanderEvents,
IFleetCommanderErrors,
IFleetCommanderConfigProvider
{
/**
* @notice Returns the total assets that are currently withdrawable from the FleetCommander.
* @dev If cached data is available, it will be used. Otherwise, it will be calculated on demand (and cached)
* @return uint256 The total amount of assets that can be withdrawn.
*/
function withdrawableTotalAssets() external view returns (uint256);
/**
* @notice Returns the total assets that are managed the FleetCommander.
* @dev If cached data is available, it will be used. Otherwise, it will be calculated on demand (and cached)
* @return uint256 The total amount of assets that can be withdrawn.
*/
function totalAssets() external view returns (uint256);
/**
* @notice Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, directly from Buffer.
* @param owner The address of the owner of the assets
* @return uint256 The maximum amount that can be withdrawn.
*/
function maxBufferWithdraw(address owner) external view returns (uint256);
/**
* @notice Returns the maximum amount of the underlying asset that can be redeemed from the owner balance in the
* Vault, directly from Buffer.
* @param owner The address of the owner of the assets
* @return uint256 The maximum amount that can be redeemed.
*/
function maxBufferRedeem(address owner) external view returns (uint256);
/* FUNCTIONS - PUBLIC - USER */
/**
* @notice Deposits a specified amount of assets into the contract for a given receiver.
* @param assets The amount of assets to be deposited.
* @param receiver The address of the receiver who will receive the deposited assets.
* @param referralCode An optional referral code that can be used for tracking or rewards.
*/
function deposit(
uint256 assets,
address receiver,
bytes memory referralCode
) external returns (uint256);
/**
* @notice Forces a withdrawal of assets from the FleetCommander
* @param assets The amount of assets to forcefully withdraw
* @param receiver The address that will receive the withdrawn assets
* @param owner The address of the owner of the assets
* @return shares The amount of shares redeemed
*/
function withdrawFromArks(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice Withdraws a specified amount of assets from the FleetCommander
* @dev This function first attempts to withdraw from the buffer. If the buffer doesn't have enough assets,
* it will withdraw from the arks. It also handles the case where the maximum possible amount is requested.
* @param assets The amount of assets to withdraw. If set to type(uint256).max, it will withdraw the maximum
* possible amount.
* @param receiver The address that will receive the withdrawn assets
* @param owner The address of the owner of the shares
* @return shares The number of shares burned in exchange for the withdrawn assets
*/
function withdraw(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice Redeems a specified amount of shares from the FleetCommander
* @dev This function first attempts to redeem from the buffer. If the buffer doesn't have enough assets,
* it will redeem from the arks. It also handles the case where the maximum possible amount is requested.
* @param shares The number of shares to redeem. If set to type(uint256).max, it will redeem all shares owned by the
* owner.
* @param receiver The address that will receive the redeemed assets
* @param owner The address of the owner of the shares
* @return assets The amount of assets received in exchange for the redeemed shares
*/
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @notice Redeems shares for assets from the FleetCommander
* @param shares The amount of shares to redeem
* @param receiver The address that will receive the assets
* @param owner The address of the owner of the shares
* @return assets The amount of assets forcefully withdrawn
*/
function redeemFromArks(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @notice Redeems shares for assets directly from the Buffer
* @param shares The amount of shares to redeem
* @param receiver The address that will receive the assets
* @param owner The address of the owner of the shares
* @return assets The amount of assets redeemed
*/
function redeemFromBuffer(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets);
/**
* @notice Forces a withdrawal of assets directly from the Buffer
* @param assets The amount of assets to withdraw
* @param receiver The address that will receive the withdrawn assets
* @param owner The address of the owner of the assets
* @return shares The amount of shares redeemed
*/
function withdrawFromBuffer(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares);
/**
* @notice Accrues and distributes tips
* @return uint256 The amount of tips accrued
*/
function tip() external returns (uint256);
/**
* @notice Rebalances the assets across Arks, including buffer adjustments
* @param data Array of RebalanceData structs
* @dev RebalanceData struct contains:
* - fromArk: The address of the Ark to move assets from
* - toArk: The address of the Ark to move assets to
* - amount: The amount of assets to move
* - boardData: Additional data for the board operation
* - disembarkData: Additional data for the disembark operation
* @dev Using type(uint256).max as the amount will move all assets from the fromArk to the toArk
* @dev For standard rebalancing:
* - Operations cannot involve the buffer Ark directly
* @dev For buffer adjustments:
* - type(uint256).max is only allowed when moving TO the buffer
* - When withdrawing FROM buffer, total amount cannot reduce balance below minFundsBufferBalance
* @dev The number of operations in a single rebalance call is limited to MAX_REBALANCE_OPERATIONS
* @dev Rebalance is subject to a cooldown period between calls
* @dev Only callable by accounts with the Keeper role
*/
function rebalance(RebalanceData[] calldata data) external;
/* FUNCTIONS - EXTERNAL - GOVERNANCE */
/**
* @notice Sets a new tip rate for the FleetCommander
* @dev Only callable by the governor
* @dev The tip rate is set as a Percentage. Percentages use 18 decimals of precision
* For example, for a 5% rate, you'd pass 5 * 1e18 (5 000 000 000 000 000 000)
* @param newTipRate The new tip rate as a Percentage
*/
function setTipRate(Percentage newTipRate) external;
/**
* @notice Sets a new minimum pause time for the FleetCommander
* @dev Only callable by the governor
* @param newMinimumPauseTime The new minimum pause time in seconds
*/
function setMinimumPauseTime(uint256 newMinimumPauseTime) external;
/**
* @notice Updates the rebalance cooldown period
* @param newCooldown The new cooldown period in seconds
*/
function updateRebalanceCooldown(uint256 newCooldown) external;
/**
* @notice Forces a rebalance operation
* @param data Array of typed rebalance data struct
* @dev has no cooldown enforced but only callable by privileged role
*/
function forceRebalance(RebalanceData[] calldata data) external;
/**
* @notice Pauses the FleetCommander
* @dev This function is used to pause the FleetCommander in case of critical issues or emergencies
* @dev Only callable by the guardian or governor
*/
function pause() external;
/**
* @notice Unpauses the FleetCommander
* @dev This function is used to resume normal operations after a pause
* @dev Only callable by the guardian or governor
*/
function unpause() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IFleetCommanderConfigProviderErrors} from "../errors/IFleetCommanderConfigProviderErrors.sol";
import {IFleetCommanderConfigProviderEvents} from "../events/IFleetCommanderConfigProviderEvents.sol";
import {FleetConfig} from "../types/FleetCommanderTypes.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title IFleetCommander Interface
* @notice Interface for the FleetCommander contract, which manages asset allocation across multiple Arks
*/
interface IFleetCommanderConfigProvider is
IFleetCommanderConfigProviderErrors,
IFleetCommanderConfigProviderEvents
{
/**
* @notice Retrieves the ark address at the specified index
* @param index The index of the ark in the arks array
* @return The address of the ark at the specified index
*/
function arks(uint256 index) external view returns (address);
/**
* @notice Retrieves the arks currently linked to fleet (excluding the buffer ark)
*/
function getActiveArks() external view returns (address[] memory);
/**
* @notice Retrieves the current fleet config
*/
function getConfig() external view returns (FleetConfig memory);
/**
* @notice Retrieves the buffer ark address
*/
function bufferArk() external view returns (address);
/**
* @notice Checks if the ark is part of the fleet or is the buffer ark
* @param ark The address of the Ark
* @return bool Returns true if the ark is active or the buffer ark, false otherwise.
*/
function isArkActiveOrBufferArk(address ark) external view returns (bool);
/* FUNCTIONS - EXTERNAL - GOVERNANCE */
/**
* @notice Adds a new Ark
* @param ark The address of the new Ark
*/
function addArk(address ark) external;
/**
* @notice Removes an existing Ark
* @param ark The address of the Ark to remove
*/
function removeArk(address ark) external;
/**
* @notice Sets a new deposit cap for Fleet
* @param newDepositCap The new deposit cap
*/
function setFleetDepositCap(uint256 newDepositCap) external;
/**
* @notice Sets a new deposit cap for an Ark
* @param ark The address of the Ark
* @param newDepositCap The new deposit cap
*/
function setArkDepositCap(address ark, uint256 newDepositCap) external;
/**
* @notice Sets the max deposit percentage of TVL for an Ark
* @param ark The address of the Ark
* @param newMaxDepositPercentageOfTVL The new max deposit percentage of TVL
*/
function setArkMaxDepositPercentageOfTVL(
address ark,
Percentage newMaxDepositPercentageOfTVL
) external;
/**
* @dev Sets the minimum buffer balance for the fleet commander.
* @param newMinimumBalance The new minimum buffer balance to be set.
*/
function setMinimumBufferBalance(uint256 newMinimumBalance) external;
/**
* @dev Sets the minimum number of allowe rebalance operations.
* @param newMaxRebalanceOperations The new maximum allowed rebalance operations.
*/
function setMaxRebalanceOperations(
uint256 newMaxRebalanceOperations
) external;
/**
* @notice Sets the maxRebalanceOutflow for an Ark
* @dev Only callable by the governor
* @param ark The address of the Ark
* @param newMaxRebalanceOutflow The new maxRebalanceOutflow value
*/
function setArkMaxRebalanceOutflow(
address ark,
uint256 newMaxRebalanceOutflow
) external;
/**
* @notice Sets the maxRebalanceInflow for an Ark
* @dev Only callable by the governor
* @param ark The address of the Ark
* @param newMaxRebalanceInflow The new maxRebalanceInflow value
*/
function setArkMaxRebalanceInflow(
address ark,
uint256 newMaxRebalanceInflow
) external;
/**
* @notice Deploys and sets the staking rewards manager contract address
*/
function updateStakingRewardsManager() external;
/**
* @notice Enables or disables transfers of fleet commander shares
* @dev Only callable by the governor when not paused
*/
function setFleetTokenTransferability() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IStakingRewardsManagerBase} from "@summerfi/rewards-contracts/interfaces/IStakingRewardsManagerBase.sol";
/**
* @title IFleetCommanderRewardsManager
* @notice Interface for the FleetStakingRewardsManager contract
* @dev Extends IStakingRewardsManagerBase with Fleet-specific functionality
*/
interface IFleetCommanderRewardsManager is IStakingRewardsManagerBase {
/**
* @notice Returns the address of the FleetCommander contract
* @return The address of the FleetCommander
*/
function fleetCommander() external view returns (address);
/**
* @notice Thrown when a non-AdmiralsQuarters contract tries
* to unstake on behalf
*/
error CallerNotAdmiralsQuarters();
/**
* @notice Thrown when AdmiralsQuarters tries to unstake for
* someone other than msg.sender
*/
error InvalidUnstakeRecipient();
/* @notice Thrown when trying to add a staking token as a reward token */
error CantAddStakingTokenAsReward();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title IFleetCommanderRewardsManagerFactory
* @notice Interface for the FleetCommanderRewardsManagerFactory contract
* @dev Defines the interface for creating new FleetCommanderRewardsManager instances
*/
interface IFleetCommanderRewardsManagerFactory {
/**
* @notice Event emitted when a new rewards manager is created
* @param rewardsManager Address of the newly created rewards manager
* @param fleetCommander Address of the fleet commander associated with the rewards manager
*/
event RewardsManagerCreated(
address indexed rewardsManager,
address indexed fleetCommander
);
/**
* @notice Creates a new FleetCommanderRewardsManager instance
* @param accessManager Address of the access manager to associate with the rewards manager
* @param fleetCommander Address of the fleet commander to associate with the rewards manager
* @return Address of the newly created rewards manager
*/
function createRewardsManager(
address accessManager,
address fleetCommander
) external returns (address);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ITipperErrors} from "../errors/ITipperErrors.sol";
import {ITipperEvents} from "../events/ITipperEvents.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title ITipper Interface
* @notice Interface for the tip accrual functionality in the FleetCommander contract
* @dev This interface defines the events and functions related to tip accrual and management
*/
interface ITipper is ITipperEvents, ITipperErrors {
/**
* @notice Get the current tip rate
* @return The current tip rate
* @dev A tip rate of 100 * 1e18 represents 100%
*/
function tipRate() external view returns (Percentage);
/**
* @notice Get the timestamp of the last tip accrual
* @return The Unix timestamp of when tips were last accrued
*/
function lastTipTimestamp() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IDistributor {
function toggleOperator(address user, address operator) external;
function claim(
address[] calldata users,
address[] calldata tokens,
uint256[] calldata amounts,
bytes32[][] calldata proofs
) external;
function operators(
address user,
address operator
) external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @title ArkParams
* @notice Constructor parameters for the Ark contract
*
* @dev This struct is used to initialize an Ark contract with all necessary parameters
*/
struct ArkParams {
/**
* @notice The name of the Ark
* @dev This should be a unique, human-readable identifier for the Ark
*/
string name;
/**
* @notice Additional details about the Ark
* @dev This can be used to store additional information about the Ark
*/
string details;
/**
* @notice The address of the access manager contract
* @dev This contract manages roles and permissions for the Ark
*/
address accessManager;
/**
* @notice The address of the configuration manager contract
* @dev This contract stores global configuration parameters
*/
address configurationManager;
/**
* @notice The address of the ERC20 token managed by this Ark
* @dev This is the underlying asset that the Ark will handle
*/
address asset;
/**
* @notice The maximum amount of tokens that can be deposited into the Ark
* @dev This cap helps to manage risk and exposure
*/
uint256 depositCap;
/**
* @notice The maximum amount of tokens that can be moved from this Ark in a single transaction
* @dev This limit helps to prevent large, sudden outflows
*/
uint256 maxRebalanceOutflow;
/**
* @notice The maximum amount of tokens that can be moved to this Ark in a single transaction
* @dev This limit helps to prevent large, sudden inflows
*/
uint256 maxRebalanceInflow;
/**
* @notice Whether the Ark requires Keepr data to be passed in with rebalance transactions
* @dev This flag is used to determine whether Keepr data is required for rebalance transactions
*/
bool requiresKeeperData;
/**
* @notice The maximum percentage of Total Value Locked (TVL) that can be deposited into this Ark
* @dev This value is represented as a percentage with 18 decimal places (1e18 = 100%)
* For example, 0.5e18 represents 50% of TVL
*/
Percentage maxDepositPercentageOfTVL;
}
/**
* @title ArkConfig
* @notice Configuration of the Ark contract
* @dev This struct stores the current configuration of an Ark, which can be updated during its lifecycle
*/
struct ArkConfig {
/**
* @notice The address of the commander (typically a FleetCommander contract)
* @dev The commander has special permissions to manage the Ark
*/
address commander;
/**
* @notice The address of the associated Raft contract
* @dev The Raft contract handles reward distribution and other protocol-wide functions
*/
address raft;
/**
* @notice The ERC20 token interface for the asset managed by this Ark
* @dev This allows direct interaction with the token contract
*/
IERC20 asset;
/**
* @notice The current maximum amount of tokens that can be deposited into the Ark
* @dev This can be adjusted by the commander to manage capacity
*/
uint256 depositCap;
/**
* @notice The current maximum amount of tokens that can be moved from this Ark in a single transaction
* @dev This can be adjusted to manage liquidity and risk
*/
uint256 maxRebalanceOutflow;
/**
* @notice The current maximum amount of tokens that can be moved to this Ark in a single transaction
* @dev This can be adjusted to manage inflows and capacity
*/
uint256 maxRebalanceInflow;
/**
* @notice The name of the Ark
* @dev This is typically set at initialization and not changed
*/
string name;
/**
* @notice Additional details about the Ark
* @dev This can be used to store additional information about the Ark
*/
string details;
/**
* @notice Whether the Ark requires Keeper data to be passed in with rebalance transactions
* @dev This flag is used to determine whether Keeper data is required for rebalance transactions
*/
bool requiresKeeperData;
/**
* @notice The maximum percentage of Total Value Locked (TVL) that can be deposited into this Ark
* @dev This value is represented as a percentage with 18 decimal places (1e18 = 100%)
* For example, 0.5e18 represents 50% of TVL
*/
Percentage maxDepositPercentageOfTVL;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {IArk} from "../interfaces/IArk.sol";
import {IFleetCommanderRewardsManager} from "../interfaces/IFleetCommanderRewardsManager.sol";
import {Percentage} from "@summerfi/percentage-solidity/contracts/Percentage.sol";
/**
* @notice Configuration parameters for the FleetCommander contract
*/
struct FleetCommanderParams {
string name;
string details;
string symbol;
address configurationManager;
address accessManager;
address asset;
uint256 initialMinimumBufferBalance;
uint256 initialRebalanceCooldown;
uint256 depositCap;
Percentage initialTipRate;
}
/**
* @title FleetConfig
* @notice Configuration parameters for the FleetCommander contract
* @dev This struct encapsulates the mutable configuration settings of a FleetCommander.
* These parameters can be updated during the contract's lifecycle to adjust its behavior.
*/
struct FleetConfig {
/**
* @notice The buffer Ark associated with this FleetCommander
* @dev This Ark is used as a temporary holding area for funds before they are allocated
* to other Arks or when they need to be quickly accessed for withdrawals.
*/
IArk bufferArk;
/**
* @notice The minimum balance that should be maintained in the buffer Ark
* @dev This value is used to ensure there's always a certain amount of funds readily
* available for withdrawals or rebalancing operations. It's denominated in the
* smallest unit of the underlying asset (e.g., wei for ETH).
*/
uint256 minimumBufferBalance;
/**
* @notice The maximum total value of assets that can be deposited into the FleetCommander
* @dev This cap helps manage the total assets under management and can be used to
* implement controlled growth strategies. It's denominated in the smallest unit
* of the underlying asset.
*/
uint256 depositCap;
/**
* @notice The maximum number of rebalance operations in a single rebalance
*/
uint256 maxRebalanceOperations;
/**
* @notice The address of the staking rewards contract
*/
address stakingRewardsManager;
}
/**
* @notice Data structure for the rebalance event
* @param fromArk The address of the Ark from which assets are moved
* @param toArk The address of the Ark to which assets are moved
* @param amount The amount of assets being moved
* @param boardData The data to be passed to the `board` function of the `toArk`
* @param disembarkData The data to be passed to the `disembark` function of the `fromArk`
* @dev if the `boardData` or `disembarkData` is not needed, it should be an empty byte array
*/
struct RebalanceData {
address fromArk;
address toArk;
uint256 amount;
bytes boardData;
bytes disembarkData;
}
/**
* @title ArkData
* @dev Struct to store information about an Ark.
* This struct holds the address of the Ark and the total assets it holds.
* @dev used in the caching mechanism for the FleetCommander
*/
struct ArkData {
/// @notice The address of the Ark.
address arkAddress;
/// @notice The total assets held by the Ark.
uint256 totalAssets;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ICooldownEnforcer} from "./ICooldownEnforcer.sol";
import "./ICooldownEnforcerErrors.sol";
import "./ICooldownEnforcerEvents.sol";
/**
* @title CooldownEnforcer
* @custom:see ICooldownEnforcer
*/
abstract contract CooldownEnforcer is ICooldownEnforcer {
/**
* STATE VARIABLES
*/
/**
* Cooldown between actions in seconds
*/
uint256 private _cooldown;
/**
* Timestamp of the last action in Epoch time (block timestamp)
*/
uint256 private _lastActionTimestamp;
/**
* @notice The minimum duration that the contract must remain paused
*/
uint256 private constant MINIMUM_COOLDOWN_TIME_SECONDS = 1 minutes;
/**
* @notice The maximum duration that the contract can enforce
*/
uint256 private constant MAXIMUM_COOLDOWN_TIME_SECONDS = 1 days;
/**
* CONSTRUCTOR
*/
/**
* @notice Initializes the cooldown period and sets the last action timestamp to the current block timestamp
* if required
*
* @param cooldown_ The cooldown period in seconds.
* @param enforceFromNow If true, the last action timestamp is set to the current block timestamp.
*
* @dev The last action timestamp is set to the current block timestamp if enforceFromNow is true,
* otherwise it is set to 0 signaling that the cooldown period has not started yet.
*/
constructor(uint256 cooldown_, bool enforceFromNow) {
if (cooldown_ < MINIMUM_COOLDOWN_TIME_SECONDS) {
revert CooldownEnforcerCooldownTooShort();
}
if (cooldown_ > MAXIMUM_COOLDOWN_TIME_SECONDS) {
revert CooldownEnforcerCooldownTooLong();
}
_cooldown = cooldown_;
if (enforceFromNow) {
_lastActionTimestamp = block.timestamp;
}
}
/**
* MODIFIERS
*/
/**
* @notice Modifier to enforce the cooldown period between actions.
*
* @dev If the cooldown period has not elapsed, the function call will revert.
* Otherwise, the last action timestamp is updated to the current block timestamp.
*/
modifier enforceCooldown() {
if (block.timestamp - _lastActionTimestamp < _cooldown) {
revert CooldownNotElapsed(
_lastActionTimestamp,
_cooldown,
block.timestamp
);
}
// Update the last action timestamp to the current block timestamp
// before executing the function so it acts as a reentrancy guard
// by not allowing a second call to execute
_lastActionTimestamp = block.timestamp;
_;
}
/**
* VIEW FUNCTIONS
*/
/// @inheritdoc ICooldownEnforcer
function getCooldown() public view returns (uint256) {
return _cooldown;
}
/// @inheritdoc ICooldownEnforcer
function getLastActionTimestamp() public view returns (uint256) {
return _lastActionTimestamp;
}
/**
* INTERNAL STATE CHANGE FUNCTIONS
*/
/**
* @notice Updates the cooldown period.
*
* @param newCooldown The new cooldown period in seconds.
*
* @dev The function is internal so it can be wrapped with access modifiers if needed
*/
function _updateCooldown(uint256 newCooldown) internal {
if (newCooldown < MINIMUM_COOLDOWN_TIME_SECONDS) {
revert CooldownEnforcerCooldownTooShort();
}
if (newCooldown > MAXIMUM_COOLDOWN_TIME_SECONDS) {
revert CooldownEnforcerCooldownTooLong();
}
emit CooldownUpdated(_cooldown, newCooldown);
_cooldown = newCooldown;
}
/**
* @notice Resets the last action timestamp
* @dev Allows for cooldown period to be skipped (IE after force withdrawal)
*/
function _resetLastActionTimestamp() internal {
_lastActionTimestamp = 0;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title ICooldownEnforcer
* @notice Enforces a cooldown period between actions. It provides the basic management for a cooldown
* period, allows to update the cooldown period and provides a modifier to enforce the cooldown.
*/
interface ICooldownEnforcer {
/**
* ERRORS
*/
/**
* @notice Error thrown when the cooldown period is too short
*/
error CooldownEnforcerCooldownTooShort();
/**
* @notice Error thrown when the cooldown period is too long
*/
error CooldownEnforcerCooldownTooLong();
/**
* VIEW FUNCTIONS
*/
/**
* @notice Returns the cooldown period in seoonds.
*/
function getCooldown() external view returns (uint256);
/**
* @notice Returns the timestamp of the last action in Epoch time (block timestamp).
*/
function getLastActionTimestamp() external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @notice Emitted by the modifier when the cooldown period has not elapsed.
*
* @param lastActionTimestamp The timestamp of the last action in Epoch time (block timestamp).
* @param cooldown The cooldown period in seconds.
* @param currentTimestamp The current block timestamp.
*/
error CooldownNotElapsed(
uint256 lastActionTimestamp,
uint256 cooldown,
uint256 currentTimestamp
);// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.28; /** * EVENTS */ /** * @param previousCooldown The previous cooldown period in seconds. * @param newCooldown The new cooldown period in seconds. */ event CooldownUpdated(uint256 previousCooldown, uint256 newCooldown);
{
"optimizer": {
"enabled": true,
"runs": 25
},
"evmVersion": "cancun",
"viaIR": true,
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"components":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"details","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"address","name":"configurationManager","type":"address"},{"internalType":"address","name":"accessManager","type":"address"},{"internalType":"address","name":"asset","type":"address"},{"internalType":"uint256","name":"initialMinimumBufferBalance","type":"uint256"},{"internalType":"uint256","name":"initialRebalanceCooldown","type":"uint256"},{"internalType":"uint256","name":"depositCap","type":"uint256"},{"internalType":"Percentage","name":"initialTipRate","type":"uint256"}],"internalType":"struct FleetCommanderParams","name":"params","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotAdmin","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotAuthorizedToBoard","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotCommander","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"CallerIsNotContractSpecificRole","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotCurator","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotDecayController","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotFoundation","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotGovernor","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotGuardian","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotGuardianOrGovernor","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotKeeper","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotRaft","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotRaftOrCommander","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"CallerIsNotSuperKeeper","type":"error"},{"inputs":[],"name":"ConfigurationManagerZeroAddress","type":"error"},{"inputs":[],"name":"CooldownEnforcerCooldownTooLong","type":"error"},{"inputs":[],"name":"CooldownEnforcerCooldownTooShort","type":"error"},{"inputs":[{"internalType":"uint256","name":"lastActionTimestamp","type":"uint256"},{"internalType":"uint256","name":"cooldown","type":"uint256"},{"internalType":"uint256","name":"currentTimestamp","type":"uint256"}],"name":"CooldownNotElapsed","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"DirectGrantIsDisabled","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"DirectRevokeIsDisabled","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxDeposit","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxMint","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxRedeem","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"}],"name":"ERC4626ExceededMaxWithdraw","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderArkAlreadyExists","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderArkAssetsNotZero","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderArkDepositCapGreaterThanZero","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderArkDepositCapZero","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderArkNotActive","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderArkNotFound","type":"error"},{"inputs":[],"name":"FleetCommanderAssetMismatch","type":"error"},{"inputs":[],"name":"FleetCommanderCantUseMaxUintMovingFromBuffer","type":"error"},{"inputs":[],"name":"FleetCommanderCantUseRebalanceOnBufferArk","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"effectiveDepositCap","type":"uint256"}],"name":"FleetCommanderEffectiveDepositCapExceeded","type":"error"},{"inputs":[{"internalType":"address","name":"fromArk","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceInflow","type":"uint256"}],"name":"FleetCommanderExceedsMaxInflow","type":"error"},{"inputs":[{"internalType":"address","name":"fromArk","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceOutflow","type":"uint256"}],"name":"FleetCommanderExceedsMaxOutflow","type":"error"},{"inputs":[],"name":"FleetCommanderInsufficientBuffer","type":"error"},{"inputs":[],"name":"FleetCommanderInvalidArkAddress","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderInvalidSourceArk","type":"error"},{"inputs":[],"name":"FleetCommanderInvalidStakingRewardsManager","type":"error"},{"inputs":[{"internalType":"uint256","name":"newMaxRebalanceOperations","type":"uint256"}],"name":"FleetCommanderMaxRebalanceOperationsTooHigh","type":"error"},{"inputs":[],"name":"FleetCommanderMovedMoreThanAvailable","type":"error"},{"inputs":[],"name":"FleetCommanderNoExcessFunds","type":"error"},{"inputs":[],"name":"FleetCommanderNoFundsMoved","type":"error"},{"inputs":[],"name":"FleetCommanderPausableMinimumPauseTimeNotElapsed","type":"error"},{"inputs":[],"name":"FleetCommanderPausableMinimumPauseTimeTooShort","type":"error"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"FleetCommanderRebalanceAmountZero","type":"error"},{"inputs":[],"name":"FleetCommanderRebalanceNoOperations","type":"error"},{"inputs":[{"internalType":"uint256","name":"operationsCount","type":"uint256"}],"name":"FleetCommanderRebalanceTooManyOperations","type":"error"},{"inputs":[],"name":"FleetCommanderStakingRewardsManagerNotSet","type":"error"},{"inputs":[],"name":"FleetCommanderTransfersDisabled","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"FleetCommanderUnauthorizedRedemption","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"FleetCommanderUnauthorizedWithdrawal","type":"error"},{"inputs":[],"name":"FleetCommanderZeroAmount","type":"error"},{"inputs":[{"internalType":"address","name":"invalidAddress","type":"address"}],"name":"InvalidAccessManagerAddress","type":"error"},{"inputs":[],"name":"InvalidFleetCommanderAddress","type":"error"},{"inputs":[],"name":"InvalidTipJarAddress","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"TipRateCannotExceedFivePercent","type":"error"},{"inputs":[],"name":"WithdrawalAmountExceedsMaxBufferLimit","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"ark","type":"address"}],"name":"ArkAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"ark","type":"address"}],"name":"ArkRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"previousCooldown","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newCooldown","type":"uint256"}],"name":"CooldownUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newAddress","type":"address"}],"name":"FeeAddressUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newCap","type":"uint256"}],"name":"FleetCommanderDepositCapUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newMaxRebalanceOperations","type":"uint256"}],"name":"FleetCommanderMaxRebalanceOperationsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalRedeemed","type":"uint256"}],"name":"FleetCommanderRedeemedFromArks","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"referee","type":"address"},{"indexed":true,"internalType":"bytes","name":"referralCode","type":"bytes"}],"name":"FleetCommanderReferral","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newStakingRewards","type":"address"}],"name":"FleetCommanderStakingRewardsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"totalWithdrawn","type":"uint256"}],"name":"FleetCommanderWithdrawnFromArks","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"FleetCommanderminimumBufferBalanceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"prevBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"FundsBufferBalanceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"keeper","type":"address"},{"indexed":false,"internalType":"uint256","name":"prevBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"FundsQueueRefilled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"keeper","type":"address"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"MinFundsQueueBalanceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newMinimumPauseTime","type":"uint256"}],"name":"MinimumPauseTimeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"keeper","type":"address"},{"indexed":false,"internalType":"uint256","name":"prevBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"QueuedFundsCommitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"keeper","type":"address"},{"components":[{"internalType":"address","name":"fromArk","type":"address"},{"internalType":"address","name":"toArk","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"boardData","type":"bytes"},{"internalType":"bytes","name":"disembarkData","type":"bytes"}],"indexed":false,"internalType":"struct RebalanceData[]","name":"rebalances","type":"tuple[]"}],"name":"Rebalanced","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"tipAmount","type":"uint256"}],"name":"TipAccrued","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newTipJar","type":"address"}],"name":"TipJarUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"Percentage","name":"newTipRate","type":"uint256"}],"name":"TipRateUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"TransfersEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"ADMIRALS_QUARTERS_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DECAY_CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GOVERNOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GUARDIAN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INITIAL_MINIMUM_PAUSE_TIME","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_REBALANCE_OPERATIONS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SUPER_KEEPER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"addArk","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"arks","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bufferArk","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"config","outputs":[{"internalType":"contract IArk","name":"bufferArk","type":"address"},{"internalType":"uint256","name":"minimumBufferBalance","type":"uint256"},{"internalType":"uint256","name":"depositCap","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceOperations","type":"uint256"},{"internalType":"address","name":"stakingRewardsManager","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"configurationManager","outputs":[{"internalType":"contract IConfigurationManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"convertToAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"convertToShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"bytes","name":"referralCode","type":"bytes"}],"name":"deposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"details","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fleetCommanderRewardsManagerFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"fromArk","type":"address"},{"internalType":"address","name":"toArk","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"boardData","type":"bytes"},{"internalType":"bytes","name":"disembarkData","type":"bytes"}],"internalType":"struct RebalanceData[]","name":"rebalanceData","type":"tuple[]"}],"name":"forceRebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum ContractSpecificRoles","name":"roleName","type":"uint8"},{"internalType":"address","name":"roleTargetContract","type":"address"}],"name":"generateRole","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getActiveArks","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getConfig","outputs":[{"components":[{"internalType":"contract IArk","name":"bufferArk","type":"address"},{"internalType":"uint256","name":"minimumBufferBalance","type":"uint256"},{"internalType":"uint256","name":"depositCap","type":"uint256"},{"internalType":"uint256","name":"maxRebalanceOperations","type":"uint256"},{"internalType":"address","name":"stakingRewardsManager","type":"address"}],"internalType":"struct FleetConfig","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCooldown","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IArk","name":"ark","type":"address"}],"name":"getEffectiveArkDepositCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLastActionTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"harborCommand","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"hasAdmiralsQuartersRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"arkAddress","type":"address"}],"name":"isArkActiveOrBufferArk","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTipTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxBufferRedeem","outputs":[{"internalType":"uint256","name":"_maxBufferRedeem","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxBufferWithdraw","outputs":[{"internalType":"uint256","name":"_maxBufferWithdraw","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxDeposit","outputs":[{"internalType":"uint256","name":"_maxDeposit","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxMint","outputs":[{"internalType":"uint256","name":"_maxMint","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxRedeem","outputs":[{"internalType":"uint256","name":"_maxRedeem","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"maxWithdraw","outputs":[{"internalType":"uint256","name":"_maxWithdraw","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minimumPauseTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pauseStartTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewMint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"previewRedeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tipJar","type":"address"},{"internalType":"uint256","name":"totalSupply","type":"uint256"}],"name":"previewTip","outputs":[{"internalType":"uint256","name":"tippedShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"name":"previewWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"raft","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"fromArk","type":"address"},{"internalType":"address","name":"toArk","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"boardData","type":"bytes"},{"internalType":"bytes","name":"disembarkData","type":"bytes"}],"internalType":"struct RebalanceData[]","name":"rebalanceData","type":"tuple[]"}],"name":"rebalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeemFromArks","outputs":[{"internalType":"uint256","name":"totalAssetsToWithdraw","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"redeemFromBuffer","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"ark","type":"address"}],"name":"removeArk","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"ark","type":"address"},{"internalType":"uint256","name":"newDepositCap","type":"uint256"}],"name":"setArkDepositCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"ark","type":"address"},{"internalType":"Percentage","name":"newMaxDepositPercentageOfTVL","type":"uint256"}],"name":"setArkMaxDepositPercentageOfTVL","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"ark","type":"address"},{"internalType":"uint256","name":"newMaxRebalanceInflow","type":"uint256"}],"name":"setArkMaxRebalanceInflow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"ark","type":"address"},{"internalType":"uint256","name":"newMaxRebalanceOutflow","type":"uint256"}],"name":"setArkMaxRebalanceOutflow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newCap","type":"uint256"}],"name":"setFleetDepositCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"setFleetTokenTransferability","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxRebalanceOperations","type":"uint256"}],"name":"setMaxRebalanceOperations","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMinimumBalance","type":"uint256"}],"name":"setMinimumBufferBalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newMinimumPauseTime","type":"uint256"}],"name":"setMinimumPauseTime","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Percentage","name":"newTipRate","type":"uint256"}],"name":"setTipRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tip","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tipJar","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tipRate","outputs":[{"internalType":"Percentage","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"transfersEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newCooldown","type":"uint256"}],"name":"updateRebalanceCooldown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"updateStakingRewardsManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdraw","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdrawFromArks","outputs":[{"internalType":"uint256","name":"totalSharesToRedeem","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"withdrawFromBuffer","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawableTotalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]Contract Creation Code
6101208060405234610848576194f6803803809161001d8285610b0e565b8339810190602081830312610848578051906001600160401b03821161084857019061014082820312610848576040519061005782610af2565b82516001600160401b0381116108485781610073918501610b4c565b825260208301516001600160401b0381116108485781610094918501610b4c565b60208301908152604084015190916001600160401b038211610848576100bb918501610b4c565b918260408201526100ce60608501610b92565b9160608201928084526100e360808701610b92565b9560808401948786526100f860a08301610b92565b9560a0860198878a5260c08401519460c0880195865260e0850151998a60e08a0152610120610100870151966101008b019788520151998a6101208b015260018060a01b031698519160018060a01b03169260018060a01b03169180519060018060401b0382116108005760035490600182811c92168015610ae8575b60208310146107e25781601f849311610a7a575b50602090601f8311600114610a14575f92610a09575b50508160011b915f199060031b1c1916176003555b8051906001600160401b0382116108005760045490600182811c921680156109ff575b60208310146107e25781601f849311610991575b50602090601f831160011461092b575f92610920575b50508160011b915f199060031b1c1916176004555b801561090d576040516301ffc9a760e01b815263261c910560e21b6004820152602081602481855afa908115610902575f916108c7575b50156108b5576080526202a3006006557f3cf175d91d8c5823f3729423b5a64130e40d4b09e88c6dc1925a260f26818c2560206040516202a3008152a180156108a65760a0525197519051604051986001600160a01b039283169291821691166102b68a610af2565b6040998a9283516102c78582610b0e565b600981526842756666657241726b60b81b602082015282528351946102ec8587610b0e565b601186527042756666657241726b2064657461696c7360781b602087015260208301958652848301938452606083019182526080830190815260a083015f19815260c084015f19815260e08501915f1983526101008601935f855261012087019568056bc75e2d63100000875289519a6128db90818d01998d8b1060018060401b038c1117610800578c6101408f9e928f938e6103b09761039d96616c1b90395251918d01526101808c0190610ba6565b90518a8203603f190160608c0152610ba6565b98516001600160a01b0390811660808a01529051811660a089015290511660c08701525160e08601525161010085015251610120840152511515610140830152516101608201523060209091015203905ff0801561089c5760018060a01b031690875192827fcb4a29d359e86f179111dcba8714def1a859612f729f2d224d13efeac51b36bc5f80a25190519160208460048160018060a01b0360a05116633df94cfb60e21b82525afa938415610854575f9461085e575b506080518951630f07f82960e01b81526001600160a01b03918216600482015230602482015294602091869160449183915f91165af1938415610854575f94610814575b50885160a08101946001600160401b03861182871017610800576080958b52828252836020830152848b8301526032606083015260018060a01b0316948591015260018060a01b03196008541617600855600955600a556032600b5560018060a01b0319600c541617600c555180519060018060401b03821161080057600d5490600182811c921680156107f6575b60208310146107e25781601f849311610774575b50602090601f831160011461070e575f92610703575b50508160011b915f199060031b1c191617600d555b61058381610bca565b90156106fb575b60e05260c052674563918244f4000061010052674563918244f4000081116106ec5760115542601255603c81106106dd576201518081116106ce5760135551615fad9081610c6e823960805181818161090501528181610b5c01528181610c8601528181610df801528181610fbd015281816113600152818161149d015281816117bd015281816119ff01528181611bd701528181611e5d01528181611f2001528181611fe2015281816120d401528181612185015281816122790152818161233901528181612427015281816125b00152818161314001526132b2015260a0518181816108070152818161105b0152818161112301528181611d7001528181612fa60152613d6c015260c051818181610bcf01528181612b64015281816135bb015281816144d7015261495f015260e05181610abe01526101005181612c340152f35b637092ddf560e01b5f5260045ffd5b63d93a8d8760e01b5f5260045ffd5b63ab9a408f60e01b5f5260045ffd5b50601261058a565b015190505f80610565565b600d5f9081528281209350601f198516905b81811061075c5750908460019594939210610744575b505050811b01600d5561057a565b01515f1960f88460031b161c191690555f8080610736565b92936020600181928786015181550195019301610720565b600d5f529091507fd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb5601f840160051c810191602085106107d8575b90601f859493920160051c01905b8181106107ca575061054f565b5f81558493506001016107bd565b90915081906107af565b634e487b7160e01b5f52602260045260245ffd5b91607f169161053b565b634e487b7160e01b5f52604160045260245ffd5b9093506020813d60201161084c575b8161083060209383610b0e565b810103126108485761084190610b92565b925f6104ac565b5f80fd5b3d9150610823565b89513d5f823e3d90fd5b93506020843d602011610894575b8161087960209383610b0e565b8101031261084857602061088d5f95610b92565b9450610468565b3d915061086c565b87513d5f823e3d90fd5b63f1634df960e01b5f5260045ffd5b6347bd7c1d60e01b5f5260045260245ffd5b90506020813d6020116108fa575b816108e260209383610b0e565b8101031261084857518015158103610848575f61024d565b3d91506108d5565b6040513d5f823e3d90fd5b6347bd7c1d60e01b5f525f60045260245ffd5b015190505f80610201565b60045f9081528281209350601f198516905b8181106109795750908460019594939210610961575b505050811b01600455610216565b01515f1960f88460031b161c191690555f8080610953565b9293602060018192878601518155019501930161093d565b60045f529091507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b601f840160051c810191602085106109f5575b90601f859493920160051c01905b8181106109e757506101eb565b5f81558493506001016109da565b90915081906109cc565b91607f16916101d7565b015190505f8061019f565b60035f9081528281209350601f198516905b818110610a625750908460019594939210610a4a575b505050811b016003556101b4565b01515f1960f88460031b161c191690555f8080610a3c565b92936020600181928786015181550195019301610a26565b60035f529091507fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b601f840160051c81019160208510610ade575b90601f859493920160051c01905b818110610ad05750610189565b5f8155849350600101610ac3565b9091508190610ab5565b91607f1691610175565b61014081019081106001600160401b0382111761080057604052565b601f909101601f19168101906001600160401b0382119082101761080057604052565b6001600160401b03811161080057601f01601f191660200190565b81601f8201121561084857805190610b6382610b31565b92610b716040519485610b0e565b8284526020838301011161084857815f9260208093018386015e8301015290565b51906001600160a01b038216820361084857565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b5f8091604051602081019063313ce56760e01b825260048152610bee602482610b0e565b51916001600160a01b03165afa3d15610c65573d90610c0c82610b31565b91610c1a6040519384610b0e565b82523d5f602084013e5b80610c59575b610c36575b505f905f90565b602081805181010312610848576020015160ff8111610c2f579060ff6001921690565b50602081511015610c2a565b606090610c2456fe60806040526004361015610011575f80fd5b5f3560e01c806301e1d1141461054a57806306fdde031461054557806307a2d13a146104e1578063095ea7b3146105405780630a28a4771461053b578063117d8ae014610536578063133ab5791461053157806318160ddd1461052c578063218e4a151461052757806323b872dd14610522578063240ecd601461051d57806324ea54f4146105185780632755cd2d14610513578063313ce5671461050e5780633152d5d114610509578063340505601461050457806338d52e0f146104ff5780633a7c9f0e146104fa5780633e314c76146104f55780633f4ba83a146104f0578063402d267d146104eb578063498e76a0146104e65780634cdad506146104e15780634daecb9c146104dc578063565974d3146104d75780635822198f146104d25780635b0f83f3146104cd5780635c975abb146104c85780635ed975e5146104c35780635f538f6f146104be57806361d027b3146104b957806366e943f1146104b4578063680e57ab146104af57806369b3054b146104aa5780636e553f65146104a557806370a08231146104a057806371aedbc11461049b57806379502c55146104965780637aaceb951461049157806383cf3d4a1461048c5780638456cb59146104875780639265b76e14610482578063934170521461047d57806394bf804d1461047857806394d7eaa41461047357806395d89b411461046e57806396c25a3814610469578063a039e94414610464578063a0506f0b1461045f578063a89f38a31461045a578063a9059cbb14610455578063b3d7f6b914610450578063b460af941461044b578063b637766c14610446578063ba08765214610441578063bef97c871461043c578063c0b534c214610437578063c37007c214610432578063c3f909d41461042d578063c63d75b614610428578063c6e6f592146103d3578063c8169aa114610423578063c9c667e31461041e578063ccc5749014610419578063ce96cb7714610414578063d206a0591461040f578063d45a07a11461040a578063d570ee4714610405578063d902d41a14610400578063d905777e146103fb578063dc9de0a8146103f6578063dd62ed3e146103f1578063e193858f146103ec578063e37d5b7f146103e7578063e7b20e5b146103e2578063ebc136d0146103dd578063ef2fc472146103d8578063ef8b30f7146103d3578063f3577816146103ce578063f3ba553e146103c9578063f7e533ec146103c4578063faa9bce9146103bf578063fcf2849f146103ba5763ff32a42a146103b5575f80fd5b6126ab565b6125a0565b61250f565b612485565b6123de565b6123c5565b611d15565b61239e565b6122df565b61223d565b61213a565b612092565b612040565b611fa5565b611f7e565b611ee3565b611ebb565b611e14565b611ded565b611dc6565b611d9f565b611d5b565b611d33565b611cee565b611c3c565b611b99565b611b5f565b611b3d565b611a5d565b6119b6565b6118c9565b6118ab565b611880565b611859565b61183c565b611823565b611772565b6116bd565b6116a0565b6114fb565b611465565b61143e565b611341565b611316565b6112ea565b61129a565b61127d565b611243565b611219565b6111b4565b611197565b611170565b6110fe565b6110e5565b6110ca565b6110a8565b611036565b610f7b565b610ec6565b610dbb565b6106b8565b610d9e565b610d77565b610c67565b610c40565b610c27565b610bba565b610b13565b610af6565b610aaa565b610a77565b610a50565b6109eb565b6109aa565b61098d565b610973565b610889565b6107e3565b6107a1565b6106f4565b6105c5565b61055d565b5f91031261055957565b5f80fd5b34610559575f36600319011261055957600854602090610585906001600160a01b0316613e6f565b604051908152f35b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9060206105c292818152019061058d565b90565b34610559575f366003190112610559576040515f6003548060011c90600181169081156106ae575b60208310821461069a578285526020850191908115610681575060011461062f575b61062b8461061f81860382610ea5565b604051918291826105b1565b0390f35b60035f9081529250907fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b81841061066d5750500161061f8261060f565b80548484015260209093019260010161065a565b60ff191682525090151560051b01905061061f8261060f565b634e487b7160e01b5f52602260045260245ffd5b91607f16916105ed565b34610559576020366003190112610559576020610585600435613f29565b6001600160a01b0381160361055957565b35906106f2826106d6565b565b3461055957604036600319011261055957600435610711816106d6565b602435331561078e576001600160a01b03821691821561077b576107418291335f52600160205260405f20612f7c565b5560405190815233907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a3602060405160018152f35b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b34610559576020366003190112610559576020610585600435613fa8565b6001600160a01b0316600452602490565b6001600160a01b03909116815260200190565b34610559575f36600319011261055957604051628bec5760e51b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91610855575b506040516001600160a01b039091168152602090f35b610877915060203d60201161087d575b61086f8183610ea5565b81019061270a565b5f61083f565b503d610865565b61271f565b3461055957602036600319011261055957600435301580156108cb575b6108b5576108b39061278e565b005b6363b52ed760e11b5f526108c8336107bf565b5ffd5b5061090160206108da30612ddb565b604051632474521560e21b8152600481019190915233602482015291829081906044820190565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91610944575b50156108a6565b610966915060203d60201161096c575b61095e8183610ea5565b81019061272a565b5f61093d565b503d610954565b34610559575f366003190112610559576020610585612810565b34610559575f366003190112610559576020601354604051908152f35b346105595760603660031901126105595760206109e16004356109cc816106d6565b6024356109d8816106d6565b60443591612843565b6040519015158152f35b34610559575f36600319011261055957610a036151da565b6040518091602082016020835281518091526020604084019201905f5b818110610a2e575050500390f35b82516001600160a01b0316845285945060209384019390920191600101610a20565b34610559575f3660031901126105595760206040515f516020615f585f395f51905f528152f35b34610559575f36600319011261055957610a8f613ffa565b6020610585610a9c612f91565b610aa4612810565b9061404e565b34610559575f3660031901126105595760ff7f00000000000000000000000000000000000000000000000000000000000000001660ff8111610af157602090604051908152f35b6127e1565b34610559575f366003190112610559576020601454604051908152f35b3461055957604036600319011261055957600435610b30816106d6565b60243530158015610b49575b6108b5576108b391612892565b50610b5860206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91610b9b575b5015610b3c565b610bb4915060203d60201161096c5761095e8183610ea5565b5f610b94565b34610559575f366003190112610559576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b60609060031901126105595760043590602435610c1a816106d6565b906044356105c2816106d6565b34610559576020610585610c3a36610bfe565b91612902565b34610559576020366003190112610559576020610585600435610c62816106d6565b612a90565b34610559575f36600319011261055957604051632474521560e21b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169060208180610cc03360048301612742565b0381855afa908115610884575f91610d58575b50159081610cfc575b50610ce9576108b3614545565b636b2a758d60e01b5f526108c8336107bf565b604051632474521560e21b8152915060209082908180610d1f3360048301612768565b03915afa908115610884575f91610d39575b50155f610cdc565b610d52915060203d60201161096c5761095e8183610ea5565b5f610d31565b610d71915060203d60201161096c5761095e8183610ea5565b5f610cd3565b34610559576020366003190112610559576020610585600435610d99816106d6565b612b1a565b34610559575f366003190112610559576020601154604051908152f35b346105595760203660031901126105595760043530158015610de5575b6108b5576108b390612bdf565b50610df460206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91610e37575b5015610dd8565b610e50915060203d60201161096c5761095e8183610ea5565b5f610e30565b634e487b7160e01b5f52604160045260245ffd5b60a081019081106001600160401b03821117610e8557604052565b610e56565b604081019081106001600160401b03821117610e8557604052565b90601f801991011681019081106001600160401b03821117610e8557604052565b34610559575f366003190112610559576040515f600d548060011c9060018116908115610f71575b60208310821461069a5782855260208501919081156106815750600114610f1f5761062b8461061f81860382610ea5565b600d5f9081529250907fd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb55b818410610f5d5750500161061f8261060f565b805484840152602090930192600101610f4a565b91607f1691610eee565b3461055957602036600319011261055957600435604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91611017575b5015611004576108b390612c18565b630ea7d7ed60e21b5f526108c8336107bf565b611030915060203d60201161096c5761095e8183610ea5565b5f610ff5565b34610559575f36600319011261055957604051635b0f83f360e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f9161085557506040516001600160a01b039091168152602090f35b34610559575f36600319011261055957602060ff600554166040519015158152f35b34610559575f36600319011261055957602060405160328152f35b346105595760206105856110f836610bfe565b91612ca3565b34610559575f366003190112610559576040516361d027b360e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f9161085557506040516001600160a01b039091168152602090f35b34610559575f3660031901126105595760206040515f516020615f185f395f51905f528152f35b34610559575f366003190112610559576020600654604051908152f35b34610559576040366003190112610559576004356003811015610559576020906024356111e0816106d6565b604051908382019260f81b835260018060601b03199060601b1660218201526015815261120e603582610ea5565b519020604051908152f35b3461055957604036600319011261055957602061058560243560043561123e826106d6565b612e43565b3461055957602036600319011261055957600435611260816106d6565b60018060a01b03165f525f602052602060405f2054604051908152f35b34610559575f366003190112610559576020601254604051908152f35b34610559575f36600319011261055957600854600954600a54600b54600c54604080516001600160a01b03968716815260208101959095528401929092526060830152909116608082015260a090f35b34610559575f366003190112610559576020611304612f91565b6040516001600160a01b039091168152f35b34610559576040366003190112610559576020610585600435611338816106d6565b60243590612ffa565b34610559575f36600319011261055957604051632474521560e21b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906020818061139a3360048301612742565b0381855afa908115610884575f9161141f575b501590816113c3575b50610ce9576108b3614b02565b604051632474521560e21b81529150602090829081806113e63360048301612768565b03915afa908115610884575f91611400575b50155f6113b6565b611419915060203d60201161096c5761095e8183610ea5565b5f6113f8565b611438915060203d60201161096c5761095e8183610ea5565b5f6113ad565b34610559576020366003190112610559576020610585600435611460816106d6565b613093565b34610559575f366003190112610559573015801561148a575b6108b5576108b361310e565b5061149960206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f916114dc575b501561147e565b6114f5915060203d60201161096c5761095e8183610ea5565b5f6114d5565b34610559576040366003190112610559576004602435813561151c826106d6565b6001611526614015565b5d611532610a9c612f91565b5060085460209061157290611566906115536001600160a01b0382166145b7565b5061155c613ffa565b6115663386614b47565b6001600160a01b031690565b6040516278744560e21b815294859182905afa908115610884576004935f9261167b575b50806115a46115ac92613f68565b8094336148bc565b6008546115cc9083906115c7906001600160a01b0316611566565b61494a565b6008546020906115e4906001600160a01b0316611566565b6040516278744560e21b815294859182905afa8015610884576116295f516020615eb85f395f51905f529161062b955f9161164c575b50604051918291339583612dca565b0390a2611634614326565b61163c613985565b6040519081529081906020820190565b61166e915060203d602011611674575b6116668183610ea5565b810190612a81565b5f61161a565b503d61165c565b6115ac9192506116999060203d602011611674576116668183610ea5565b9190611596565b34610559575f366003190112610559576020600754604051908152f35b34610559575f366003190112610559576040515f6004548060011c9060018116908115611768575b60208310821461069a57828552602085019190811561068157506001146117165761062b8461061f81860382610ea5565b60045f9081529250907f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b8184106117545750500161061f8261060f565b805484840152602090930192600101611741565b91607f16916116e5565b346105595760203660031901126105595760043561178f816106d6565b604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91611804575b5015611004576108b39061323b565b61181d915060203d60201161096c5761095e8183610ea5565b5f6117f5565b3461055957602061058561183636610bfe565b91613373565b34610559575f3660031901126105595760206040516202a3008152f35b34610559575f3660031901126105595760206040515f516020615ed85f395f51905f528152f35b346105595760403660031901126105595760206109e16004356118a2816106d6565b60243590613499565b34610559576020366003190112610559576020610585600435613f68565b346105595760046118d936610bfe565b9060016118e4614015565b5d6118f0610a9c612f91565b50600854926119076001600160a01b0385166145b7565b50611910613ffa565b928390602090611928906001600160a01b0316611566565b6040516278744560e21b815296879182905afa9081156108845761062b955f92611995575b505f191461197b575b831161196d5761196592612ca3565b611634614326565b61197692613373565b611965565b925061198f61198983612f63565b54613f29565b92611956565b6119af91925060203d602011611674576116668183610ea5565b905f61194d565b34610559576040366003190112610559576004356119d3816106d6565b602435301580156119ec575b6108b5576108b3916134d8565b506119fb60206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91611a3e575b50156119df565b611a57915060203d60201161096c5761095e8183610ea5565b5f611a37565b34610559576004611a6d36610bfe565b906001611a78614015565b5d611a84610a9c612f91565b5060085492611a9b6001600160a01b0385166145b7565b50611aa4613ffa565b928390602090611abc906001600160a01b0316611566565b6040516278744560e21b815296879182905afa9485156108845761062b95611aeb915f91611b1e575b50613fd1565b905f1914611b0c575b8311611b035761196592613c58565b61197692612902565b9250611b1782612f63565b5492611af4565b611b37915060203d602011611674576116668183610ea5565b5f611ae5565b34610559575f36600319011261055957602060ff601054166040519015158152f35b34610559575f3660031901126105595760206040517f025d8bbf3268be680d2605ebf6da15063b9915615bf1087dab336efc1bf970cb8152f35b34610559575f36600319011261055957604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91611c1d575b5015611004576108b361352b565b611c36915060203d60201161096c5761095e8183610ea5565b5f611c0f565b34610559575f366003190112610559575f6080604051611c5b81610e6a565b828152826020820152826040820152826060820152015261062b604051611c8181610e6a565b6008546001600160a01b039081168083526009546020808501918252600a546040808701918252600b546060808901918252600c5488166080998a0190815283519788529551948701949094529151908501525190830152519091169181019190915290819060a0820190565b34610559576020366003190112610559576020610585600435611d10816106d6565b613572565b34610559576020366003190112610559576020610585600435613fd1565b34610559575f366003190112610559576008546040516001600160a01b039091168152602090f35b34610559575f366003190112610559576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b34610559575f3660031901126105595760206040515f516020615ef85f395f51905f528152f35b34610559576020366003190112610559576020610585600435611de8816106d6565b61361f565b346105595760203660031901126105595760206109e1600435611e0f816106d6565b613650565b3461055957604036600319011261055957600435611e31816106d6565b60243530158015611e4a575b6108b5576108b39161367f565b50611e5960206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91611e9c575b5015611e3d565b611eb5915060203d60201161096c5761095e8183610ea5565b5f611e95565b34610559575f36600319011261055957600854602090610585906001600160a01b0316614bbc565b346105595760203660031901126105595760043530158015611f0d575b6108b5576108b3906136d2565b50611f1c60206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91611f5f575b5015611f00565b611f78915060203d60201161096c5761095e8183610ea5565b5f611f58565b34610559576020366003190112610559576020610585600435611fa0816106d6565b61370b565b346105595760203660031901126105595760043530158015611fcf575b6108b5576108b390613724565b50611fde60206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91612021575b5015611fc2565b61203a915060203d60201161096c5761095e8183610ea5565b5f61201a565b34610559576040366003190112610559576020612089600435612062816106d6565b6024359061206f826106d6565b6001600160a01b03165f9081526001845260409020612f7c565b54604051908152f35b3461055957602036600319011261055957600435604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f9161211b575b5015611004576108b390613798565b612134915060203d60201161096c5761095e8183610ea5565b5f61210c565b3461055957602036600319011261055957600435612157816106d6565b604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f916121cc575b5015611004576108b3906137ea565b6121e5915060203d60201161096c5761095e8183610ea5565b5f6121bd565b906020600319830112610559576004356001600160401b0381116105595782602382011215610559578060040135926001600160401b0384116105595760248460051b83010111610559576024019190565b346105595761224b366121eb565b604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f916122c0575b5015611004576108b39161395c565b6122d9915060203d60201161096c5761095e8183610ea5565b5f6122b1565b34610559576020366003190112610559576004356122fc816106d6565b604051632474521560e21b81525f516020615ed85f395f51905f5260048201526001600160a01b03918216602482015290602090829060449082907f0000000000000000000000000000000000000000000000000000000000000000165afa80156108845761062b915f9161237f575b5060405190151581529081906020820190565b612398915060203d60201161096c5761095e8183610ea5565b5f61236c565b346105595760203660031901126105595760206105856004356123c0816106d6565b613b80565b346105595760206105856123d836610bfe565b91613c58565b34610559576040366003190112610559576004356123fb816106d6565b60243530158015612414575b6108b5576108b391613d04565b5061242360206108da30612ddb565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91612466575b5015612407565b61247f915060203d60201161096c5761095e8183610ea5565b5f61245f565b34610559575f366003190112610559576020611304613d57565b604051906106f2604083610ea5565b6001600160401b038111610e8557601f01601f191660200190565b81601f82011215610559578035906124e0826124ae565b926124ee6040519485610ea5565b8284526020838301011161055957815f926020809301838601378301015290565b346105595760603660031901126105595760043560243561252f816106d6565b604435906001600160401b0382116105595761062b92602061255861163c9436906004016124c9565b604051918183925191829101835e81015f815203902060018060a01b0383167f38383a2eb7bd8ee888f12fb942a2e22e84f2d7240f1f8541ad4bbddace6e34425f80a3612e43565b34610559576125ae366121eb565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166125e660206108da30612e10565b0381855afa908115610884575f9161268c575b50159081612623575b50612610576108b391613da7565b6329068e8160e21b5f526108c8336107bf565b604051632474521560e21b81525f516020615f185f395f51905f5260048201523360248201529150602090829060449082905afa908115610884575f9161266d575b50155f612602565b612686915060203d60201161096c5761095e8183610ea5565b5f612665565b6126a5915060203d60201161096c5761095e8183610ea5565b5f6125f9565b3461055957602036600319011261055957600435600e5481101561270557600e5f527fbb7b4a454dc3493923482f07822329ed19e8244eff582cc204f8554c3620c3fd01546040516001600160a01b039091168152602090f35b61415b565b9081602091031261055957516105c2816106d6565b6040513d5f823e3d90fd5b90816020910312610559575180151581036105595790565b5f516020615f585f395f51905f5281526001600160a01b03909116602082015260400190565b5f516020615ef85f395f51905f5281526001600160a01b03909116602082015260400190565b612796613ffa565b603281116127cf576020817f4f4bedc5354096786a0fb857b12fdd6488cc973b2348cedb78088bdceaa906b592600b55604051908152a1565b631c94cf1160e11b5f5260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b9060018201809211610af157565b91908201809211610af157565b612818614015565b5c61283d576002546128318161282c612f91565b612ffa565b8101809111610af15790565b60025490565b919060ff60105416801561287e575b6128655763ec47ea8b60e01b5f5260045ffd5b612879926128748333836150b3565b615145565b600190565b50600c546001600160a01b03163314612852565b6001600160a01b0316906128a582615222565b156128ef576128b2613ffa565b813b15610559575f91602483926040519485938492638665120360e01b845260048401525af18015610884576128e55750565b5f6106f291610ea5565b50632767039f60e01b5f5260045260245ffd5b600161290c614015565b5d612918610a9c612f91565b5060085461292e906001600160a01b0316614191565b612936613ffa565b8015612a57576001600160a01b0383169133831415806129fd575b6129e95761295e8461370b565b8083116129d45750907f09fbb654e02253d6c37ecb473c5ed6f4557cac3fe5abc1d559523f6e257ee185916129a88261299681613f29565b80976129a182614364565b8433614452565b6129b15f601455565b6129c060405192839283612a66565b0390a26129cb614326565b906106f2613985565b632e52afbb60e21b5f526108c890838661434d565b630c849df760e41b5f526108c8843361320a565b50604051636eb1769f60e11b815260208180612a1d338960048401613221565b0381305afa80156108845783915f91612a38575b5010612951565b612a51915060203d602011611674576116668183610ea5565b5f612a31565b632334425960e21b5f5260045ffd5b6001600160a01b039091168152602081019190915260400190565b90816020910312610559575190565b6008546040516278744560e21b81529190602090839060049082906001600160a01b03165afa918215610884575f92612aec575b5060018060a01b03165f525f602052612ae060405f2054613f29565b90818082109118021890565b612b0691925060203d602011611674576116668183610ea5565b905f612ac4565b91908203918211610af157565b600854612b609190612b34906001600160a01b0316613e6f565b600a5480821115612bcd57505060205f915b604051809481926370a0823160e01b8352600483016107d0565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884576105c2925f92612bac575b50808218908211021890565b612bc691925060203d602011611674576116668183610ea5565b905f612ba0565b602091612bd991612b0d565b91612b46565b60207f3ba130ec8df44f0a71243af1b7f9f4239616bafda97ae766b3c40a9d202b21a491612c0b613ffa565b80600955604051908152a1565b612c20613ffa565b612c28612f91565b90612c31612810565b907f00000000000000000000000000000000000000000000000000000000000000008111612c9457612c866020927f186e864438b783eec69fd7ce4871c28accfc0b45558ea08c48540f76094fecde9461404e565b5080601155604051908152a1565b63ab9a408f60e01b5f5260045ffd5b90612cac613ffa565b6001612cb6614015565b5d612cc2610a9c612f91565b5060085492612cd96001600160a01b0385166145b7565b50612cf5611566612ce985613fa8565b95611566848888614746565b92604051916278744560e21b8352602083600481885afa9384156108845786935f95612da1575b50612d2b83612d31969761482b565b33614452565b600854600490602090612d4c906001600160a01b0316611566565b6040516278744560e21b815292839182905afa908115610884575f516020615eb85f395f51905f5291612d8e915f9161164c5750604051918291339583612dca565b0390a2612d99614326565b6105c2613985565b612d31955083612dc2612d2b9260203d602011611674576116668183610ea5565b965050612d1c565b908152602081019190915260400190565b6040515f6020820190815260609290921b6001600160601b031916602182015260158152612e0a603582610ea5565b51902090565b604051600160f81b6020820190815260609290921b6001600160601b031916602182015260158152612e0a603582610ea5565b906001612e4e614015565b5d612e5a610a9c612f91565b5060046020612e8c611566600854612e7960018060a01b0382166145b7565b50612e82613ffa565b6115663388614880565b6040516278744560e21b815292839182905afa9081156108845783905f92612f3c575b50612eca612edf9293612ec183613fd1565b958691336148bc565b6008546115c7906001600160a01b0316611566565b600854600490602090612efa906001600160a01b0316611566565b6040516278744560e21b815292839182905afa908115610884575f516020615eb85f395f51905f52916129c0915f9161164c5750604051918291339583612dca565b612edf9250612f5c612eca9160203d602011611674576116668183610ea5565b9250612eaf565b6001600160a01b03165f90815260208190526040902090565b9060018060a01b03165f5260205260405f2090565b604051637aaceb9560e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91612fe1575090565b6105c2915060203d60201161087d5761086f8183610ea5565b61300660125442612b0d565b90811561308c57601154613021670de0b6b3a7640000614a93565b1461308c57602061304691604051809381926370a0823160e01b8352600483016107d0565b0381305afa8015610884576105c293613066925f9261306b575b50612b0d565b614ad7565b61308591925060203d602011611674576116668183610ea5565b905f613060565b5050505f90565b6008546040516278744560e21b815290602090829060049082906001600160a01b03165afa8015610884576130cf915f916130ef575b50613fa8565b9060018060a01b03165f525f60205260405f205490818082109118021890565b613108915060203d602011611674576116668183610ea5565b5f6130c9565b613116613ffa565b613124611566611566613d57565b604051630f07f82960e01b8152906020908290815f81613171307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031660048401613221565b03925af18015610884576131a9915f916131eb575b50600c80546001600160a01b0319166001600160a01b0392909216919091179055565b600c546040517f8f407169a2fff9de40408b8d482b293eff9e2dbc448da0593fa9a39d428a41049181906131e6906001600160a01b0316826107d0565b0390a1565b613204915060203d60201161087d5761086f8183610ea5565b5f613186565b6001600160a01b0390811660045216602452604490565b6001600160a01b0391821681529116602082015260400190565b613243613ffa565b6001600160a01b0381165f818152600f6020526040902054909190156128ef5761326c816154d0565b6132866132816001600160a01b038316611566565b61598a565b50813b156105595760405163ebf3113160e01b81525f8160048183875af180156108845761335f575b507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316803b156105595760405163d55dd62b60e01b8152600260048201526001600160a01b039290921660248301525f908290604490829084905af1801561088457613345575b507f66d72a91b52f63fb063c4f672763d7ef15ce4d7c9a268a7f9b5133e41c1709a55f80a2565b806133535f61335993610ea5565b8061054f565b5f61331e565b806133535f61336d93610ea5565b5f6132af565b9190916001613380614015565b5d61338c610a9c612f91565b506008546133a2906001600160a01b0316614191565b6133aa613ffa565b6133b381613fa8565b928315612a57576001600160a01b03831692338414158061343f575b61342b576133dc8161361f565b8084116134165750906129a8858480946129a17fd4383faec5079b2ec7ac0ff240326baa0d584b03d51b9742f7c1a034f6fc015b97614364565b633fa733bb60e21b5f526108c891849061434d565b638b27f8ed60e01b5f526108c8903361320a565b50604051636eb1769f60e11b81526020818061345f338660048401613221565b0381305afa80156108845786915f9161347a575b50106133cf565b613493915060203d602011611674576116668183610ea5565b5f613473565b9060ff6010541680156134c4575b6134ba5763ec47ea8b60e01b5f5260045ffd5b6128799133615145565b50600c546001600160a01b031633146134a7565b6001600160a01b0316906134eb82615222565b156128ef576134f8613ffa565b813b15610559575f916024839260405194859384926361f5cd8b60e01b845260048401525af18015610884576128e55750565b613533613ffa565b60105460ff8116156135425750565b60ff19166001176010557feadb24812ab3c9a55c774958184293ebdb6c7f6a2dbab11f397d80c86feb65d35f80a1565b600854613587906001600160a01b0316613e6f565b600a54908181111561360a5750506135b760205f925b604051809381926370a0823160e01b8352600483016107d0565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa8015610884576105c292613605925f92612bac5750808218908211021890565b613fd1565b6136196020916135b793612b0d565b9261359d565b600854613634906001600160a01b0316614bbc565b9060018060a01b03165f525f602052612ae060405f2054613f29565b6001600160a01b031661366281615222565b90811561366d575090565b6008546001600160a01b031614919050565b6001600160a01b03169061369282615222565b156128ef5761369f613ffa565b813b15610559575f9160248392604051948593849263497af41960e11b845260048401525af18015610884576128e55750565b60207f4faeac5aec9fa2e6f82ae7ccfef27a03ca3ff9d8c5356fea9acb2caad1c4c344916136fe613ffa565b80600a55604051908152a1565b6008546130cf90613605906001600160a01b0316614bbc565b61372c613ffa565b603c81106137895762015180811161377a577f5953b565c074c2cce1866b4e69c9efc4908556bb6fca70f735907c94d94055158160135461377260405192839283612dca565b0390a1601355565b637092ddf560e01b5f5260045ffd5b63d93a8d8760e01b5f5260045ffd5b6137a0613ffa565b6202a30081106137db576020817f3cf175d91d8c5823f3729423b5a64130e40d4b09e88c6dc1925a260f26818c2592600655604051908152a1565b63f710d83560e01b5f5260045ffd5b6137f2613ffa565b6001600160a01b03811690811561394d5761380c81613650565b61393a576040516338d52e0f60e01b8152602081600481865afa908115610884575f9161391b575b506040516338d52e0f60e01b8152602081600481305afa908115610884575f916138fc575b506001600160a01b039081169116036138ed57813b1561055957604051634545ccbb60e11b81525f8160048183875af18015610884576138b2926138ad92611566926138d9575b506001600160a01b031690565b615a2b565b507fcb4a29d359e86f179111dcba8714def1a859612f729f2d224d13efeac51b36bc5f80a2565b806133535f6138e793610ea5565b5f6138a0565b631692ea4f60e31b5f5260045ffd5b613915915060203d60201161087d5761086f8183610ea5565b5f613859565b613934915060203d60201161087d5761086f8183610ea5565b5f613834565b637eadea0960e11b5f526108c8906107bf565b63210e96cb60e01b5f5260045ffd5b9061398591600161396b614015565b5d613977610a9c612f91565b50613980613ffa565b613991565b5f61398e614015565b5d565b9190600b548111613b6e578015613b5f576008546139b7906001600160a01b0316611566565b926040516278744560e21b8152602081600481885afa908115610884575f91613b40575b506001600160a01b03909416935f90815b848110613a2257506106f29495505f8212613a09575b5050614e0b565b613a15613a1b92614cc9565b90615595565b5f80613a02565b86613a3c6115666020613a36858a8a614c6a565b01614c8c565b148015613b27575b613a51575b6001016139ec565b9186613a666115666020613a36878a8a614c6a565b14906040613a75858888614c6a565b01355f198114613aa9575b60019215613a9a57613a9191614cae565b925b9050613a49565b613aa391614c96565b92613a93565b508115613b18576004916020613ace611566611566613ac9898c8c614c6a565b614c8c565b6040516278744560e21b815294859182905afa8015610884576001935f91613afa575b50909250613a80565b613b12915060203d8111611674576116668183610ea5565b5f613af1565b63055bb2a160e41b5f5260045ffd5b5086613b3a611566613ac9848989614c6a565b14613a44565b613b59915060203d602011611674576116668183610ea5565b5f6139db565b6304dcdcd560e31b5f5260045ffd5b63899a5d8160e01b5f5260045260245ffd5b6040516278744560e21b815290602082600481305afa918215610884575f92613c37575b50604051635ee6ec4160e11b8152916001600160a01b039190911690602083600481855afa92831561088457600493602092613be7925f92613c18575b50614ef4565b916040519384809263dbd5edc760e01b82525afa908115610884576105c2925f92612bac5750808218908211021890565b613c30919250843d8611611674576116668183610ea5565b905f613be1565b613c5191925060203d602011611674576116668183610ea5565b905f613ba4565b916001613c63614015565b5d613c6f610a9c612f91565b50600854613ca09061156690613c8d6001600160a01b0382166145b7565b50613c96613ffa565b6115668487614f08565b6040516278744560e21b81529390602085600481845afa92831561088457612d2b955f94613ce1575b50612edf9394613cd884613f29565b9687809461482b565b612edf9450613cfe9060203d602011611674576116668183610ea5565b93613cc9565b6001600160a01b031690613d1782615222565b156128ef57613d24613ffa565b813b15610559575f91602483926040519485938492634fc7fac360e01b845260048401525af18015610884576128e55750565b604051633df94cfb60e21b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115610884575f91612fe1575090565b91906014549283420393428511610af157601354809510613dd7575061398592935042601455600161396b614015565b8490630924dbf160e21b5f526004526024524260445260645ffd5b604051602081017fa44c7cc604645fc9d906e0a5aeb821ecf76e473a1a4d03393ebd52161430e41a815260208252613e2b604083610ea5565b9051902060ff191690565b604051602081017fa9898051640582db44f19359a5df62a03dbff55353a9f388ea332d75dfa80fa0815260208252613e2b604083610ea5565b613e77613df2565b5c613f1c57613e8d90613e886151da565b614fbd565b5f9190825b8151841015613f175760046020613ec26001600160a01b03613eb4888761416f565b51166001600160a01b031690565b6040516278744560e21b815292839182905afa801561088457600192613eef925f92613ef7575b50612803565b930192613e92565b613f1091925060203d8111611674576116668183610ea5565b905f613ee9565b925050565b50613f25613e36565b5c90565b600854613f3e906001600160a01b0316613e6f565b9060018201809211610af157613f52612810565b60018101809111610af1576105c2925f92615055565b600854613f7d906001600160a01b0316613e6f565b9060018201809211610af157613f91612810565b60018101809111610af1576105c292600192615055565b613fb0612810565b9060018201809211610af157600854613f91906001600160a01b0316613e6f565b613fd9612810565b9060018201809211610af157600854613f52906001600160a01b0316613e6f565b60ff6005541661400657565b63d93c066560e01b5f5260045ffd5b604051602081017f4e71cabede5261c2c661c1a41d0d13331711e62f0548c4fdf8ade97c9c524d41815260208252613e2b604083610ea5565b9190601154156140a6576140629083612ffa565b91828061406d575050565b61407a9142601255615482565b7f698f29fe990d4e7770f7e74cd309da261dd03ca828f7bb3c2ea8b8c9adcc0ecd6020604051848152a1565b50426012555f9150565b604051602081017f98932279f8646d348f86cf154406d1fab3c6a0c52686d604c7d4a6a140038108815260208252613e2b604083610ea5565b6001600160401b038111610e855760051b60200190565b9061410a826140e9565b6141176040519182610ea5565b8281528092614128601f19916140e9565b01905f5b82811061413857505050565b60209060405161414781610e8a565b5f81525f838201528282850101520161412c565b634e487b7160e01b5f52603260045260245ffd5b80518210156127055760209160051b010190565b5f198114610af15760010190565b6141996140b0565b5c6142b1576141a7906145b7565b6141b18151614100565b905f915f905f5b835181101561429157600460206141e66115666115666141d8868a61416f565b51516001600160a01b031690565b60405163d570ee4760e01b815292839182905afa908115610884575f91614273575b5080614218575b506001016141b8565b61426661426c918395976142316141d86001968a61416f565b61424b61423c61249f565b6001600160a01b039092168252565b82602082015261425b8a8861416f565b52613ee9898761416f565b95614183565b929061420f565b61428b915060203d8111611674576116668183610ea5565b5f614208565b5091506106f2926142a3918352615233565b6142ac81615246565b615348565b50565b604051602081017f410d83ac3c7a0c2a0669e43e3a5ca6694ee49455f748efa9954a95c3752e9fc8815260208252613e2b604083610ea5565b604051602081017f2e756c3932ba771b80f1bae53d1177d9f7a4ced0ce66d74053b09f874cec6ffe815260208252613e2b604083610ea5565b5f61432f613df2565b5d5f6143396140b0565b5d5f6143436142b4565b5d5f61398e6142ed565b6001600160a01b0316600452602452604452606490565b61436c6142b4565b5c61437681614100565b905f5b8181106143f9575050905f5b82518110156143f457602061439a828561416f565b5101518281106143ba57506141d86143b5916106f29461416f565b61482b565b809392936143cf575b50600101919091614385565b8082946143e86143ed936143b56141d86001978961416f565b612b0d565b92906143c3565b505050565b8061440d60019261440861530f565b6158ba565b5c61441a826144086152d6565b5c6040519161442883610e8a565b848060a01b031682526020820152614440828661416f565b5261444b818561416f565b5001614379565b6001600160a01b03808416959082169392909182878603614534575b50508515614521576144a1827ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db946157ce565b60405163a9059cbb60e01b6020820152614504906144d5816144c7898660248401612a66565b03601f198101835282610ea5565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166158da565b61451c60405192839260018060a01b03169683612dca565b0390a4565b634b637e8f60e11b5f525f60045260245ffd5b61453e91856150b3565b5f8261446e565b6007546006548101809111610af15742106145a85760055460ff8116156145995760ff19166005557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1565b638dfc202b60e01b5f5260045ffd5b6304a59e3b60e01b5f5260045ffd5b6145bf613df2565b5c61473d576145cc6151da565b6145de6145d982516127f5565b614100565b925f90815b83518310156146935760046020614610611566611566614603888a61416f565b516001600160a01b031690565b6040516278744560e21b815292839182905afa80156108845760019261466b925f92614673575b50614645614603878961416f565b61465061423c61249f565b826020820152614660878b61416f565b52613ee9868a61416f565b9201916145e3565b61468c91925060203d8111611674576116668183610ea5565b905f614637565b6040516278744560e21b815291949192506001600160a01b0390911690602083600481855afa9182156108845761470d94614708945f94614716575b5090613ee9916146ef6146e061249f565b6001600160a01b039093168352565b8460208301525190614701828a61416f565b528761416f565b615452565b6106f282615465565b613ee9929194506147359060203d602011611674576116668183610ea5565b9390916146cf565b506105c26153dd565b908015612a5757336001600160a01b038416141590816147a4575b506147905761476f82612a90565b9182821161477c57505050565b633fa733bb60e21b5f526108c8935061434d565b638b27f8ed60e01b5f526108c8823361320a565b604051636eb1769f60e11b8152909150602081806147c6338860048401613221565b0381305afa908115610884575f916147e1575b50105f614761565b6147fa915060203d602011611674576116668183610ea5565b5f6147d9565b6040519061480f602083610ea5565b5f8252565b6040906105c293928152816020820152019061058d565b60018060a01b031690604051614842602082610ea5565b5f8152823b156105595761486f925f9283604051809681958294630278811f60e31b845260048401614814565b03925af18015610884576128e55750565b8015612a575761488f82612b1a565b9182821161489c57505050565b633c8097d960e11b5f5260018060a01b031660045260245260445260645ffd5b6040516323b872dd60e01b60208201526001600160a01b03909116602482018190523060448301526064808301859052825292937fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7929091614923906144d5608482610ea5565b61492d8282615482565b61494560405192839260018060a01b03169683612dca565b0390a3565b60405163095ea7b360e01b60208083019182527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031692915f906149ab8461499d898960248401612a66565b03601f198101865285610ea5565b83519082865af15f51903d81614a70575b501590505b614a23575b50506001600160a01b0316906149da614800565b823b1561055957614a04925f9283604051809681958294632db6d39960e01b845260048401614814565b03925af1801561088457614a155750565b806133535f6106f293610ea5565b60405163095ea7b360e01b60208201526001600160a01b03841660248201525f6044820152614a699290614a6490614a5e81606481016144c7565b826158da565b6158da565b5f806149c6565b15159050614a8757506149c1823b15155b5f6149bc565b60016149c19114614a81565b905f911560011715610af157565b81810292918115918404141715610af157565b634e487b7160e01b5f52601260045260245ffd5b8115614ad2570490565b614ab4565b614afe906301e13380614af768056bc75e2d631000009460115490614aa1565b0490614aa1565b0490565b614b0a613ffa565b600160ff1960055416176005557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a142600755565b8015612a5757614b5682613572565b91828211614b6357505050565b63284ff66760e01b5f5260018060a01b031660045260245260445260645ffd5b604051602081017f3d5fcbe10cf86b117683d0d4967b64a0c0fa4bdda7d07499d3c9dc5e388b6940815260208252613e2b604083610ea5565b905f91614bc76140b0565b5c614c5f57614bd890613e886151da565b5f5b8151811015614c5b5760046020614bf7611566614603858761416f565b60405163d570ee4760e01b815292839182905afa908115610884575f91614c3d575b5080614c29575b50600101614bda565b614c369060019295612803565b9390614c20565b614c55915060203d8111611674576116668183610ea5565b5f614c19565b5050565b509050613f25614b83565b91908110156127055760051b81013590609e1981360301821215610559570190565b356105c2816106d6565b81810392915f138015828513169184121617610af157565b9190915f8382019384129112908015821691151617610af157565b600160ff1b8114610af1575f0390565b9035601e19823603018112156105595701602081359101916001600160401b03821161055957813603831361055957565b908060209392818452848401375f828201840152601f01601f1916010190565b82602082016020835252604081019260408160051b83010193835f91609e1982360301945b848410614d60575050505050505090565b90919293949596603f19828203018352873587811215610559576020614dfa60019387839401908135614d92816106d6565b868060a01b0316815283820135614da8816106d6565b868060a01b03168482015260408201356040820152614dec614de1614dd06060850185614cd9565b60a0606086015260a0850191614d0a565b926080810190614cd9565b916080818503910152614d0a565b990193019401929195949390614d4f565b905f5b818110614e4e5750614e497f507d790d4c0157977bb25bd8941f5f91c3118eab68b257c1d1c0825cb0051fd991604051918291339583614d2a565b0390a2565b614e59818385614c6a565b9060a0823603126105595760405191614e7183610e6a565b8035614e7c816106d6565b8352614e8a602082016106e7565b60208401526040810135604084015260608101356001600160401b03811161055957614eb990369083016124c9565b60608401526080810135926001600160401b03841161055957614ee4614eee926001953691016124c9565b60808201526155cf565b01614e0e565b68056bc75e2d6310000091614afe91614aa1565b8015612a5757336001600160a01b038316141580614f63575b614f4f57614f2e82613093565b91828211614f3b57505050565b632e52afbb60e21b5f526108c8935061434d565b630c849df760e41b5f526108c8823361320a565b50604051636eb1769f60e11b815260208180614f83338760048401613221565b0381305afa80156108845782915f91614f9e575b5010614f21565b614fb7915060203d602011611674576116668183610ea5565b5f614f97565b9182519060018201809211610af157614fd5826140e9565b91614fe36040519384610ea5565b808352614ff2601f19916140e9565b013660208401375f5b8451811015615035576001906001600160a01b03615019828861416f565b5116615025828661416f565b90838060a01b0316905201614ffb565b509261504590929192518361416f565b6001600160a01b03909116905290565b9190615062828285615743565b93600481101561509f57600180911614928361508a575b50505015158101809111610af15790565b909180935015614ad2570915155f8080615079565b634e487b7160e01b5f52602160045260245ffd5b6001600160a01b03165f818152600160205260409020919290916150d8908490612f7c565b545f1981106150e8575b50505050565b81811061512457821561078e576001600160a01b0384161561077b5761511a925f526001602052039160405f20612f7c565b555f8080806150e2565b83637dc7a0d960e11b5f5260018060a01b031660045260245260445260645ffd5b916001600160a01b038316918215614521576001600160a01b0381169384156151c75761517181612f63565b548381106151b1579161519f91615199855f516020615f385f395f51905f5296950391612f63565b55612f63565b805482019055604051908152602090a3565b63391434e360e21b5f526108c89184919061434d565b63ec442f0560e01b5f525f60045260245ffd5b60405190600e548083528260208101600e5f5260205f20925f5b8181106152095750506106f292500383610ea5565b84548352600194850194879450602090930192016151f4565b5f52600f60205260405f2054151590565b61523b614b83565b5d600161398e6140b0565b905f905b82518210156152d15760018201808311610af1575b83518110156152c6576001906020615277858761416f565b5101516020615286838861416f565b51015110615295575b0161525f565b61529f818661416f565b516152aa858761416f565b516152b5838861416f565b526152c0858761416f565b5261528f565b50906001019061524a565b915050565b604051602081017f8f2b8f2fcb6f2e256bfd8c09fcca564574482705250cb5c8dbe56c4f4fce37c8815260208252613e2b604083610ea5565b604051602081017f05abb041f8dc8945baa4f2792e2109e9d9e22dea3aa665ccf2f030209c7415ad815260208252613e2b604083610ea5565b6106f2906153546152d6565b61535c61530f565b906153656142b4565b92615861565b604051602081017fb4b00da68d43fac77a22bb187c63cb88989e294cfebeb79b3789ae1629639d98815260208252613e2b604083610ea5565b604051602081017f5720a3c83eb8242bbe1a4159c3b45ed663cd9e207a02bdea64844c6c583da9dd815260208252613e2b604083610ea5565b6153e56142ed565b5c906153f082614100565b915f5b8181106153fe575050565b8061540d60019261440861536b565b5c61541a826144086153a4565b5c6040519161542883610e8a565b848060a01b031682526020820152615440828761416f565b5261544b818661416f565b50016153f3565b61545a613e36565b5d600161398e613df2565b6106f2906154716153a4565b61547961536b565b906153656142ed565b6001600160a01b038116919082156151c75760025490828201809211610af1575f926154c16020925f516020615f385f395f51905f5294600255612f63565b818154019055604051908152a3565b60405163dbd5edc760e01b81526001600160a01b03821690602081600481855afa908115610884575f91615576575b50615563576020600491604051928380926278744560e21b82525afa908115610884575f91615544575b506155315750565b63ca4a18b360e01b5f526108c8906107bf565b61555d915060203d602011611674576116668183610ea5565b5f615529565b632a4d8fbb60e01b5f526108c8826107bf565b61558f915060203d602011611674576116668183610ea5565b5f6154ff565b90600954808311156155c0578203918211610af157116155b157565b633b5391f960e01b5f5260045ffd5b63ff105df960e01b5f5260045ffd5b6020810180519192916155ea906001600160a01b0316611566565b8351909390615601906001600160a01b0316611566565b9160408201515f1981145f1461572357506040516278744560e21b81526020816004816001600160a01b0388165afa801561088457615668915f91615704575b5080925b8451615662906001600160a01b031691516001600160a01b031690565b90615a94565b61567185613b80565b6040516278744560e21b81526001600160a01b03909616956020816004818a5afa801561088457836156ab9184935f916156e55750612803565b116156d15750606082015160809092015193946106f294936001600160a01b0316615bea565b6316e05b4760e21b5f526108c8918661434d565b6156fe915060203d602011611674576116668183610ea5565b5f613ee9565b61571d915060203d602011611674576116668183610ea5565b5f615641565b615668908092615645565b8054821015612705575f5260205f2001905f90565b9161574e8284615c77565b92909384156157c157848311156157b45790829109815f0382168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b6011600384150218615c8a565b5050906105c29250614ac8565b6001600160a01b038116919082615818575090600254828101809111610af1575f925f516020615f385f395f51905f52916002555b600280548290039055604051908152602090a3565b61582181612f63565b5482811061584d57915f516020615f385f395f51905f5291615847825f96950391612f63565b55615803565b63391434e360e21b5f526108c8929161434d565b91935f5b83518110156158b1578061587b600192856158ba565b6020615887838861416f565b510151905d61589681886158ba565b828060a01b036158a6838861416f565b515116905d01615865565b5093505051905d565b906040519060208201928352604082015260408152612e0a606082610ea5565b905f602091828151910182855af11561271f575f513d61592957506001600160a01b0381163b155b6159095750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415615902565b9161594b9183549060031b91821b915f19901b19161790565b9055565b80548015615976575f190190615965828261572e565b8154905f199060031b1b1916905555565b634e487b7160e01b5f52603160045260245ffd5b5f818152600f6020526040902054908115615a25575f19820190828211610af157600e545f19810193908411610af15783835f956159e495036159ea575b5050506159d5600e61594f565b600f905f5260205260405f2090565b55600190565b6159d5615a1691615a0c615a02615a1c95600e61572e565b90549060031b1c90565b928391600e61572e565b90615932565b555f80806159c8565b50505f90565b5f818152600f6020526040902054615a8f57600e54600160401b811015610e8557615a78615a62826001859401600e55600e61572e565b819391549060031b91821b915f19901b19161790565b9055600e54905f52600f60205260405f2055600190565b505f90565b90918015615bd7576001600160a01b0383168015615bc4576001600160a01b03831615615bb157615acb615ac785613650565b1590565b615b9e57615adb615ac784613650565b615b8b5760206004916040519283809263dbd5edc760e01b82525afa908115610884575f91615b6c575b5015615b5957615b16908383615d7e565b9190949293828211615b4557505050828211615b3157505050565b63016b606760e21b5f526108c8935061434d565b637d7bf8e160e01b5f526108c8935061434d565b630b9cb3f960e11b5f526108c8836107bf565b615b85915060203d602011611674576116668183610ea5565b5f615b05565b63c80e655f60e01b5f526108c8836107bf565b63c80e655f60e01b5f526108c8846107bf565b632767039f60e01b5f526108c8836107bf565b632767039f60e01b5f526108c8846107bf565b630a16952b60e21b5f526108c8836107bf565b9192916001600160a01b031690813b15610559575f8094615c51615c3f976040519889978896879563c38a6f0b60e01b8752600487015260018060a01b0316602486015260806044860152608485019061058d565b8381036003190160648501529061058d565b03925af1801561088457615c625750565b80615c6e5f8093610ea5565b80031261055957565b905f198183099102908180821091030391565b634e487b715f526020526024601cfd5b604051602081017fd6ca653d633b7805e7a09d886857226f949d3ea7294700814274fe35008a00e0815260208252613e2b604083610ea5565b604051602081017f546815194d984b29286d5b6f432093bc0b41f225a5a8e27984a1c97f6c2c975e815260208252613e2b604083610ea5565b604051602081017fd06b3f94ec7e002c6893cd0c8991bb46b1dd8a8de8b084874f6c9702acf78346815260208252613e2b604083610ea5565b604051602081017f880bdf4b1569fe9025df88e4aa4034209a7b27fcb16c5e9fc1f6231643aa93e4815260208252613e2b604083610ea5565b9290615d9e615d8b615c9a565b6001600160a01b039092169182906158ba565b91615dbd615daa615cd3565b6001600160a01b039096169586906158ba565b92615dca83614408615d0c565b93615dd787614408615d45565b855c95815c958715615e63575b50508415615e0f575b50615e089650615dfe86835c612803565b968796825c612803565b9586925d5d565b93506020600497604051988980926318ca2a4f60e11b82525afa801561088457615e08975f91615e44575b5080945d5f615ded565b615e5d915060203d602011611674576116668183610ea5565b5f615e3a565b60405163ad5a356f60e01b8152919750602090829060049082905afa908115610884575f91615e98575b5080965d5f80615de4565b615eb1915060203d602011611674576116668183610ea5565b5f615e8d56fee68a55afda2dca8343871fe0e5575a383291a40ae7d53e4dee12faf79cde144eb00be3d6a5434b97b328543d1486d56adcb7e74080170d1cdd7e0306c3d9ba3d7935bd0ae54bc31f548c14dba4d37c5c64b3f8ca900cb468fb8abd54d5894f550d186688925976bbe6755ae984501c8e3e2b103a7af59fd803ab9c6d891ae7e0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041a2646970667358221220ffe78f20c50967397587665653faf23d405ed3baa128f0956bc473b97bf57edd64736f6c634300081c003360c08060405234610635576128db803803809161001c828561067b565b833981016040828203126106355781516001600160401b0381116106355782016101408183031261063557604051916100548361065f565b81516001600160401b038111610635578161007091840161069e565b83526020820151906001600160401b0382116106355761009191830161069e565b90602083019182526100a5604082016106f3565b918260408501526100b8606083016106f3565b938460608201526100cb608084016106f3565b936080820194855260a08401519460a0830195865260c08501519060c0840191825260e08601519260e08501938452610129602061012061010f6101008b01610707565b9961010089019a8b5201519b61012088019c8d52016106f3565b986001600160a01b039081169116801561064c576040516301ffc9a760e01b815263261c910560e21b6004820152602081602481855afa908115610641575f91610603575b50156105f15760805280156105e25760a05280516001600160a01b0316156105d357835151156105c4576001600160a01b036101a8610714565b16156105b55768056bc75e2d631000008951116105a657516001600160a01b03166101d1610714565b9651915192519351945195511515985196610120604051916101f28361065f565b5f8084526001600160a01b03919091166020840181905260408401859052606084018690526080840187905260a0840188905260c0840189905260e08401998a5261010084019c8d529190920198895281546001600160a01b031990811690925560018054831690911790556002805490911690911790556003556004556005558051906001600160401b0382116104a95760065490600182811c9216801561059c575b602083101461048b5781601f84931161052e575b50602090601f83116001146104c8575f926104bd575b50508160011b915f199060031b1c1916176006555b5180519093906001600160401b0381116104a957600754600181811c9116801561049f575b602082101461048b57601f8111610428575b50602094601f82116001146103c5579481929394955f926103ba575b50508160011b915f199060031b1c1916176007555b51151560ff8019600854169116176008555160095560018060a01b031660018060a01b03195f5416175f556040516121599081610782823960805181818161032d01528181610a8c0152611935015260a0518181816101e1015281816105f901528181610bd90152818161143c015281816114ae0152611e3e0152f35b015190505f80610328565b601f1982169560075f52805f20915f5b888110610410575083600195969798106103f8575b505050811b0160075561033d565b01515f1960f88460031b161c191690555f80806103ea565b919260206001819286850151815501940192016103d5565b60075f527fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688601f830160051c81019160208410610481575b601f0160051c01905b818110610476575061030c565b5f8155600101610469565b9091508190610460565b634e487b7160e01b5f52602260045260245ffd5b90607f16906102fa565b634e487b7160e01b5f52604160045260245ffd5b015190505f806102c0565b60065f9081528281209350601f198516905b81811061051657509084600195949392106104fe575b505050811b016006556102d5565b01515f1960f88460031b161c191690555f80806104f0565b929360206001819287860151815501950193016104da565b60065f529091507ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f601f840160051c81019160208510610592575b90601f859493920160051c01905b81811061058457506102aa565b5f8155849350600101610577565b9091508190610569565b91607f1691610296565b634ef9dfe360e01b5f5260045ffd5b633a4f9cdb60e21b5f5260045ffd5b63268c072960e01b5f5260045ffd5b637ff57ef160e11b5f5260045ffd5b63f1634df960e01b5f5260045ffd5b6347bd7c1d60e01b5f5260045260245ffd5b90506020813d602011610639575b8161061e6020938361067b565b810103126106355761062f90610707565b5f61016e565b5f80fd5b3d9150610611565b6040513d5f823e3d90fd5b6347bd7c1d60e01b5f525f60045260245ffd5b61014081019081106001600160401b038211176104a957604052565b601f909101601f19168101906001600160401b038211908210176104a957604052565b81601f82011215610635578051906001600160401b0382116104a957604051926106d2601f8401601f19166020018561067b565b8284526020838301011161063557815f9260208093018386015e8301015290565b51906001600160a01b038216820361063557565b5190811515820361063557565b60a051604051628bec5760e51b815290602090829060049082906001600160a01b03165afa908115610641575f9161074a575090565b90506020813d602011610779575b816107656020938361067b565b8101031261063557610776906106f3565b90565b3d915061075856fe60806040526004361015610011575f80fd5b5f5f3560e01c806301e1d11414611ac757806306fdde0314611aac5780630af02e50146118f2578063117d8ae0146118c557806313c408f81461183f57806324ea54f4146118045780632db6d39914611637578063303dbaf3146116145780633194549e146115f657806337270936146115cf57806338d52e0f146115a65780634fc7fac31461152e578063565974d3146114fa5780635b0f83f31461148857806361d027b31461141657806361f5cd8b146113bd57806366e943f11461139557806369b3054b14611331578063780469bb14610cd657806379502c5514610c255780637aaceb9514610bb35780638665120314610b5a5780638a8b997614610a1457806392f5e832146109a8578063a89f38a314610980578063ad5a356f14610962578063bdcdd88214610944578063c0b534c214610909578063c38a6f0b146107a2578063c3f909d414610628578063c9c667e3146105e3578063ccc57490146105a8578063ce5c7f61146103d8578063d570ee47146103b5578063dbd5edc714610397578063ebc136d0146102d6578063ebf31131146102695763f7e533ec146101bc575f80fd5b34610266578060031936011261026657604051633df94cfb60e21b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561025b576020929161022e575b506040516001600160a01b039091168152f35b61024e9150823d8411610254575b6102468183611bc1565b810190611e0b565b5f61021b565b503d61023c565b6040513d84823e3d90fd5b80fd5b503461026657806003193601126102665780546001600160a01b03811633036102c7576001600160a01b03191681556040513381527f7cb941d7b1708e5b3bcd35ca960d6c6311188cec18886e5b67630552676b048790602090a180f35b63430da47160e01b8252600482fd5b5034610266576020366003190112610266576102f0611b05565b604051632474521560e21b81525f5160206120c45f395f51905f5260048201526001600160a01b03918216602482015290602090829060449082907f0000000000000000000000000000000000000000000000000000000000000000165afa90811561025b576020929161036a575b506040519015158152f35b61038a9150823d8411610390575b6103828183611bc1565b810190611df3565b5f61035f565b503d610378565b50346102665780600319360112610266576020600354604051908152f35b503461026657806003193601126102665760206103d0611ed8565b604051908152f35b5034610266576020366003190112610266576004356001600160401b0381116105a457610409903690600401611b31565b5050604051628bec5760e51b8152602081600481305afa90811561025b578291610585575b506001600160a01b0316330361057257610446611eee565b604051808091606051608090855b8181106105505750505003902060405180606051608090855b81811061053a575050508190039020916040519283927f3e3e7958121b3e39c7a49392d1aa9cdce870c2a059744f9e15cf66fff78654558380a3805f5160206121045f395f51905f525d6040820190604083526060518092526060830191608090825b81811061051857505050828203602084015260206060519283815201916080915b8181106104ff575050500390f35b82518452859450602093840193909201916001016104f1565b82516001600160a01b03168552869550602094850194909201916001016104d0565b825184526020938401939092019160010161046d565b82516001600160a01b0316845285945060209384019390920191600101610454565b631184b31b60e21b815233600452602490fd5b61059e915060203d602011610254576102468183611bc1565b5f61042e565b5080fd5b503461026657806003193601126102665760206040517f7935bd0ae54bc31f548c14dba4d37c5c64b3f8ca900cb468fb8abd54d5894f558152f35b50346102665780600319360112610266576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102665780600319360112610266578061012060405161064981611b91565b8281528260208201528260408201528260608201528260808201528260a0820152606060c0820152606060e08201528261010082015201526040519061068e82611b91565b546001600160a01b03908116825260015481166020830190815260025490911660408301908152600354606084019081526004546080850190815260055460a0860190815293949391929161078d9190610779906106ea611bf9565b9060c088019182526106fa611cdb565b60e089810191825260085460ff1615156101008b019081526009546101208c019081526040805160208082529d516001600160a01b039081169e82019e909e529d518d16908e01529851909a1660608c0152975160808b0152935160a08a01525160c08901525161014095880195909552869594610160870190611ae1565b9051858203601f1901610100870152611ae1565b91511515610120840152516101408301520390f35b5034610266576080366003190112610266576004356107bf611b1b565b6044356001600160401b0381116108ea576107de903690600401611b31565b6064939193356001600160401b03811161090557610800903690600401611b31565b86549091906001600160a01b031633036108f25786929161082091611f23565b6002546001600160a01b031693610838848287611fae565b6001600160a01b031694853b156108ee5781606484926040519485938492632db6d39960e01b845289600485015260406024850152816044850152848401378181018301859052601f01601f1916810103018183895af1801561025b576108d5575b50506108cf7f9f784fc02a186f1c98b2d9f15fda084da27cdd291a3785d978f91911d880516b91604051918291309583611e95565b0390a380f35b816108df91611bc1565b6108ea57835f61089a565b8380fd5b8280fd5b631564c0e160e11b875233600452602487fd5b8580fd5b503461026657806003193601126102665760206040517f025d8bbf3268be680d2605ebf6da15063b9915615bf1087dab336efc1bf970cb8152f35b50346102665780600319360112610266576020600954604051908152f35b50346102665780600319360112610266576020600554604051908152f35b503461026657806003193601126102665760206040515f5160206120c45f395f51905f528152f35b5034610266576020366003190112610266578054600435906001600160a01b03163303610a01576020817fb6ac66853c4e59c71e118d25ab494bb847c4e5eb0c8894898c5343e6f61afc1292600555604051908152a180f35b631564c0e160e11b825233600452602482fd5b5034610266578060031936011261026657604051600160f91b60208281019182523060601b6001600160601b031916602184015260158352610a8892909190610a5e603582611bc1565b519020604051632474521560e21b8152600481019190915233602482015291829081906044820190565b03817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561025b578291610b3b575b5015610b285780546001600160a01b038116610b19576001600160a01b0319163390811782556040519081527f55489ce0259bd691120d8860861be1c401c7c16a3cd268d21045756af4ecc5ca90602090a180f35b636a79b97d60e11b8252600482fd5b631564c0e160e11b815233600452602490fd5b610b54915060203d602011610390576103828183611bc1565b5f610ac4565b5034610266576020366003190112610266578054600435906001600160a01b03163303610a01576020817f333b26cca69716ad4680ddb07663f5bfb4f06045671f336af9a83690a3ae00f992600355604051908152a180f35b5034610266578060031936011261026657604051637aaceb9560e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561025b576020929161022e57506040516001600160a01b039091168152f35b5034610266578060031936011261026657546001546002546003546004546005546001600160a01b0394851695851694929390921691610cc39190610cb590610c6c611bf9565b90610c75611cdb565b9360ff6008541697600954976040519b8c9b8c5260208c015260408b015260608a0152608089015260a088015261014060c0880152610140870190611ae1565b9085820360e0870152611ae1565b9115156101008401526101208301520390f35b5034610266576020366003190112610266576004356001600160401b0381116105a457366023820112156105a4578060040135610d1281611be2565b91610d206040519384611bc1565b8183526024602084019260051b820101903682116111ef57602401915b818310611311575050604051628bec5760e51b81529050602081600481305afa9081156111e45783916112f2575b506001600160a01b031633036112df57610d83611eee565b8051610da7610d9182611be2565b91610d9f6040519384611bc1565b808352611be2565b602082019290601f1901368437805193610dd9610dc386611be2565b95610dd16040519788611bc1565b808752611be2565b6020860190601f1901368237600254825460405163c8169aa160e01b8152916001600160a01b039081169160209184916004918391165afa918215610fc45784926112be575b506040516370a0823160e01b8152306004820152602081602481855afa90811561126e57859161128c575b50151580611279575b6110f3575b5050815b8351811015610fcf5760249060206001600160a01b03610e7c8388611eb0565b5116604051938480926370a0823160e01b82523060048301525afa918215610fc4578492610f91575b5081610eb6575b6001915001610e5c565b6001600160a01b03610ec88287611eb0565b5116916024610ed5611e2a565b9360206001600160a01b03610eea868b611eb0565b5116604051938480926370a0823160e01b82523060048301525afa918215610f86578792610f4e575b5090600194610f2192611f74565b828060a01b03610f318388611eb0565b5116610f3d8389611eb0565b52610f48828a611eb0565b52610eac565b91506020823d8211610f7e575b81610f6860209383611bc1565b81010312610f7a579051906001610f13565b5f80fd5b3d9150610f5b565b6040513d89823e3d90fd5b9091506020813d8211610fbc575b81610fac60209383611bc1565b81010312610f7a5751905f610ea5565b3d9150610f9f565b6040513d86823e3d90fd5b5085908492866040518086518390855b8181106110d4575050508190039020936040518082518690865b8181106110be575050508190039020956040519687967f46b8771620f6acf56cb03d3e835ea8024c7dcbcf05fcc3f6ade9e19d1a3e212b8680a3835f5160206121045f395f51905f525d60408601906040875251809152606086019290845b81811061109c575050506020908583038287015251918281520192915b818110611083575050500390f35b8251845285945060209384019390920191600101611075565b82516001600160a01b0316855288975060209485019490920191600101611058565b8251845260209384019390920191600101610ff9565b82516001600160a01b0316845260209384019390920191600101610fdf565b6040516370a0823160e01b8152306004820152602081602481855afa90811561126e57859161123b575b508261112e60209260249585611fae565b6040516370a0823160e01b8152306004820152936001600160a01b03919091169284919082905afa918215610fc4578492611207575b5060405191602083018381106001600160401b038211176111f357604052848352813b156111ef579184916111bd9383604051809681958294632db6d39960e01b84526004840152604060248401526044830190611ae1565b03925af180156111e45790839115610e5857816111d991611bc1565b6105a457815f610e58565b6040513d85823e3d90fd5b8480fd5b634e487b7160e01b86526041600452602486fd5b9091506020813d602011611233575b8161122360209383611bc1565b81010312610f7a5751905f611164565b3d9150611216565b90506020813d602011611266575b8161125660209383611bc1565b81010312610f7a5751602461111d565b3d9150611249565b6040513d87823e3d90fd5b50306001600160a01b0383161415610e53565b90506020813d6020116112b6575b816112a760209383611bc1565b81010312610f7a57515f610e4a565b3d915061129a565b6112d891925060203d602011610254576102468183611bc1565b905f610e1f565b631184b31b60e21b825233600452602482fd5b61130b915060203d602011610254576102468183611bc1565b5f610d6b565b82356001600160a01b038116810361090557815260209283019201610d3d565b50346102665760403660031901126102665760043560038110156105a45760209161135a611b1b565b9050604051908382019260f81b835260018060601b03199060601b1660218201526015815261138a603582611bc1565b519020604051908152f35b503461026657806003193601126102665760206040515f5160206120e45f395f51905f528152f35b5034610266576020366003190112610266578054600435906001600160a01b03163303610a01576020817ffbe2d5c01ea8ba5596d6c4e6c82c6d4a0a0ee1128689993a4a5ba0169273d69f92600455604051908152a180f35b50346102665780600319360112610266576040516361d027b360e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561025b576020929161022e57506040516001600160a01b039091168152f35b5034610266578060031936011261026657604051635b0f83f360e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa90811561025b576020929161022e57506040516001600160a01b039091168152f35b503461026657806003193601126102665761152a611516611cdb565b604051918291602083526020830190611ae1565b0390f35b5034610266576020366003190112610266578054600435906001600160a01b03163303610a015768056bc75e2d631000008111611597576020817fd3c6d0ab315f2f1352f036cd9f401b49e38e1b90907e195225e8105f9a0b6f0292600955604051908152a180f35b634ef9dfe360e01b8252600482fd5b50346102665780600319360112610266576002546040516001600160a01b039091168152602090f35b5034610266578060031936011261026657546040516001600160a01b039091168152602090f35b50346102665780600319360112610266576020600454604051908152f35b5034610266578060031936011261026657602060ff600854166040519015158152f35b50346102665761164636611b5e565b9061164f611eee565b604051631b93849b60e11b8152602081600481305afa90811561126e5785916117e5575b506001600160a01b031633810361171e575b509061169091611f23565b7fcbaa1442ac205415c9d69643e7b60ec73d1de35dbc807c21ec288c70ddc4207b61170860018060a01b0360025416926116fa6040516323b872dd60e01b6020820152336024820152306044820152826064820152606481526116f4608482611bc1565b8561206b565b604051918291339583611e95565b0390a2805f5160206121045f395f51905f525d80f35b604051628bec5760e51b8152602081600481305afa9081156117da5786916117bb575b506001600160a01b031633146116855760206024916040519283809263d206a05960e01b82523360048301525afa90811561126e57859161179c575b5015611789575f611685565b638f7a567d60e01b845233600452602484fd5b6117b5915060203d602011610390576103828183611bc1565b5f61177d565b6117d4915060203d602011610254576102468183611bc1565b5f611741565b6040513d88823e3d90fd5b6117fe915060203d602011610254576102468183611bc1565b5f611673565b503461026657806003193601126102665760206040517f55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a50418152f35b50346102665761184e36611b5e565b83549091906001600160a01b031633036118b257906118749161186f611eee565b611f23565b6002546001600160a01b0316907fd5e872c5ecfb1bb8820b2e6a20e31b883682282da886621541f71e31ec11947e90611708906116fa813386611f74565b631564c0e160e11b845233600452602484fd5b503461026657806003193601126102665760206118e0611e2a565b6040516001600160a01b039091168152f35b5034610f7a576020366003190112610f7a5761190c611b05565b604051600160f81b60208281019182523060601b6001600160601b0319166021840152601583527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169261196e9290610a5e603582611bc1565b0381855afa908115611a06575f91611a8d575b50159081611a24575b50611a1157733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae3b15610f7a5760405163bdac7ca360e01b81523060048201526001600160a01b0390911660248201525f8160448183733ef3d8ba38ebe18db133cec108f4d14ce00dd9ae5af18015611a06576119f8575080f35b611a0491505f90611bc1565b005b6040513d5f823e3d90fd5b6329068e8160e21b5f523360045260245ffd5b604051632474521560e21b81525f5160206120e45f395f51905f5260048201523360248201529150602090829060449082905afa908115611a06575f91611a6e575b50155f61198a565b611a87915060203d602011610390576103828183611bc1565b5f611a66565b611aa6915060203d602011610390576103828183611bc1565b5f611981565b34610f7a575f366003190112610f7a5761152a611516611bf9565b34610f7a575f366003190112610f7a5760206103d0611d87565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b0382168203610f7a57565b602435906001600160a01b0382168203610f7a57565b9181601f84011215610f7a578235916001600160401b038311610f7a5760208381860195010111610f7a57565b906040600319830112610f7a5760043591602435906001600160401b038211610f7a57611b8d91600401611b31565b9091565b61014081019081106001600160401b03821117611bad57604052565b634e487b7160e01b5f52604160045260245ffd5b90601f801991011681019081106001600160401b03821117611bad57604052565b6001600160401b038111611bad5760051b60200190565b604051905f6006548060011c9160018216918215611cd1575b602084108314611cbd578386528592908115611c9e5750600114611c3f575b611c3d92500383611bc1565b565b5060065f90815290917ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b818310611c82575050906020611c3d92820101611c31565b6020919350806001915483858901015201910190918492611c6a565b60209250611c3d94915060ff191682840152151560051b820101611c31565b634e487b7160e01b5f52602260045260245ffd5b92607f1692611c12565b604051905f6007548060011c9160018216918215611d7d575b602084108314611cbd578386528592908115611c9e5750600114611d1e57611c3d92500383611bc1565b5060075f90815290917fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c6885b818310611d61575050906020611c3d92820101611c31565b6020919350806001915483858901015201910190918492611d49565b92607f1692611cf4565b6002546040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa908115611a06575f91611dc4575090565b90506020813d602011611deb575b81611ddf60209383611bc1565b81010312610f7a575190565b3d9150611dd2565b90816020910312610f7a57518015158103610f7a5790565b90816020910312610f7a57516001600160a01b0381168103610f7a5790565b604051628bec5760e51b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa908115611a06575f91611e79575090565b611e92915060203d602011610254576102468183611bc1565b90565b6001600160a01b039091168152602081019190915260400190565b8051821015611ec45760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b60ff60085416611eea57611e92611d87565b5f90565b5f5160206121045f395f51905f525c611f145760015f5160206121045f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b5015801580611f67575b611f585780611f4c575b611f3d57565b63332863a960e11b5f5260045ffd5b5060ff60085416611f37565b630cd0fdf960e01b5f5260045ffd5b5060ff6008541615611f2d565b611fa9611c3d9392611f9b60405194859263a9059cbb60e01b602085015260248401611e95565b03601f198101845283611bc1565b61206b565b91909160205f60405193611fe585611fd78582019363095ea7b360e01b85528960248401611e95565b03601f198101875286611bc1565b84519082855af15f513d82612046575b50501561200157505050565b60405163095ea7b360e01b60208201526001600160a01b0390931660248401525f6044808501919091528352611c3d92611fa990612040606482611bc1565b8261206b565b90915061206357506001600160a01b0381163b15155b5f80611ff5565b60011461205c565b905f602091828151910182855af115611a06575f513d6120ba57506001600160a01b0381163b155b61209a5750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b6001141561209356feb00be3d6a5434b97b328543d1486d56adcb7e74080170d1cdd7e0306c3d9ba3d0d186688925976bbe6755ae984501c8e3e2b103a7af59fd803ab9c6d891ae7e09b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a2646970667358221220dbb985e1e4aee79b943132eb751c0db69661cd05d6b16198ea66a813e1f4055c64736f6c634300081c003300000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000001c00000000000000000000000005a4ac204864a36e9820a3663836299ed963f085700000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000025800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000184c617a795661756c745f4c6f7765725269736b5f5553444300000000000000000000000000000000000000000000000000000000000000000000000000000002222200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064c56555344430000000000000000000000000000000000000000000000000000
Deployed Bytecode
0x60806040526004361015610011575f80fd5b5f3560e01c806301e1d1141461054a57806306fdde031461054557806307a2d13a146104e1578063095ea7b3146105405780630a28a4771461053b578063117d8ae014610536578063133ab5791461053157806318160ddd1461052c578063218e4a151461052757806323b872dd14610522578063240ecd601461051d57806324ea54f4146105185780632755cd2d14610513578063313ce5671461050e5780633152d5d114610509578063340505601461050457806338d52e0f146104ff5780633a7c9f0e146104fa5780633e314c76146104f55780633f4ba83a146104f0578063402d267d146104eb578063498e76a0146104e65780634cdad506146104e15780634daecb9c146104dc578063565974d3146104d75780635822198f146104d25780635b0f83f3146104cd5780635c975abb146104c85780635ed975e5146104c35780635f538f6f146104be57806361d027b3146104b957806366e943f1146104b4578063680e57ab146104af57806369b3054b146104aa5780636e553f65146104a557806370a08231146104a057806371aedbc11461049b57806379502c55146104965780637aaceb951461049157806383cf3d4a1461048c5780638456cb59146104875780639265b76e14610482578063934170521461047d57806394bf804d1461047857806394d7eaa41461047357806395d89b411461046e57806396c25a3814610469578063a039e94414610464578063a0506f0b1461045f578063a89f38a31461045a578063a9059cbb14610455578063b3d7f6b914610450578063b460af941461044b578063b637766c14610446578063ba08765214610441578063bef97c871461043c578063c0b534c214610437578063c37007c214610432578063c3f909d41461042d578063c63d75b614610428578063c6e6f592146103d3578063c8169aa114610423578063c9c667e31461041e578063ccc5749014610419578063ce96cb7714610414578063d206a0591461040f578063d45a07a11461040a578063d570ee4714610405578063d902d41a14610400578063d905777e146103fb578063dc9de0a8146103f6578063dd62ed3e146103f1578063e193858f146103ec578063e37d5b7f146103e7578063e7b20e5b146103e2578063ebc136d0146103dd578063ef2fc472146103d8578063ef8b30f7146103d3578063f3577816146103ce578063f3ba553e146103c9578063f7e533ec146103c4578063faa9bce9146103bf578063fcf2849f146103ba5763ff32a42a146103b5575f80fd5b6126ab565b6125a0565b61250f565b612485565b6123de565b6123c5565b611d15565b61239e565b6122df565b61223d565b61213a565b612092565b612040565b611fa5565b611f7e565b611ee3565b611ebb565b611e14565b611ded565b611dc6565b611d9f565b611d5b565b611d33565b611cee565b611c3c565b611b99565b611b5f565b611b3d565b611a5d565b6119b6565b6118c9565b6118ab565b611880565b611859565b61183c565b611823565b611772565b6116bd565b6116a0565b6114fb565b611465565b61143e565b611341565b611316565b6112ea565b61129a565b61127d565b611243565b611219565b6111b4565b611197565b611170565b6110fe565b6110e5565b6110ca565b6110a8565b611036565b610f7b565b610ec6565b610dbb565b6106b8565b610d9e565b610d77565b610c67565b610c40565b610c27565b610bba565b610b13565b610af6565b610aaa565b610a77565b610a50565b6109eb565b6109aa565b61098d565b610973565b610889565b6107e3565b6107a1565b6106f4565b6105c5565b61055d565b5f91031261055957565b5f80fd5b34610559575f36600319011261055957600854602090610585906001600160a01b0316613e6f565b604051908152f35b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b9060206105c292818152019061058d565b90565b34610559575f366003190112610559576040515f6003548060011c90600181169081156106ae575b60208310821461069a578285526020850191908115610681575060011461062f575b61062b8461061f81860382610ea5565b604051918291826105b1565b0390f35b60035f9081529250907fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b81841061066d5750500161061f8261060f565b80548484015260209093019260010161065a565b60ff191682525090151560051b01905061061f8261060f565b634e487b7160e01b5f52602260045260245ffd5b91607f16916105ed565b34610559576020366003190112610559576020610585600435613f29565b6001600160a01b0381160361055957565b35906106f2826106d6565b565b3461055957604036600319011261055957600435610711816106d6565b602435331561078e576001600160a01b03821691821561077b576107418291335f52600160205260405f20612f7c565b5560405190815233907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a3602060405160018152f35b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b34610559576020366003190112610559576020610585600435613fa8565b6001600160a01b0316600452602490565b6001600160a01b03909116815260200190565b34610559575f36600319011261055957604051628bec5760e51b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610884575f91610855575b506040516001600160a01b039091168152602090f35b610877915060203d60201161087d575b61086f8183610ea5565b81019061270a565b5f61083f565b503d610865565b61271f565b3461055957602036600319011261055957600435301580156108cb575b6108b5576108b39061278e565b005b6363b52ed760e11b5f526108c8336107bf565b5ffd5b5061090160206108da30612ddb565b604051632474521560e21b8152600481019190915233602482015291829081906044820190565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91610944575b50156108a6565b610966915060203d60201161096c575b61095e8183610ea5565b81019061272a565b5f61093d565b503d610954565b34610559575f366003190112610559576020610585612810565b34610559575f366003190112610559576020601354604051908152f35b346105595760603660031901126105595760206109e16004356109cc816106d6565b6024356109d8816106d6565b60443591612843565b6040519015158152f35b34610559575f36600319011261055957610a036151da565b6040518091602082016020835281518091526020604084019201905f5b818110610a2e575050500390f35b82516001600160a01b0316845285945060209384019390920191600101610a20565b34610559575f3660031901126105595760206040515f516020615f585f395f51905f528152f35b34610559575f36600319011261055957610a8f613ffa565b6020610585610a9c612f91565b610aa4612810565b9061404e565b34610559575f3660031901126105595760ff7f00000000000000000000000000000000000000000000000000000000000000061660ff8111610af157602090604051908152f35b6127e1565b34610559575f366003190112610559576020601454604051908152f35b3461055957604036600319011261055957600435610b30816106d6565b60243530158015610b49575b6108b5576108b391612892565b50610b5860206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91610b9b575b5015610b3c565b610bb4915060203d60201161096c5761095e8183610ea5565b5f610b94565b34610559575f366003190112610559576040517f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f6001600160a01b03168152602090f35b60609060031901126105595760043590602435610c1a816106d6565b906044356105c2816106d6565b34610559576020610585610c3a36610bfe565b91612902565b34610559576020366003190112610559576020610585600435610c62816106d6565b612a90565b34610559575f36600319011261055957604051632474521560e21b81527f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03169060208180610cc03360048301612742565b0381855afa908115610884575f91610d58575b50159081610cfc575b50610ce9576108b3614545565b636b2a758d60e01b5f526108c8336107bf565b604051632474521560e21b8152915060209082908180610d1f3360048301612768565b03915afa908115610884575f91610d39575b50155f610cdc565b610d52915060203d60201161096c5761095e8183610ea5565b5f610d31565b610d71915060203d60201161096c5761095e8183610ea5565b5f610cd3565b34610559576020366003190112610559576020610585600435610d99816106d6565b612b1a565b34610559575f366003190112610559576020601154604051908152f35b346105595760203660031901126105595760043530158015610de5575b6108b5576108b390612bdf565b50610df460206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91610e37575b5015610dd8565b610e50915060203d60201161096c5761095e8183610ea5565b5f610e30565b634e487b7160e01b5f52604160045260245ffd5b60a081019081106001600160401b03821117610e8557604052565b610e56565b604081019081106001600160401b03821117610e8557604052565b90601f801991011681019081106001600160401b03821117610e8557604052565b34610559575f366003190112610559576040515f600d548060011c9060018116908115610f71575b60208310821461069a5782855260208501919081156106815750600114610f1f5761062b8461061f81860382610ea5565b600d5f9081529250907fd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb55b818410610f5d5750500161061f8261060f565b805484840152602090930192600101610f4a565b91607f1691610eee565b3461055957602036600319011261055957600435604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91611017575b5015611004576108b390612c18565b630ea7d7ed60e21b5f526108c8336107bf565b611030915060203d60201161096c5761095e8183610ea5565b5f610ff5565b34610559575f36600319011261055957604051635b0f83f360e01b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610884575f9161085557506040516001600160a01b039091168152602090f35b34610559575f36600319011261055957602060ff600554166040519015158152f35b34610559575f36600319011261055957602060405160328152f35b346105595760206105856110f836610bfe565b91612ca3565b34610559575f366003190112610559576040516361d027b360e01b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610884575f9161085557506040516001600160a01b039091168152602090f35b34610559575f3660031901126105595760206040515f516020615f185f395f51905f528152f35b34610559575f366003190112610559576020600654604051908152f35b34610559576040366003190112610559576004356003811015610559576020906024356111e0816106d6565b604051908382019260f81b835260018060601b03199060601b1660218201526015815261120e603582610ea5565b519020604051908152f35b3461055957604036600319011261055957602061058560243560043561123e826106d6565b612e43565b3461055957602036600319011261055957600435611260816106d6565b60018060a01b03165f525f602052602060405f2054604051908152f35b34610559575f366003190112610559576020601254604051908152f35b34610559575f36600319011261055957600854600954600a54600b54600c54604080516001600160a01b03968716815260208101959095528401929092526060830152909116608082015260a090f35b34610559575f366003190112610559576020611304612f91565b6040516001600160a01b039091168152f35b34610559576040366003190112610559576020610585600435611338816106d6565b60243590612ffa565b34610559575f36600319011261055957604051632474521560e21b81527f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b0316906020818061139a3360048301612742565b0381855afa908115610884575f9161141f575b501590816113c3575b50610ce9576108b3614b02565b604051632474521560e21b81529150602090829081806113e63360048301612768565b03915afa908115610884575f91611400575b50155f6113b6565b611419915060203d60201161096c5761095e8183610ea5565b5f6113f8565b611438915060203d60201161096c5761095e8183610ea5565b5f6113ad565b34610559576020366003190112610559576020610585600435611460816106d6565b613093565b34610559575f366003190112610559573015801561148a575b6108b5576108b361310e565b5061149960206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f916114dc575b501561147e565b6114f5915060203d60201161096c5761095e8183610ea5565b5f6114d5565b34610559576040366003190112610559576004602435813561151c826106d6565b6001611526614015565b5d611532610a9c612f91565b5060085460209061157290611566906115536001600160a01b0382166145b7565b5061155c613ffa565b6115663386614b47565b6001600160a01b031690565b6040516278744560e21b815294859182905afa908115610884576004935f9261167b575b50806115a46115ac92613f68565b8094336148bc565b6008546115cc9083906115c7906001600160a01b0316611566565b61494a565b6008546020906115e4906001600160a01b0316611566565b6040516278744560e21b815294859182905afa8015610884576116295f516020615eb85f395f51905f529161062b955f9161164c575b50604051918291339583612dca565b0390a2611634614326565b61163c613985565b6040519081529081906020820190565b61166e915060203d602011611674575b6116668183610ea5565b810190612a81565b5f61161a565b503d61165c565b6115ac9192506116999060203d602011611674576116668183610ea5565b9190611596565b34610559575f366003190112610559576020600754604051908152f35b34610559575f366003190112610559576040515f6004548060011c9060018116908115611768575b60208310821461069a57828552602085019190811561068157506001146117165761062b8461061f81860382610ea5565b60045f9081529250907f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b8184106117545750500161061f8261060f565b805484840152602090930192600101611741565b91607f16916116e5565b346105595760203660031901126105595760043561178f816106d6565b604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91611804575b5015611004576108b39061323b565b61181d915060203d60201161096c5761095e8183610ea5565b5f6117f5565b3461055957602061058561183636610bfe565b91613373565b34610559575f3660031901126105595760206040516202a3008152f35b34610559575f3660031901126105595760206040515f516020615ed85f395f51905f528152f35b346105595760403660031901126105595760206109e16004356118a2816106d6565b60243590613499565b34610559576020366003190112610559576020610585600435613f68565b346105595760046118d936610bfe565b9060016118e4614015565b5d6118f0610a9c612f91565b50600854926119076001600160a01b0385166145b7565b50611910613ffa565b928390602090611928906001600160a01b0316611566565b6040516278744560e21b815296879182905afa9081156108845761062b955f92611995575b505f191461197b575b831161196d5761196592612ca3565b611634614326565b61197692613373565b611965565b925061198f61198983612f63565b54613f29565b92611956565b6119af91925060203d602011611674576116668183610ea5565b905f61194d565b34610559576040366003190112610559576004356119d3816106d6565b602435301580156119ec575b6108b5576108b3916134d8565b506119fb60206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91611a3e575b50156119df565b611a57915060203d60201161096c5761095e8183610ea5565b5f611a37565b34610559576004611a6d36610bfe565b906001611a78614015565b5d611a84610a9c612f91565b5060085492611a9b6001600160a01b0385166145b7565b50611aa4613ffa565b928390602090611abc906001600160a01b0316611566565b6040516278744560e21b815296879182905afa9485156108845761062b95611aeb915f91611b1e575b50613fd1565b905f1914611b0c575b8311611b035761196592613c58565b61197692612902565b9250611b1782612f63565b5492611af4565b611b37915060203d602011611674576116668183610ea5565b5f611ae5565b34610559575f36600319011261055957602060ff601054166040519015158152f35b34610559575f3660031901126105595760206040517f025d8bbf3268be680d2605ebf6da15063b9915615bf1087dab336efc1bf970cb8152f35b34610559575f36600319011261055957604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91611c1d575b5015611004576108b361352b565b611c36915060203d60201161096c5761095e8183610ea5565b5f611c0f565b34610559575f366003190112610559575f6080604051611c5b81610e6a565b828152826020820152826040820152826060820152015261062b604051611c8181610e6a565b6008546001600160a01b039081168083526009546020808501918252600a546040808701918252600b546060808901918252600c5488166080998a0190815283519788529551948701949094529151908501525190830152519091169181019190915290819060a0820190565b34610559576020366003190112610559576020610585600435611d10816106d6565b613572565b34610559576020366003190112610559576020610585600435613fd1565b34610559575f366003190112610559576008546040516001600160a01b039091168152602090f35b34610559575f366003190112610559576040517f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03168152602090f35b34610559575f3660031901126105595760206040515f516020615ef85f395f51905f528152f35b34610559576020366003190112610559576020610585600435611de8816106d6565b61361f565b346105595760203660031901126105595760206109e1600435611e0f816106d6565b613650565b3461055957604036600319011261055957600435611e31816106d6565b60243530158015611e4a575b6108b5576108b39161367f565b50611e5960206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91611e9c575b5015611e3d565b611eb5915060203d60201161096c5761095e8183610ea5565b5f611e95565b34610559575f36600319011261055957600854602090610585906001600160a01b0316614bbc565b346105595760203660031901126105595760043530158015611f0d575b6108b5576108b3906136d2565b50611f1c60206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91611f5f575b5015611f00565b611f78915060203d60201161096c5761095e8183610ea5565b5f611f58565b34610559576020366003190112610559576020610585600435611fa0816106d6565b61370b565b346105595760203660031901126105595760043530158015611fcf575b6108b5576108b390613724565b50611fde60206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91612021575b5015611fc2565b61203a915060203d60201161096c5761095e8183610ea5565b5f61201a565b34610559576040366003190112610559576020612089600435612062816106d6565b6024359061206f826106d6565b6001600160a01b03165f9081526001845260409020612f7c565b54604051908152f35b3461055957602036600319011261055957600435604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f9161211b575b5015611004576108b390613798565b612134915060203d60201161096c5761095e8183610ea5565b5f61210c565b3461055957602036600319011261055957600435612157816106d6565b604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f916121cc575b5015611004576108b3906137ea565b6121e5915060203d60201161096c5761095e8183610ea5565b5f6121bd565b906020600319830112610559576004356001600160401b0381116105595782602382011215610559578060040135926001600160401b0384116105595760248460051b83010111610559576024019190565b346105595761224b366121eb565b604051632474521560e21b81525f516020615ef85f395f51905f5260048201523360248201526020816044817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f916122c0575b5015611004576108b39161395c565b6122d9915060203d60201161096c5761095e8183610ea5565b5f6122b1565b34610559576020366003190112610559576004356122fc816106d6565b604051632474521560e21b81525f516020615ed85f395f51905f5260048201526001600160a01b03918216602482015290602090829060449082907f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f165afa80156108845761062b915f9161237f575b5060405190151581529081906020820190565b612398915060203d60201161096c5761095e8183610ea5565b5f61236c565b346105595760203660031901126105595760206105856004356123c0816106d6565b613b80565b346105595760206105856123d836610bfe565b91613c58565b34610559576040366003190112610559576004356123fb816106d6565b60243530158015612414575b6108b5576108b391613d04565b5061242360206108da30612ddb565b03817f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03165afa908115610884575f91612466575b5015612407565b61247f915060203d60201161096c5761095e8183610ea5565b5f61245f565b34610559575f366003190112610559576020611304613d57565b604051906106f2604083610ea5565b6001600160401b038111610e8557601f01601f191660200190565b81601f82011215610559578035906124e0826124ae565b926124ee6040519485610ea5565b8284526020838301011161055957815f926020809301838601378301015290565b346105595760603660031901126105595760043560243561252f816106d6565b604435906001600160401b0382116105595761062b92602061255861163c9436906004016124c9565b604051918183925191829101835e81015f815203902060018060a01b0383167f38383a2eb7bd8ee888f12fb942a2e22e84f2d7240f1f8541ad4bbddace6e34425f80a3612e43565b34610559576125ae366121eb565b7f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b03166125e660206108da30612e10565b0381855afa908115610884575f9161268c575b50159081612623575b50612610576108b391613da7565b6329068e8160e21b5f526108c8336107bf565b604051632474521560e21b81525f516020615f185f395f51905f5260048201523360248201529150602090829060449082905afa908115610884575f9161266d575b50155f612602565b612686915060203d60201161096c5761095e8183610ea5565b5f612665565b6126a5915060203d60201161096c5761095e8183610ea5565b5f6125f9565b3461055957602036600319011261055957600435600e5481101561270557600e5f527fbb7b4a454dc3493923482f07822329ed19e8244eff582cc204f8554c3620c3fd01546040516001600160a01b039091168152602090f35b61415b565b9081602091031261055957516105c2816106d6565b6040513d5f823e3d90fd5b90816020910312610559575180151581036105595790565b5f516020615f585f395f51905f5281526001600160a01b03909116602082015260400190565b5f516020615ef85f395f51905f5281526001600160a01b03909116602082015260400190565b612796613ffa565b603281116127cf576020817f4f4bedc5354096786a0fb857b12fdd6488cc973b2348cedb78088bdceaa906b592600b55604051908152a1565b631c94cf1160e11b5f5260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b9060018201809211610af157565b91908201809211610af157565b612818614015565b5c61283d576002546128318161282c612f91565b612ffa565b8101809111610af15790565b60025490565b919060ff60105416801561287e575b6128655763ec47ea8b60e01b5f5260045ffd5b612879926128748333836150b3565b615145565b600190565b50600c546001600160a01b03163314612852565b6001600160a01b0316906128a582615222565b156128ef576128b2613ffa565b813b15610559575f91602483926040519485938492638665120360e01b845260048401525af18015610884576128e55750565b5f6106f291610ea5565b50632767039f60e01b5f5260045260245ffd5b600161290c614015565b5d612918610a9c612f91565b5060085461292e906001600160a01b0316614191565b612936613ffa565b8015612a57576001600160a01b0383169133831415806129fd575b6129e95761295e8461370b565b8083116129d45750907f09fbb654e02253d6c37ecb473c5ed6f4557cac3fe5abc1d559523f6e257ee185916129a88261299681613f29565b80976129a182614364565b8433614452565b6129b15f601455565b6129c060405192839283612a66565b0390a26129cb614326565b906106f2613985565b632e52afbb60e21b5f526108c890838661434d565b630c849df760e41b5f526108c8843361320a565b50604051636eb1769f60e11b815260208180612a1d338960048401613221565b0381305afa80156108845783915f91612a38575b5010612951565b612a51915060203d602011611674576116668183610ea5565b5f612a31565b632334425960e21b5f5260045ffd5b6001600160a01b039091168152602081019190915260400190565b90816020910312610559575190565b6008546040516278744560e21b81529190602090839060049082906001600160a01b03165afa918215610884575f92612aec575b5060018060a01b03165f525f602052612ae060405f2054613f29565b90818082109118021890565b612b0691925060203d602011611674576116668183610ea5565b905f612ac4565b91908203918211610af157565b600854612b609190612b34906001600160a01b0316613e6f565b600a5480821115612bcd57505060205f915b604051809481926370a0823160e01b8352600483016107d0565b03817f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f6001600160a01b03165afa908115610884576105c2925f92612bac575b50808218908211021890565b612bc691925060203d602011611674576116668183610ea5565b905f612ba0565b602091612bd991612b0d565b91612b46565b60207f3ba130ec8df44f0a71243af1b7f9f4239616bafda97ae766b3c40a9d202b21a491612c0b613ffa565b80600955604051908152a1565b612c20613ffa565b612c28612f91565b90612c31612810565b907f0000000000000000000000000000000000000000000000004563918244f400008111612c9457612c866020927f186e864438b783eec69fd7ce4871c28accfc0b45558ea08c48540f76094fecde9461404e565b5080601155604051908152a1565b63ab9a408f60e01b5f5260045ffd5b90612cac613ffa565b6001612cb6614015565b5d612cc2610a9c612f91565b5060085492612cd96001600160a01b0385166145b7565b50612cf5611566612ce985613fa8565b95611566848888614746565b92604051916278744560e21b8352602083600481885afa9384156108845786935f95612da1575b50612d2b83612d31969761482b565b33614452565b600854600490602090612d4c906001600160a01b0316611566565b6040516278744560e21b815292839182905afa908115610884575f516020615eb85f395f51905f5291612d8e915f9161164c5750604051918291339583612dca565b0390a2612d99614326565b6105c2613985565b612d31955083612dc2612d2b9260203d602011611674576116668183610ea5565b965050612d1c565b908152602081019190915260400190565b6040515f6020820190815260609290921b6001600160601b031916602182015260158152612e0a603582610ea5565b51902090565b604051600160f81b6020820190815260609290921b6001600160601b031916602182015260158152612e0a603582610ea5565b906001612e4e614015565b5d612e5a610a9c612f91565b5060046020612e8c611566600854612e7960018060a01b0382166145b7565b50612e82613ffa565b6115663388614880565b6040516278744560e21b815292839182905afa9081156108845783905f92612f3c575b50612eca612edf9293612ec183613fd1565b958691336148bc565b6008546115c7906001600160a01b0316611566565b600854600490602090612efa906001600160a01b0316611566565b6040516278744560e21b815292839182905afa908115610884575f516020615eb85f395f51905f52916129c0915f9161164c5750604051918291339583612dca565b612edf9250612f5c612eca9160203d602011611674576116668183610ea5565b9250612eaf565b6001600160a01b03165f90815260208190526040902090565b9060018060a01b03165f5260205260405f2090565b604051637aaceb9560e01b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610884575f91612fe1575090565b6105c2915060203d60201161087d5761086f8183610ea5565b61300660125442612b0d565b90811561308c57601154613021670de0b6b3a7640000614a93565b1461308c57602061304691604051809381926370a0823160e01b8352600483016107d0565b0381305afa8015610884576105c293613066925f9261306b575b50612b0d565b614ad7565b61308591925060203d602011611674576116668183610ea5565b905f613060565b5050505f90565b6008546040516278744560e21b815290602090829060049082906001600160a01b03165afa8015610884576130cf915f916130ef575b50613fa8565b9060018060a01b03165f525f60205260405f205490818082109118021890565b613108915060203d602011611674576116668183610ea5565b5f6130c9565b613116613ffa565b613124611566611566613d57565b604051630f07f82960e01b8152906020908290815f81613171307f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b031660048401613221565b03925af18015610884576131a9915f916131eb575b50600c80546001600160a01b0319166001600160a01b0392909216919091179055565b600c546040517f8f407169a2fff9de40408b8d482b293eff9e2dbc448da0593fa9a39d428a41049181906131e6906001600160a01b0316826107d0565b0390a1565b613204915060203d60201161087d5761086f8183610ea5565b5f613186565b6001600160a01b0390811660045216602452604490565b6001600160a01b0391821681529116602082015260400190565b613243613ffa565b6001600160a01b0381165f818152600f6020526040902054909190156128ef5761326c816154d0565b6132866132816001600160a01b038316611566565b61598a565b50813b156105595760405163ebf3113160e01b81525f8160048183875af180156108845761335f575b507f00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f6001600160a01b0316803b156105595760405163d55dd62b60e01b8152600260048201526001600160a01b039290921660248301525f908290604490829084905af1801561088457613345575b507f66d72a91b52f63fb063c4f672763d7ef15ce4d7c9a268a7f9b5133e41c1709a55f80a2565b806133535f61335993610ea5565b8061054f565b5f61331e565b806133535f61336d93610ea5565b5f6132af565b9190916001613380614015565b5d61338c610a9c612f91565b506008546133a2906001600160a01b0316614191565b6133aa613ffa565b6133b381613fa8565b928315612a57576001600160a01b03831692338414158061343f575b61342b576133dc8161361f565b8084116134165750906129a8858480946129a17fd4383faec5079b2ec7ac0ff240326baa0d584b03d51b9742f7c1a034f6fc015b97614364565b633fa733bb60e21b5f526108c891849061434d565b638b27f8ed60e01b5f526108c8903361320a565b50604051636eb1769f60e11b81526020818061345f338660048401613221565b0381305afa80156108845786915f9161347a575b50106133cf565b613493915060203d602011611674576116668183610ea5565b5f613473565b9060ff6010541680156134c4575b6134ba5763ec47ea8b60e01b5f5260045ffd5b6128799133615145565b50600c546001600160a01b031633146134a7565b6001600160a01b0316906134eb82615222565b156128ef576134f8613ffa565b813b15610559575f916024839260405194859384926361f5cd8b60e01b845260048401525af18015610884576128e55750565b613533613ffa565b60105460ff8116156135425750565b60ff19166001176010557feadb24812ab3c9a55c774958184293ebdb6c7f6a2dbab11f397d80c86feb65d35f80a1565b600854613587906001600160a01b0316613e6f565b600a54908181111561360a5750506135b760205f925b604051809381926370a0823160e01b8352600483016107d0565b03817f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f6001600160a01b03165afa8015610884576105c292613605925f92612bac5750808218908211021890565b613fd1565b6136196020916135b793612b0d565b9261359d565b600854613634906001600160a01b0316614bbc565b9060018060a01b03165f525f602052612ae060405f2054613f29565b6001600160a01b031661366281615222565b90811561366d575090565b6008546001600160a01b031614919050565b6001600160a01b03169061369282615222565b156128ef5761369f613ffa565b813b15610559575f9160248392604051948593849263497af41960e11b845260048401525af18015610884576128e55750565b60207f4faeac5aec9fa2e6f82ae7ccfef27a03ca3ff9d8c5356fea9acb2caad1c4c344916136fe613ffa565b80600a55604051908152a1565b6008546130cf90613605906001600160a01b0316614bbc565b61372c613ffa565b603c81106137895762015180811161377a577f5953b565c074c2cce1866b4e69c9efc4908556bb6fca70f735907c94d94055158160135461377260405192839283612dca565b0390a1601355565b637092ddf560e01b5f5260045ffd5b63d93a8d8760e01b5f5260045ffd5b6137a0613ffa565b6202a30081106137db576020817f3cf175d91d8c5823f3729423b5a64130e40d4b09e88c6dc1925a260f26818c2592600655604051908152a1565b63f710d83560e01b5f5260045ffd5b6137f2613ffa565b6001600160a01b03811690811561394d5761380c81613650565b61393a576040516338d52e0f60e01b8152602081600481865afa908115610884575f9161391b575b506040516338d52e0f60e01b8152602081600481305afa908115610884575f916138fc575b506001600160a01b039081169116036138ed57813b1561055957604051634545ccbb60e11b81525f8160048183875af18015610884576138b2926138ad92611566926138d9575b506001600160a01b031690565b615a2b565b507fcb4a29d359e86f179111dcba8714def1a859612f729f2d224d13efeac51b36bc5f80a2565b806133535f6138e793610ea5565b5f6138a0565b631692ea4f60e31b5f5260045ffd5b613915915060203d60201161087d5761086f8183610ea5565b5f613859565b613934915060203d60201161087d5761086f8183610ea5565b5f613834565b637eadea0960e11b5f526108c8906107bf565b63210e96cb60e01b5f5260045ffd5b9061398591600161396b614015565b5d613977610a9c612f91565b50613980613ffa565b613991565b5f61398e614015565b5d565b9190600b548111613b6e578015613b5f576008546139b7906001600160a01b0316611566565b926040516278744560e21b8152602081600481885afa908115610884575f91613b40575b506001600160a01b03909416935f90815b848110613a2257506106f29495505f8212613a09575b5050614e0b565b613a15613a1b92614cc9565b90615595565b5f80613a02565b86613a3c6115666020613a36858a8a614c6a565b01614c8c565b148015613b27575b613a51575b6001016139ec565b9186613a666115666020613a36878a8a614c6a565b14906040613a75858888614c6a565b01355f198114613aa9575b60019215613a9a57613a9191614cae565b925b9050613a49565b613aa391614c96565b92613a93565b508115613b18576004916020613ace611566611566613ac9898c8c614c6a565b614c8c565b6040516278744560e21b815294859182905afa8015610884576001935f91613afa575b50909250613a80565b613b12915060203d8111611674576116668183610ea5565b5f613af1565b63055bb2a160e41b5f5260045ffd5b5086613b3a611566613ac9848989614c6a565b14613a44565b613b59915060203d602011611674576116668183610ea5565b5f6139db565b6304dcdcd560e31b5f5260045ffd5b63899a5d8160e01b5f5260045260245ffd5b6040516278744560e21b815290602082600481305afa918215610884575f92613c37575b50604051635ee6ec4160e11b8152916001600160a01b039190911690602083600481855afa92831561088457600493602092613be7925f92613c18575b50614ef4565b916040519384809263dbd5edc760e01b82525afa908115610884576105c2925f92612bac5750808218908211021890565b613c30919250843d8611611674576116668183610ea5565b905f613be1565b613c5191925060203d602011611674576116668183610ea5565b905f613ba4565b916001613c63614015565b5d613c6f610a9c612f91565b50600854613ca09061156690613c8d6001600160a01b0382166145b7565b50613c96613ffa565b6115668487614f08565b6040516278744560e21b81529390602085600481845afa92831561088457612d2b955f94613ce1575b50612edf9394613cd884613f29565b9687809461482b565b612edf9450613cfe9060203d602011611674576116668183610ea5565b93613cc9565b6001600160a01b031690613d1782615222565b156128ef57613d24613ffa565b813b15610559575f91602483926040519485938492634fc7fac360e01b845260048401525af18015610884576128e55750565b604051633df94cfb60e21b81526020816004817f0000000000000000000000005a4ac204864a36e9820a3663836299ed963f08576001600160a01b03165afa908115610884575f91612fe1575090565b91906014549283420393428511610af157601354809510613dd7575061398592935042601455600161396b614015565b8490630924dbf160e21b5f526004526024524260445260645ffd5b604051602081017fa44c7cc604645fc9d906e0a5aeb821ecf76e473a1a4d03393ebd52161430e41a815260208252613e2b604083610ea5565b9051902060ff191690565b604051602081017fa9898051640582db44f19359a5df62a03dbff55353a9f388ea332d75dfa80fa0815260208252613e2b604083610ea5565b613e77613df2565b5c613f1c57613e8d90613e886151da565b614fbd565b5f9190825b8151841015613f175760046020613ec26001600160a01b03613eb4888761416f565b51166001600160a01b031690565b6040516278744560e21b815292839182905afa801561088457600192613eef925f92613ef7575b50612803565b930192613e92565b613f1091925060203d8111611674576116668183610ea5565b905f613ee9565b925050565b50613f25613e36565b5c90565b600854613f3e906001600160a01b0316613e6f565b9060018201809211610af157613f52612810565b60018101809111610af1576105c2925f92615055565b600854613f7d906001600160a01b0316613e6f565b9060018201809211610af157613f91612810565b60018101809111610af1576105c292600192615055565b613fb0612810565b9060018201809211610af157600854613f91906001600160a01b0316613e6f565b613fd9612810565b9060018201809211610af157600854613f52906001600160a01b0316613e6f565b60ff6005541661400657565b63d93c066560e01b5f5260045ffd5b604051602081017f4e71cabede5261c2c661c1a41d0d13331711e62f0548c4fdf8ade97c9c524d41815260208252613e2b604083610ea5565b9190601154156140a6576140629083612ffa565b91828061406d575050565b61407a9142601255615482565b7f698f29fe990d4e7770f7e74cd309da261dd03ca828f7bb3c2ea8b8c9adcc0ecd6020604051848152a1565b50426012555f9150565b604051602081017f98932279f8646d348f86cf154406d1fab3c6a0c52686d604c7d4a6a140038108815260208252613e2b604083610ea5565b6001600160401b038111610e855760051b60200190565b9061410a826140e9565b6141176040519182610ea5565b8281528092614128601f19916140e9565b01905f5b82811061413857505050565b60209060405161414781610e8a565b5f81525f838201528282850101520161412c565b634e487b7160e01b5f52603260045260245ffd5b80518210156127055760209160051b010190565b5f198114610af15760010190565b6141996140b0565b5c6142b1576141a7906145b7565b6141b18151614100565b905f915f905f5b835181101561429157600460206141e66115666115666141d8868a61416f565b51516001600160a01b031690565b60405163d570ee4760e01b815292839182905afa908115610884575f91614273575b5080614218575b506001016141b8565b61426661426c918395976142316141d86001968a61416f565b61424b61423c61249f565b6001600160a01b039092168252565b82602082015261425b8a8861416f565b52613ee9898761416f565b95614183565b929061420f565b61428b915060203d8111611674576116668183610ea5565b5f614208565b5091506106f2926142a3918352615233565b6142ac81615246565b615348565b50565b604051602081017f410d83ac3c7a0c2a0669e43e3a5ca6694ee49455f748efa9954a95c3752e9fc8815260208252613e2b604083610ea5565b604051602081017f2e756c3932ba771b80f1bae53d1177d9f7a4ced0ce66d74053b09f874cec6ffe815260208252613e2b604083610ea5565b5f61432f613df2565b5d5f6143396140b0565b5d5f6143436142b4565b5d5f61398e6142ed565b6001600160a01b0316600452602452604452606490565b61436c6142b4565b5c61437681614100565b905f5b8181106143f9575050905f5b82518110156143f457602061439a828561416f565b5101518281106143ba57506141d86143b5916106f29461416f565b61482b565b809392936143cf575b50600101919091614385565b8082946143e86143ed936143b56141d86001978961416f565b612b0d565b92906143c3565b505050565b8061440d60019261440861530f565b6158ba565b5c61441a826144086152d6565b5c6040519161442883610e8a565b848060a01b031682526020820152614440828661416f565b5261444b818561416f565b5001614379565b6001600160a01b03808416959082169392909182878603614534575b50508515614521576144a1827ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db946157ce565b60405163a9059cbb60e01b6020820152614504906144d5816144c7898660248401612a66565b03601f198101835282610ea5565b7f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f6001600160a01b03166158da565b61451c60405192839260018060a01b03169683612dca565b0390a4565b634b637e8f60e11b5f525f60045260245ffd5b61453e91856150b3565b5f8261446e565b6007546006548101809111610af15742106145a85760055460ff8116156145995760ff19166005557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1565b638dfc202b60e01b5f5260045ffd5b6304a59e3b60e01b5f5260045ffd5b6145bf613df2565b5c61473d576145cc6151da565b6145de6145d982516127f5565b614100565b925f90815b83518310156146935760046020614610611566611566614603888a61416f565b516001600160a01b031690565b6040516278744560e21b815292839182905afa80156108845760019261466b925f92614673575b50614645614603878961416f565b61465061423c61249f565b826020820152614660878b61416f565b52613ee9868a61416f565b9201916145e3565b61468c91925060203d8111611674576116668183610ea5565b905f614637565b6040516278744560e21b815291949192506001600160a01b0390911690602083600481855afa9182156108845761470d94614708945f94614716575b5090613ee9916146ef6146e061249f565b6001600160a01b039093168352565b8460208301525190614701828a61416f565b528761416f565b615452565b6106f282615465565b613ee9929194506147359060203d602011611674576116668183610ea5565b9390916146cf565b506105c26153dd565b908015612a5757336001600160a01b038416141590816147a4575b506147905761476f82612a90565b9182821161477c57505050565b633fa733bb60e21b5f526108c8935061434d565b638b27f8ed60e01b5f526108c8823361320a565b604051636eb1769f60e11b8152909150602081806147c6338860048401613221565b0381305afa908115610884575f916147e1575b50105f614761565b6147fa915060203d602011611674576116668183610ea5565b5f6147d9565b6040519061480f602083610ea5565b5f8252565b6040906105c293928152816020820152019061058d565b60018060a01b031690604051614842602082610ea5565b5f8152823b156105595761486f925f9283604051809681958294630278811f60e31b845260048401614814565b03925af18015610884576128e55750565b8015612a575761488f82612b1a565b9182821161489c57505050565b633c8097d960e11b5f5260018060a01b031660045260245260445260645ffd5b6040516323b872dd60e01b60208201526001600160a01b03909116602482018190523060448301526064808301859052825292937fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7929091614923906144d5608482610ea5565b61492d8282615482565b61494560405192839260018060a01b03169683612dca565b0390a3565b60405163095ea7b360e01b60208083019182527f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f6001600160a01b031692915f906149ab8461499d898960248401612a66565b03601f198101865285610ea5565b83519082865af15f51903d81614a70575b501590505b614a23575b50506001600160a01b0316906149da614800565b823b1561055957614a04925f9283604051809681958294632db6d39960e01b845260048401614814565b03925af1801561088457614a155750565b806133535f6106f293610ea5565b60405163095ea7b360e01b60208201526001600160a01b03841660248201525f6044820152614a699290614a6490614a5e81606481016144c7565b826158da565b6158da565b5f806149c6565b15159050614a8757506149c1823b15155b5f6149bc565b60016149c19114614a81565b905f911560011715610af157565b81810292918115918404141715610af157565b634e487b7160e01b5f52601260045260245ffd5b8115614ad2570490565b614ab4565b614afe906301e13380614af768056bc75e2d631000009460115490614aa1565b0490614aa1565b0490565b614b0a613ffa565b600160ff1960055416176005557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a142600755565b8015612a5757614b5682613572565b91828211614b6357505050565b63284ff66760e01b5f5260018060a01b031660045260245260445260645ffd5b604051602081017f3d5fcbe10cf86b117683d0d4967b64a0c0fa4bdda7d07499d3c9dc5e388b6940815260208252613e2b604083610ea5565b905f91614bc76140b0565b5c614c5f57614bd890613e886151da565b5f5b8151811015614c5b5760046020614bf7611566614603858761416f565b60405163d570ee4760e01b815292839182905afa908115610884575f91614c3d575b5080614c29575b50600101614bda565b614c369060019295612803565b9390614c20565b614c55915060203d8111611674576116668183610ea5565b5f614c19565b5050565b509050613f25614b83565b91908110156127055760051b81013590609e1981360301821215610559570190565b356105c2816106d6565b81810392915f138015828513169184121617610af157565b9190915f8382019384129112908015821691151617610af157565b600160ff1b8114610af1575f0390565b9035601e19823603018112156105595701602081359101916001600160401b03821161055957813603831361055957565b908060209392818452848401375f828201840152601f01601f1916010190565b82602082016020835252604081019260408160051b83010193835f91609e1982360301945b848410614d60575050505050505090565b90919293949596603f19828203018352873587811215610559576020614dfa60019387839401908135614d92816106d6565b868060a01b0316815283820135614da8816106d6565b868060a01b03168482015260408201356040820152614dec614de1614dd06060850185614cd9565b60a0606086015260a0850191614d0a565b926080810190614cd9565b916080818503910152614d0a565b990193019401929195949390614d4f565b905f5b818110614e4e5750614e497f507d790d4c0157977bb25bd8941f5f91c3118eab68b257c1d1c0825cb0051fd991604051918291339583614d2a565b0390a2565b614e59818385614c6a565b9060a0823603126105595760405191614e7183610e6a565b8035614e7c816106d6565b8352614e8a602082016106e7565b60208401526040810135604084015260608101356001600160401b03811161055957614eb990369083016124c9565b60608401526080810135926001600160401b03841161055957614ee4614eee926001953691016124c9565b60808201526155cf565b01614e0e565b68056bc75e2d6310000091614afe91614aa1565b8015612a5757336001600160a01b038316141580614f63575b614f4f57614f2e82613093565b91828211614f3b57505050565b632e52afbb60e21b5f526108c8935061434d565b630c849df760e41b5f526108c8823361320a565b50604051636eb1769f60e11b815260208180614f83338760048401613221565b0381305afa80156108845782915f91614f9e575b5010614f21565b614fb7915060203d602011611674576116668183610ea5565b5f614f97565b9182519060018201809211610af157614fd5826140e9565b91614fe36040519384610ea5565b808352614ff2601f19916140e9565b013660208401375f5b8451811015615035576001906001600160a01b03615019828861416f565b5116615025828661416f565b90838060a01b0316905201614ffb565b509261504590929192518361416f565b6001600160a01b03909116905290565b9190615062828285615743565b93600481101561509f57600180911614928361508a575b50505015158101809111610af15790565b909180935015614ad2570915155f8080615079565b634e487b7160e01b5f52602160045260245ffd5b6001600160a01b03165f818152600160205260409020919290916150d8908490612f7c565b545f1981106150e8575b50505050565b81811061512457821561078e576001600160a01b0384161561077b5761511a925f526001602052039160405f20612f7c565b555f8080806150e2565b83637dc7a0d960e11b5f5260018060a01b031660045260245260445260645ffd5b916001600160a01b038316918215614521576001600160a01b0381169384156151c75761517181612f63565b548381106151b1579161519f91615199855f516020615f385f395f51905f5296950391612f63565b55612f63565b805482019055604051908152602090a3565b63391434e360e21b5f526108c89184919061434d565b63ec442f0560e01b5f525f60045260245ffd5b60405190600e548083528260208101600e5f5260205f20925f5b8181106152095750506106f292500383610ea5565b84548352600194850194879450602090930192016151f4565b5f52600f60205260405f2054151590565b61523b614b83565b5d600161398e6140b0565b905f905b82518210156152d15760018201808311610af1575b83518110156152c6576001906020615277858761416f565b5101516020615286838861416f565b51015110615295575b0161525f565b61529f818661416f565b516152aa858761416f565b516152b5838861416f565b526152c0858761416f565b5261528f565b50906001019061524a565b915050565b604051602081017f8f2b8f2fcb6f2e256bfd8c09fcca564574482705250cb5c8dbe56c4f4fce37c8815260208252613e2b604083610ea5565b604051602081017f05abb041f8dc8945baa4f2792e2109e9d9e22dea3aa665ccf2f030209c7415ad815260208252613e2b604083610ea5565b6106f2906153546152d6565b61535c61530f565b906153656142b4565b92615861565b604051602081017fb4b00da68d43fac77a22bb187c63cb88989e294cfebeb79b3789ae1629639d98815260208252613e2b604083610ea5565b604051602081017f5720a3c83eb8242bbe1a4159c3b45ed663cd9e207a02bdea64844c6c583da9dd815260208252613e2b604083610ea5565b6153e56142ed565b5c906153f082614100565b915f5b8181106153fe575050565b8061540d60019261440861536b565b5c61541a826144086153a4565b5c6040519161542883610e8a565b848060a01b031682526020820152615440828761416f565b5261544b818661416f565b50016153f3565b61545a613e36565b5d600161398e613df2565b6106f2906154716153a4565b61547961536b565b906153656142ed565b6001600160a01b038116919082156151c75760025490828201809211610af1575f926154c16020925f516020615f385f395f51905f5294600255612f63565b818154019055604051908152a3565b60405163dbd5edc760e01b81526001600160a01b03821690602081600481855afa908115610884575f91615576575b50615563576020600491604051928380926278744560e21b82525afa908115610884575f91615544575b506155315750565b63ca4a18b360e01b5f526108c8906107bf565b61555d915060203d602011611674576116668183610ea5565b5f615529565b632a4d8fbb60e01b5f526108c8826107bf565b61558f915060203d602011611674576116668183610ea5565b5f6154ff565b90600954808311156155c0578203918211610af157116155b157565b633b5391f960e01b5f5260045ffd5b63ff105df960e01b5f5260045ffd5b6020810180519192916155ea906001600160a01b0316611566565b8351909390615601906001600160a01b0316611566565b9160408201515f1981145f1461572357506040516278744560e21b81526020816004816001600160a01b0388165afa801561088457615668915f91615704575b5080925b8451615662906001600160a01b031691516001600160a01b031690565b90615a94565b61567185613b80565b6040516278744560e21b81526001600160a01b03909616956020816004818a5afa801561088457836156ab9184935f916156e55750612803565b116156d15750606082015160809092015193946106f294936001600160a01b0316615bea565b6316e05b4760e21b5f526108c8918661434d565b6156fe915060203d602011611674576116668183610ea5565b5f613ee9565b61571d915060203d602011611674576116668183610ea5565b5f615641565b615668908092615645565b8054821015612705575f5260205f2001905f90565b9161574e8284615c77565b92909384156157c157848311156157b45790829109815f0382168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b6011600384150218615c8a565b5050906105c29250614ac8565b6001600160a01b038116919082615818575090600254828101809111610af1575f925f516020615f385f395f51905f52916002555b600280548290039055604051908152602090a3565b61582181612f63565b5482811061584d57915f516020615f385f395f51905f5291615847825f96950391612f63565b55615803565b63391434e360e21b5f526108c8929161434d565b91935f5b83518110156158b1578061587b600192856158ba565b6020615887838861416f565b510151905d61589681886158ba565b828060a01b036158a6838861416f565b515116905d01615865565b5093505051905d565b906040519060208201928352604082015260408152612e0a606082610ea5565b905f602091828151910182855af11561271f575f513d61592957506001600160a01b0381163b155b6159095750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415615902565b9161594b9183549060031b91821b915f19901b19161790565b9055565b80548015615976575f190190615965828261572e565b8154905f199060031b1b1916905555565b634e487b7160e01b5f52603160045260245ffd5b5f818152600f6020526040902054908115615a25575f19820190828211610af157600e545f19810193908411610af15783835f956159e495036159ea575b5050506159d5600e61594f565b600f905f5260205260405f2090565b55600190565b6159d5615a1691615a0c615a02615a1c95600e61572e565b90549060031b1c90565b928391600e61572e565b90615932565b555f80806159c8565b50505f90565b5f818152600f6020526040902054615a8f57600e54600160401b811015610e8557615a78615a62826001859401600e55600e61572e565b819391549060031b91821b915f19901b19161790565b9055600e54905f52600f60205260405f2055600190565b505f90565b90918015615bd7576001600160a01b0383168015615bc4576001600160a01b03831615615bb157615acb615ac785613650565b1590565b615b9e57615adb615ac784613650565b615b8b5760206004916040519283809263dbd5edc760e01b82525afa908115610884575f91615b6c575b5015615b5957615b16908383615d7e565b9190949293828211615b4557505050828211615b3157505050565b63016b606760e21b5f526108c8935061434d565b637d7bf8e160e01b5f526108c8935061434d565b630b9cb3f960e11b5f526108c8836107bf565b615b85915060203d602011611674576116668183610ea5565b5f615b05565b63c80e655f60e01b5f526108c8836107bf565b63c80e655f60e01b5f526108c8846107bf565b632767039f60e01b5f526108c8836107bf565b632767039f60e01b5f526108c8846107bf565b630a16952b60e21b5f526108c8836107bf565b9192916001600160a01b031690813b15610559575f8094615c51615c3f976040519889978896879563c38a6f0b60e01b8752600487015260018060a01b0316602486015260806044860152608485019061058d565b8381036003190160648501529061058d565b03925af1801561088457615c625750565b80615c6e5f8093610ea5565b80031261055957565b905f198183099102908180821091030391565b634e487b715f526020526024601cfd5b604051602081017fd6ca653d633b7805e7a09d886857226f949d3ea7294700814274fe35008a00e0815260208252613e2b604083610ea5565b604051602081017f546815194d984b29286d5b6f432093bc0b41f225a5a8e27984a1c97f6c2c975e815260208252613e2b604083610ea5565b604051602081017fd06b3f94ec7e002c6893cd0c8991bb46b1dd8a8de8b084874f6c9702acf78346815260208252613e2b604083610ea5565b604051602081017f880bdf4b1569fe9025df88e4aa4034209a7b27fcb16c5e9fc1f6231643aa93e4815260208252613e2b604083610ea5565b9290615d9e615d8b615c9a565b6001600160a01b039092169182906158ba565b91615dbd615daa615cd3565b6001600160a01b039096169586906158ba565b92615dca83614408615d0c565b93615dd787614408615d45565b855c95815c958715615e63575b50508415615e0f575b50615e089650615dfe86835c612803565b968796825c612803565b9586925d5d565b93506020600497604051988980926318ca2a4f60e11b82525afa801561088457615e08975f91615e44575b5080945d5f615ded565b615e5d915060203d602011611674576116668183610ea5565b5f615e3a565b60405163ad5a356f60e01b8152919750602090829060049082905afa908115610884575f91615e98575b5080965d5f80615de4565b615eb1915060203d602011611674576116668183610ea5565b5f615e8d56fee68a55afda2dca8343871fe0e5575a383291a40ae7d53e4dee12faf79cde144eb00be3d6a5434b97b328543d1486d56adcb7e74080170d1cdd7e0306c3d9ba3d7935bd0ae54bc31f548c14dba4d37c5c64b3f8ca900cb468fb8abd54d5894f550d186688925976bbe6755ae984501c8e3e2b103a7af59fd803ab9c6d891ae7e0ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef55435dd261a4b9b3364963f7738a7a662ad9c84396d64be3365284bb7f0a5041a2646970667358221220ffe78f20c50967397587665653faf23d405ed3baa128f0956bc473b97bf57edd64736f6c634300081c0033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000001c00000000000000000000000005a4ac204864a36e9820a3663836299ed963f085700000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000025800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000184c617a795661756c745f4c6f7765725269736b5f5553444300000000000000000000000000000000000000000000000000000000000000000000000000000002222200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064c56555344430000000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : params (tuple):
Arg [1] : name (string): LazyVault_LowerRisk_USDC
Arg [2] : details (string): ""
Arg [3] : symbol (string): LVUSDC
Arg [4] : configurationManager (address): 0x5A4ac204864a36e9820A3663836299ed963F0857
Arg [5] : accessManager (address): 0x38fB5a7fa70103dCd9e8A969f3975A77E0fE755f
Arg [6] : asset (address): 0xb88339CB7199b77E23DB6E890353E22632Ba630f
Arg [7] : initialMinimumBufferBalance (uint256): 0
Arg [8] : initialRebalanceCooldown (uint256): 600
Arg [9] : depositCap (uint256): 0
Arg [10] : initialTipRate (uint256): 1000000000000000000
-----Encoded View---------------
17 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000020
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000140
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [3] : 00000000000000000000000000000000000000000000000000000000000001c0
Arg [4] : 0000000000000000000000005a4ac204864a36e9820a3663836299ed963f0857
Arg [5] : 00000000000000000000000038fb5a7fa70103dcd9e8a969f3975a77e0fe755f
Arg [6] : 000000000000000000000000b88339cb7199b77e23db6e890353e22632ba630f
Arg [7] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000258
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000000
Arg [10] : 0000000000000000000000000000000000000000000000000de0b6b3a7640000
Arg [11] : 0000000000000000000000000000000000000000000000000000000000000018
Arg [12] : 4c617a795661756c745f4c6f7765725269736b5f555344430000000000000000
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [14] : 2222000000000000000000000000000000000000000000000000000000000000
Arg [15] : 0000000000000000000000000000000000000000000000000000000000000006
Arg [16] : 4c56555344430000000000000000000000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in HYPE
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ 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.