Overview
S Balance
S Value
$0.00More Info
Private Name Tags
ContractCreator
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
Treasury
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 200 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import { IPriceOracle } from "./interfaces/IPriceOracle.sol"; import { ITreasury } from "./interfaces/ITreasury.sol"; import { TreasuryStateLibrary } from "./libs/TreasuryStateLibrary.sol"; import { TreasuryHarvestLibrary } from "./libs/TreasuryHarvestLibrary.sol"; import { TreasuryRebalanceLibrary } from "./libs/TreasuryRebalanceLibrary.sol"; import { Currency, CurrencyLibrary } from "./types/Currency.sol"; import { GroupId } from "./types/GroupId.sol"; import { CacheLibrary } from "./libs/CacheLibrary.sol"; import { Address, AddressLibrary } from "./types/Address.sol"; import { FxStableMath } from "./libs/math/FxStableMath.sol"; import { CustomRevert } from "./libs/CustomRevert.sol"; import { DTreasury } from "./declarations/DTreasury.sol"; import { GroupState } from "./types/CommonTypes.sol"; import { GroupStateHelper, GroupSettings } from "./types/GroupStateHelper.sol"; interface IToken { function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; } /** * @title Treasury Contract * @notice Manages the treasury operations including minting, redeeming tokens, handling collateral, and interacting with strategies. */ contract Treasury is AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, ITreasury { using TreasuryStateLibrary for DTreasury.TreasuryState; using FxStableMath for FxStableMath.SwapState; using CacheLibrary for CacheLibrary.Storage; using CurrencyLibrary for Currency; using AddressLibrary for Address; using GroupStateHelper for GroupSettings; using CustomRevert for bytes4; /// @notice Cache storage for group states CacheLibrary.Storage private cacheStorage; /// @notice Address of the protocol contract address public protocol; /// @notice Address of the fee collector address public feeCollector; /// @notice Role identifier for the protocol role bytes32 public constant PROTOCOL_ROLE = keccak256("PROTOCOL_ROLE"); /// @notice Role identifier for the cache updater role bytes32 public constant CACHE_UPDATER_ROLE = keccak256("CACHE_UPDATER_ROLE"); /// @notice Role identifier for the pauser role bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /// @notice Role identifier for the harvester role bytes32 public constant HARVESTER_ROLE = keccak256("HARVESTER_ROLE"); /// @notice Precision constant used in calculations (1e18) uint256 private constant PRECISION = 1e18; /// @notice Small constant to avoid rounding issues uint256 private constant DUST = 1e2; /// @notice Mapping of treasury states by group ID mapping(GroupId => DTreasury.TreasuryState) public treasuryStates; /// @notice Mapping of last harvest timestamps by group ID mapping(GroupId => uint256) public lastHarvestTimestamp; /** * @dev Modifier to validate if a group is properly configured for the treasury. * @param groupId The group identifier. */ modifier validateGroup(GroupId groupId) { GroupState memory groupState = cacheStorage.getGroupState(groupId); if (groupState.extended.treasury.toAddress() != address(this)) ITreasury.InvalidGroupConfiguration.selector.revertWith(groupId); _; } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /** * @notice Doesn't the contract to receive Ether. * @dev Reverts with NotPermitted error. */ receive() external payable { ITreasury.NotPermitted.selector.revertWith(); } /** * @notice Fallback function to handle calls to non-existent functions. * @dev Reverts with NotPermitted error. */ fallback() external payable { ITreasury.NotPermitted.selector.revertWith(); } /** * @notice Initializes the Treasury contract. * @param _protocol Address of the protocol. * @param _feeCollector Address of the fee collector. * @param _admin Address of the admin. */ function initialize(address _protocol, address _feeCollector, address _admin) external initializer { if (_protocol == address(0) || _admin == address(0) || _feeCollector == address(0)) { ITreasury.ZeroAddress.selector.revertWith(); } __AccessControl_init(); __ReentrancyGuard_init(); __Pausable_init(); _grantRole(DEFAULT_ADMIN_ROLE, _admin); _grantRole(PAUSER_ROLE, _admin); _grantRole(PROTOCOL_ROLE, _protocol); _grantRole(CACHE_UPDATER_ROLE, _protocol); _grantRole(CACHE_UPDATER_ROLE, _admin); _grantRole(HARVESTER_ROLE, _admin); protocol = _protocol; feeCollector = _feeCollector; } /** * @notice Forces the update of the group cache. * @param tokenRegistry The token registry address. * @param groupId The group identifier. */ function forceUpdateGroupCache(address tokenRegistry, GroupId groupId) external nonReentrant onlyRole(CACHE_UPDATER_ROLE) { _forceUpdateGroupCache(tokenRegistry, groupId); } /** * @dev Internal function to force update the group cache. * @param tokenRegistry The token registry address. * @param groupId The group identifier. */ function _forceUpdateGroupCache(address tokenRegistry, GroupId groupId) private { cacheStorage.forceUpdate(tokenRegistry, groupId); GroupState memory groupState = cacheStorage.getGroupState(groupId); if (groupState.extended.treasury.toAddress() != address(this)) ITreasury.InvalidGroupConfiguration.selector.revertWith(groupId); } /** * @notice Initializes a group within the treasury. * @param tokenRegistry The token registry address. * @param groupId The group identifier. * @param params Parameters for group initialization. */ function initializeGroup( address tokenRegistry, GroupId groupId, DTreasury.GroupUpdateParams calldata params ) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { // Validate input parameters if (tokenRegistry == address(0)) ITreasury.ZeroAddress.selector.revertWith(); if (params.baseTokenCaps == 0) ITreasury.InvalidBaseTokenCap.selector.revertWith(groupId); // Check if the group is already initialized DTreasury.TreasuryState storage state = treasuryStates[groupId]; if (state.inited) ITreasury.GroupAlreadyInitialized.selector.revertWith(groupId); GroupState memory groupState = cacheStorage.getGroupState(groupId); // Force update if the treasury doesn't match if (groupState.extended.treasury.toAddress() != address(this)) _forceUpdateGroupCache(tokenRegistry, groupId); groupState = cacheStorage.getGroupState(groupId); // Update base token caps in state state.updateBaseTokenCaps(params.baseTokenCaps); (, uint256 _newPrice) = state.fetchBaseTokenPrice(groupState); state.updateBaseTokenPrice(_newPrice); uint256 baseInNormalized = TreasuryStateLibrary.normalizeDecimals(params.baseIn, _getTokenDecimalsFromGroup(groupState, "base")); state.totalBaseTokens = baseInNormalized; state.initializeGroupEMALeverageRatio(); state.inited = true; // Mint 50/50 aToken and xToken uint256 halfTokenOut = (baseInNormalized * _newPrice) / (2 * PRECISION); if (params.beta) halfTokenOut = (baseInNormalized) / (2); // this is for when beta = 0, doesn't affect the math uint256 aTokenOutDenorm = TreasuryStateLibrary.denormalizeDecimals(halfTokenOut, _getTokenDecimalsFromGroup(groupState, "a")); uint256 xTokenOutDenorm = TreasuryStateLibrary.denormalizeDecimals(halfTokenOut, _getTokenDecimalsFromGroup(groupState, "x")); groupState.core.baseToken.safeTransferFrom(_msgSender(), address(this), params.baseIn); IToken(groupState.core.xToken.toAddress()).mint(address(this), xTokenOutDenorm); IToken(groupState.core.aToken.toAddress()).mint(address(this), aTokenOutDenorm); emit Settle(groupId, 0, _newPrice); emit GroupInitialized(groupId, _newPrice); } /** * @notice Gets the collateral ratio for a group. * @param groupId The group identifier. * @return The collateral ratio. */ function collateralRatio(GroupId groupId) external view override validateGroup(groupId) returns (uint256) { GroupState memory groupState = cacheStorage.getGroupState(groupId); return treasuryStates[groupId].getCollateralRatio(groupState); } /** * @notice Checks if a group is under-collateralized. * @param groupId The group identifier. * @return True if under-collateralized, false otherwise. */ function isUnderCollateral(GroupId groupId) public view override validateGroup(groupId) returns (bool) { GroupState memory groupState = cacheStorage.getGroupState(groupId); return treasuryStates[groupId].isUnderCollateral(groupState); } /** * @notice Gets the current base token price for a group. * @param groupId The group identifier. * @return The current base token price. */ function currentBaseTokenPrice(GroupId groupId) external view override validateGroup(groupId) returns (uint256) { GroupState memory groupState = cacheStorage.getGroupState(groupId); (bool isValid, uint256 baseTokenPrice) = IPriceOracle(groupState.extended.priceOracle.toAddress()).getPrice( groupState.core.baseToken.toAddress() ); if (!isValid) ITreasury.InvalidPrice.selector.revertWith(groupId); return baseTokenPrice; } /** * @notice Gets the current EMA leverage ratio for a group. * @param groupId The group identifier. * @return The current EMA leverage ratio. */ function leverageRatio(GroupId groupId) external view override validateGroup(groupId) returns (uint256) { uint256 ratio = treasuryStates[groupId].getEMAValue(); if (ratio == 0) ITreasury.InvalidRatio.selector.revertWith(groupId); return ratio; } /** * @notice Gets the total base tokens for a group. * @param groupId The group identifier. * @return The total base tokens. */ function totalBaseToken(GroupId groupId) external view override validateGroup(groupId) returns (uint256) { return treasuryStates[groupId].totalBaseTokens; } /** * @notice Returns the amount of base token that can be harvested. * @param groupId The group identifier. * @return The harvestable amount. */ function harvestable(GroupId groupId) public view validateGroup(groupId) returns (uint256) { // Retrieve group state GroupState memory groupState = cacheStorage.getGroupState(groupId); // Get the total base tokens recorded in the treasury uint256 _totalBaseToken = treasuryStates[groupId].totalBaseTokens; if (_totalBaseToken < DUST) return 0; // Get the actual balance of base tokens at this contract's address uint256 balance = groupState.core.baseToken.balanceOf(address(this)); // Normalize the balance to account for decimal differences uint256 balanceNormalized = TreasuryStateLibrary.normalizeDecimals(balance, _getTokenDecimalsFromGroup(groupState, "base")); // Return the harvestable amount if (balanceNormalized <= _totalBaseToken) { return 0; } else { uint256 harvestableAmount = TreasuryStateLibrary.denormalizeDecimals( balanceNormalized - _totalBaseToken, _getTokenDecimalsFromGroup(groupState, "base") ); return harvestableAmount; } } /** * @notice Calculates the maximum mintable AToken. * @param groupId The group identifier. * @param _newCollateralRatio The new collateral ratio. * @return _maxBaseIn The maximum base tokens input. * @return _maxATokenMintable The maximum AToken mintable. */ function maxMintableAToken( GroupId groupId, uint256 _newCollateralRatio ) external view override validateGroup(groupId) returns (uint256 _maxBaseIn, uint256 _maxATokenMintable) { GroupState memory groupState = cacheStorage.getGroupState(groupId); (_maxBaseIn, _maxATokenMintable) = treasuryStates[groupId].maxMintableAToken(groupState, _newCollateralRatio); // Denormalize outputs _maxBaseIn = TreasuryStateLibrary.denormalizeDecimals(_maxBaseIn, _getTokenDecimalsFromGroup(groupState, "base")); _maxATokenMintable = TreasuryStateLibrary.denormalizeDecimals(_maxATokenMintable, _getTokenDecimalsFromGroup(groupState, "a")); } /** * @notice Calculates the maximum redeemable AToken. * @param groupId The group identifier. * @param _newCollateralRatio The new collateral ratio. * @return _maxBaseOut The maximum base tokens output. * @return _maxATokenRedeemable The maximum AToken redeemable. */ function maxRedeemableAToken( GroupId groupId, uint256 _newCollateralRatio ) external view override validateGroup(groupId) returns (uint256 _maxBaseOut, uint256 _maxATokenRedeemable) { if (_newCollateralRatio <= PRECISION) ITreasury.ErrorCollateralRatioTooSmall.selector.revertWith(groupId); GroupState memory groupState = cacheStorage.getGroupState(groupId); (_maxBaseOut, _maxATokenRedeemable) = treasuryStates[groupId].maxRedeemableAToken(groupState, _newCollateralRatio); // Denormalize outputs _maxBaseOut = TreasuryStateLibrary.denormalizeDecimals(_maxBaseOut, _getTokenDecimalsFromGroup(groupState, "base")); _maxATokenRedeemable = TreasuryStateLibrary.denormalizeDecimals(_maxATokenRedeemable, _getTokenDecimalsFromGroup(groupState, "a")); } /** * @notice Mints AToken. * @param groupId The group identifier. * @param _baseIn The amount of base tokens input. * @param _recipient The recipient address. * @return _aTokenOut The amount of AToken minted. */ function mintAToken( GroupId groupId, uint256 _baseIn, address _recipient ) external override nonReentrant whenNotPaused onlyRole(PROTOCOL_ROLE) validateGroup(groupId) returns (uint256 _aTokenOut) { if (isUnderCollateral(groupId)) ITreasury.ErrorUnderCollateral.selector.revertWith(groupId); DTreasury.TreasuryState storage state = treasuryStates[groupId]; GroupState memory groupState = cacheStorage.getGroupState(groupId); uint256 baseInNormalized = TreasuryStateLibrary.normalizeDecimals(_baseIn, _getTokenDecimalsFromGroup(groupState, "base")); if (state.totalBaseTokens + baseInNormalized > state.baseTokenCaps) ITreasury.ErrorExceedTotalCap.selector.revertWith(groupId); FxStableMath.SwapState memory swapState = state.loadSwapState(groupState); state.updateEMALeverageRatio(swapState); state.totalBaseTokens += baseInNormalized; // Transfer base tokens from the sender groupState.core.baseToken.safeTransferFrom(_msgSender(), address(this), _baseIn); _aTokenOut = swapState.mintAToken(baseInNormalized); // Denormalize _aTokenOut to aToken decimals _aTokenOut = TreasuryStateLibrary.denormalizeDecimals(_aTokenOut, _getTokenDecimalsFromGroup(groupState, "a")); IToken(groupState.core.aToken.toAddress()).mint(_recipient, _aTokenOut); } /** * @notice Mints XToken. * @param groupId The group identifier. * @param _baseIn The amount of base tokens input. * @param _recipient The recipient address. * @return _xTokenOut The amount of XToken minted. */ function mintXToken( GroupId groupId, uint256 _baseIn, address _recipient ) external override nonReentrant whenNotPaused onlyRole(PROTOCOL_ROLE) validateGroup(groupId) returns (uint256 _xTokenOut) { if (isUnderCollateral(groupId)) ITreasury.ErrorUnderCollateral.selector.revertWith(groupId); DTreasury.TreasuryState storage state = treasuryStates[groupId]; GroupState memory groupState = cacheStorage.getGroupState(groupId); uint256 baseInNormalized = TreasuryStateLibrary.normalizeDecimals(_baseIn, _getTokenDecimalsFromGroup(groupState, "base")); if (state.totalBaseTokens + baseInNormalized > state.baseTokenCaps) ITreasury.ErrorExceedTotalCap.selector.revertWith(groupId); FxStableMath.SwapState memory swapState = state.loadSwapState(groupState); state.updateEMALeverageRatio(swapState); state.totalBaseTokens += baseInNormalized; // Transfer base tokens from the sender groupState.core.baseToken.safeTransferFrom(_msgSender(), address(this), _baseIn); _xTokenOut = swapState.mintXToken(baseInNormalized); // Denormalize _xTokenOut to xToken decimals _xTokenOut = TreasuryStateLibrary.denormalizeDecimals(_xTokenOut, _getTokenDecimalsFromGroup(groupState, "x")); IToken(groupState.core.xToken.toAddress()).mint(_recipient, _xTokenOut); } /** * @notice Redeems tokens. * @param groupId The group identifier. * @param _aTokenIn The amount of AToken input. * @param _xTokenIn The amount of XToken input. * @param _owner The owner address. * @return _baseOut The amount of base tokens output. */ function redeem( GroupId groupId, uint256 _aTokenIn, uint256 _xTokenIn, address _owner ) external override nonReentrant whenNotPaused onlyRole(PROTOCOL_ROLE) validateGroup(groupId) returns (uint256 _baseOut) { GroupState memory groupState = cacheStorage.getGroupState(groupId); DTreasury.TreasuryState storage treasuryState = treasuryStates[groupId]; uint256 aTokenInNormalized = TreasuryStateLibrary.normalizeDecimals(_aTokenIn, _getTokenDecimalsFromGroup(groupState, "a")); uint256 xTokenInNormalized = TreasuryStateLibrary.normalizeDecimals(_xTokenIn, _getTokenDecimalsFromGroup(groupState, "x")); uint256 balanceWithDust = DUST + groupState.core.xToken.balanceOf(_owner); // Check if the owner has enough tokens if (_xTokenIn > 0 && balanceWithDust < _xTokenIn) ITreasury.ErrorInsufficientBalance.selector.revertWith(groupId, groupState.core.xToken.toAddress()); FxStableMath.SwapState memory swapState = treasuryState.loadSwapState(groupState); treasuryState.updateEMALeverageRatio(swapState); if (swapState.xNav == 0) { if (_xTokenIn > 0) ITreasury.ErrorUnderCollateral.selector.revertWith(groupId); /// @dev only redeem aToken proportionally when under collateral. _baseOut = (aTokenInNormalized * treasuryState.totalBaseTokens) / swapState.aSupply; } else { _baseOut = swapState.redeem(aTokenInNormalized, xTokenInNormalized); } // Denormalize _baseOut to base token decimals _baseOut = TreasuryStateLibrary.denormalizeDecimals(_baseOut, _getTokenDecimalsFromGroup(groupState, "base")); // burn tokens & transfer to the owner if (_aTokenIn > 0) { groupState.core.aToken.safeTransferFrom(_owner, address(this), _aTokenIn); IToken(groupState.core.aToken.toAddress()).burn(address(this), _aTokenIn); } if (_xTokenIn > 0) { groupState.core.xToken.safeTransferFrom(_owner, address(this), _xTokenIn); IToken(groupState.core.xToken.toAddress()).burn(address(this), _xTokenIn); } TreasuryStateLibrary.transferBaseToken( address(this), _getTokenDecimalsFromGroup(groupState, "base"), groupState.core.baseToken, groupState.extended.strategy.toAddress(), treasuryState, _baseOut, _owner ); } /** * @notice Transfers base tokens to the strategy. * @param groupId The group identifier. * @param _amount The amount to transfer. */ function transferToStrategy(GroupId groupId, uint256 _amount) external override nonReentrant validateGroup(groupId) { GroupState memory groupState = cacheStorage.getGroupState(groupId); if (_msgSender() != groupState.extended.strategy.toAddress()) ITreasury.OnlyStrategy.selector.revertWith(); DTreasury.TreasuryState storage state = treasuryStates[groupId]; uint256 amountNormalized = TreasuryStateLibrary.normalizeDecimals(_amount, _getTokenDecimalsFromGroup(groupState, "base")); state.strategyUnderlying += amountNormalized; if (state.totalBaseTokens < amountNormalized) ITreasury.StrategyUnderflow.selector.revertWith(groupId); state.totalBaseTokens -= amountNormalized; groupState.core.baseToken.safeTransfer(_msgSender(), _amount); emit TransferToStrategy(groupId, _amount); } /** * @notice Harvests fees for a group. * @param groupId The group identifier. * @param params The harvest fees parameters. */ function harvestFees( GroupId groupId, TreasuryHarvestLibrary.HarvestParams memory params ) external override nonReentrant validateGroup(groupId) onlyRole(HARVESTER_ROLE) { if (params.sendTokens == true && params.swapRouter == address(0) && params.stablecoin == address(0)) ITreasury.ZeroAddress.selector.revertWith(groupId); GroupState memory groupState = cacheStorage.getGroupState(groupId); DTreasury.TreasuryState storage state = treasuryStates[groupId]; // collect fees uint256 dxTokenBalance = TreasuryHarvestLibrary.collectFees(groupState, groupId); TreasuryHarvestLibrary.harvestFees(groupId, groupState, state, params, dxTokenBalance, feeCollector, protocol); emit HarvestFees(groupId, 0, dxTokenBalance); } /** * @notice Harvests yield for a group. * @param groupId The group identifier. * @param params The harvest yield parameters. */ function harvestYield( GroupId groupId, TreasuryHarvestLibrary.HarvestParams memory params ) external override nonReentrant onlyRole(HARVESTER_ROLE) validateGroup(groupId) { if (block.timestamp < lastHarvestTimestamp[groupId] + 1 days) return; if (params.sendTokens == true && params.swapRouter == address(0) && params.stablecoin == address(0)) ITreasury.ZeroAddress.selector.revertWith(groupId); uint256 harvestableAmount = harvestable(groupId); if (harvestableAmount == 0) ITreasury.ZeroAmount.selector.revertWith(); GroupState memory groupState = cacheStorage.getGroupState(groupId); DTreasury.TreasuryState storage state = treasuryStates[groupId]; lastHarvestTimestamp[groupId] = block.timestamp; TreasuryHarvestLibrary.harvestYield(groupId, groupState, state, params, harvestableAmount, feeCollector, protocol); emit HarvestYield(groupId, harvestableAmount); } /** * @notice Rebalances the protocol when the collateral ratio is low by burning aTokens and converting base tokens to stablecoins. * @dev This function increases the collateral ratio (CR) to enhance protocol security. * @param groupId The identifier of the group. * @param params Parameters for the rebalance up operation. */ function rebalanceUp( GroupId groupId, TreasuryRebalanceLibrary.RebalanceUpParams memory params ) external nonReentrant validateGroup(groupId) onlyRole(DEFAULT_ADMIN_ROLE) { GroupState memory groupState = cacheStorage.getGroupState(groupId); GroupSettings groupSettings = GroupSettings.wrap(groupState.groupSettings); DTreasury.TreasuryState storage state = treasuryStates[groupId]; uint256 stabilityRatio = uint256(GroupStateHelper.getStabilityRatio(groupSettings)); uint256 currentCR = state.getCollateralRatio(groupState); if (params.swapRouter == address(0) || Currency.wrap(params.stablecoin).isZero()) { ITreasury.ZeroAddress.selector.revertWith(); } /** * @dev Ensure that the Target Collateral Ratio (TCR) is greater than 0 and higher than the current Collateral Ratio (currentCR). * The current Collateral Ratio must be lower than the stability ratio and greater than 100% (PRECISION). */ if ( params.targetCollateralRatio == 0 || params.targetCollateralRatio <= currentCR || currentCR >= stabilityRatio || currentCR <= PRECISION ) { ITreasury.InvalidRatio.selector.revertWith(groupId); } TreasuryRebalanceLibrary.rebalanceUp(state, groupState, params); emit RebalanceUpPerformed(groupId, params.targetCollateralRatio); } /** * @notice Rebalances the protocol when the collateral ratio is high by converting stablecoins to base tokens and minting aTokens. * @dev This function decreases the collateral ratio (CR) to improve protocol efficiency. * @param groupId The identifier of the group. * @param params Parameters for the rebalance down operation. */ function rebalanceDown( GroupId groupId, TreasuryRebalanceLibrary.RebalanceDownParams memory params ) external nonReentrant validateGroup(groupId) onlyRole(DEFAULT_ADMIN_ROLE) { GroupState memory groupState = cacheStorage.getGroupState(groupId); GroupSettings groupSettings = GroupSettings.wrap(groupState.groupSettings); DTreasury.TreasuryState storage state = treasuryStates[groupId]; if (params.swapRouter == address(0) || params.stablecoin == address(0)) { ITreasury.ZeroAddress.selector.revertWith(); } if (params.convertAmount == 0) { ITreasury.ZeroAmount.selector.revertWith(); } uint256 stabilityRatio = uint256(GroupStateHelper.getStabilityRatio(groupSettings)); uint256 currentCR = state.getCollateralRatio(groupState); /** * @dev Ensure that the Target Collateral Ratio (TCR) is greater than 0 and lower than the current Collateral Ratio (currentCR). * The current Collateral Ratio must be higher than the stability ratio. */ if (params.targetCollateralRatio == 0 || params.targetCollateralRatio <= stabilityRatio || params.targetCollateralRatio >= currentCR) { ITreasury.InvalidRatio.selector.revertWith(); } TreasuryRebalanceLibrary.rebalanceDown(state, groupState, params); emit RebalanceDownPerformed(groupId, params.targetCollateralRatio); } /** * @notice Updates the base token cap for a group. * @param groupId The group identifier. * @param _baseTokenCap The new base token cap. */ function updateBaseTokenCap(GroupId groupId, uint256 _baseTokenCap) public onlyRole(DEFAULT_ADMIN_ROLE) validateGroup(groupId) { // check if the new base token cap is greater than 0, different from the current one & greater than the total base tokens if ( _baseTokenCap == 0 || _baseTokenCap == treasuryStates[groupId].baseTokenCaps || _baseTokenCap < treasuryStates[groupId].totalBaseTokens ) { ITreasury.InvalidBaseTokenCap.selector.revertWith(groupId); } uint256 _oldBaseTokenCap = treasuryStates[groupId].baseTokenCaps; treasuryStates[groupId].updateBaseTokenCaps(_baseTokenCap); emit UpdateBaseTokenCap(groupId, _oldBaseTokenCap, _baseTokenCap); } /** * @notice Gets the treasury state for a group. * @param groupId The group identifier. * @return The treasury state. * @dev Only for admin use. */ function getTreasuryState(GroupId groupId) external view override validateGroup(groupId) returns (DTreasury.TreasuryState memory) { DTreasury.TreasuryState memory state = treasuryStates[groupId]; return DTreasury.TreasuryState({ emaLeverageRatio: state.emaLeverageRatio, inited: state.inited, baseTokenPrice: state.baseTokenPrice, totalBaseTokens: state.totalBaseTokens, baseTokenCaps: state.baseTokenCaps, strategyUnderlying: state.strategyUnderlying, lastSettlementTimestamp: state.lastSettlementTimestamp }); } /** * @notice Updates the fee collector address. * @param _newFeeCollector The new fee collector address. */ function updateFeeCollector(address _newFeeCollector) external onlyRole(DEFAULT_ADMIN_ROLE) { if (_newFeeCollector == address(0)) ITreasury.ZeroAddress.selector.revertWith(); address oldFeeCollector = feeCollector; feeCollector = _newFeeCollector; emit UpdateFeeCollector(oldFeeCollector, _newFeeCollector); } /** * @notice Pauses the contract. */ function pause() external onlyRole(PAUSER_ROLE) { _pause(); } /** * @notice Unpauses the contract. */ function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Prevents renouncing roles for security * @dev Overrides the default renounceRole function to prevent accidental role removal */ function renounceRole(bytes32, address) public virtual override { ITreasury.RenounceRoleProhibited.selector.revertWith(); } /** * @notice Checks if the contract supports a specific interface. * @param interfaceId The interface identifier. * @return True if the interface is supported, false otherwise. */ function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return interfaceId == type(ITreasury).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Helper function to get token decimals from group settings. * @param groupState The group state. * @param tokenType The type of token ("base", "a", or "x"). * @return The token decimals. */ function _getTokenDecimalsFromGroup(GroupState memory groupState, string memory tokenType) private pure returns (uint8) { if (keccak256(abi.encodePacked(tokenType)) == keccak256(abi.encodePacked("base"))) { return GroupSettings.wrap(groupState.groupSettings).getBaseTokenDecimals(); } else if (keccak256(abi.encodePacked(tokenType)) == keccak256(abi.encodePacked("a"))) { return GroupSettings.wrap(groupState.groupSettings).getATokenDecimals(); } else if (keccak256(abi.encodePacked(tokenType)) == keccak256(abi.encodePacked("x"))) { return GroupSettings.wrap(groupState.groupSettings).getXTokenDecimals(); } else ITreasury.InvalidTokenType.selector.revertWith(); } // slither-disable-next-line unused-state uint256[50] private __gap; // Storage gap for upgradeability }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(account), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @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 override 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 override 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 override 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 `account`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * May emit a {RoleGranted} event. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @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 Grants `role` to `account`. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _status == _ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable { /** * @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); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @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()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; /** * @title IPriceOracle * @notice Interface for the PriceOracle contract, managing and updating token price feeds. */ interface IPriceOracle { /** * @dev Emitted when a price feed is added for a token. * @param token The address of the token. * @param feed The address of the Chainlink price feed. */ event FeedAdded(address indexed token, address indexed feed); /** * @dev Emitted when a price feed is removed for a token. * @param token The address of the token. */ event FeedRemoved(address indexed token); /** * @dev Emitted when a price feed is updated for a token. * @param token The address of the token. * @param oldFeed The address of the old price feed. * @param newFeed The address of the new price feed. */ event FeedUpdated(address indexed token, address indexed oldFeed, address indexed newFeed); // Custom Errors error ZeroAddress(); error InvalidAddress(); error InvalidOperation(); error InvalidAmount(); error StalePrice(); error InvalidInput(); error DuplicateEntry(); /** * @notice Gets the latest price data for a specified token. * @param token The address of the token. * @return isValid Whether the price is valid. * @return price The last updated price (18 decimals). */ function getPrice(address token) external view returns (bool isValid, uint256 price); /** * @notice gets the token decimals from the feed */ function getFeedDecimals(address token) external view returns (uint8 decimals); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { GroupId } from "../types/GroupId.sol"; import { DTokenRegistry } from "../declarations/DTokenRegistry.sol"; import { DTreasury } from "../declarations/DTreasury.sol"; import { TreasuryHarvestLibrary } from "../libs/TreasuryHarvestLibrary.sol"; interface ITreasury { // Events event HarvestYield(GroupId indexed groupId, uint256 indexed yieldBaseTokens); event HarvestFees(GroupId indexed groupId, uint256 indexed xTokenAmount, uint256 indexed aTokenAmount); event FeesDistributed(GroupId indexed groupId, uint256 indexed xTokenAmount, uint256 indexed baseTokenAmount); event UpdateBaseTokenCap(GroupId indexed groupId, uint256 indexed oldBaseTokenCap, uint256 indexed newBaseTokenCap); event Settle(GroupId indexed groupId, uint256 indexed oldPrice, uint256 indexed newPrice); event UpdateFeeCollector(address indexed oldFeeCollector, address indexed newFeeCollector); event GroupInitialized(GroupId indexed groupId, uint256 indexed baseTokenPrice); event RebalanceUpPerformed(GroupId indexed groupId, uint256 indexed newCollateralRatio); event RebalanceDownPerformed(GroupId indexed groupId, uint256 indexed newCollateralRatio); event TransferToStrategy(GroupId indexed groupId, uint256 indexed amount); // Custom Errors error ZeroAddress(); error ZeroAmount(); error OnlyStrategy(); error GroupAlreadyInitialized(GroupId groupId); error ErrorUnderCollateral(GroupId groupId); error ErrorExceedTotalCap(GroupId groupId); error ErrorInvalidTwapPrice(GroupId groupId); error NotPermitted(); error InvalidGroupConfiguration(GroupId groupId); error InvalidRate(GroupId groupId, address rateProvider); error InvalidRatio(GroupId groupId); error InvalidPrice(GroupId groupId); error InvalidBaseTokenCap(GroupId groupId); error ErrorInsufficientBalance(GroupId groupId, address token); error ErrorSwapFailed(); error ErrorDistributingYield(GroupId groupId); error ErrorWithdrawFromStrategy(); error ErrorCollateralRatioTooSmall(GroupId groupId); error MaximumAmountExceeded(GroupId groupId, uint256 maxAmount); error StrategyUnderflow(GroupId groupId); error InvalidTokenType(); error RenounceRoleProhibited(); // View Functions function collateralRatio(GroupId groupId) external view returns (uint256); function isUnderCollateral(GroupId groupId) external view returns (bool); function leverageRatio(GroupId groupId) external view returns (uint256); function currentBaseTokenPrice(GroupId groupId) external view returns (uint256); // function isBaseTokenPriceValid(GroupId groupId) external view returns (bool _isValid); function totalBaseToken(GroupId groupId) external view returns (uint256); function maxMintableAToken( GroupId groupId, uint256 _newCollateralRatio ) external view returns (uint256 _maxBaseIn, uint256 _maxATokenMintable); function maxRedeemableAToken( GroupId groupId, uint256 _newCollateralRatio ) external view returns (uint256 _maxBaseOut, uint256 _maxATokenRedeemable); // State-Changing Functions function mintAToken(GroupId groupId, uint256 _baseIn, address _recipient) external returns (uint256 _aTokenOut); function mintXToken(GroupId groupId, uint256 _baseIn, address _recipient) external returns (uint256 _xTokenOut); function redeem(GroupId groupId, uint256 _aTokenIn, uint256 _xTokenIn, address _owner) external returns (uint256 _baseOut); function transferToStrategy(GroupId groupId, uint256 _amount) external; // Harvest Functions function harvestYield(GroupId groupId, TreasuryHarvestLibrary.HarvestParams memory params) external; function harvestFees(GroupId groupId, TreasuryHarvestLibrary.HarvestParams memory params) external; // Management Functions function updateBaseTokenCap(GroupId groupId, uint256 _baseTokenCap) external; function updateFeeCollector(address _newFeeCollector) external; function forceUpdateGroupCache(address tokenRegistry, GroupId groupId) external; function getTreasuryState(GroupId groupId) external view returns (DTreasury.TreasuryState memory); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency, CurrencyLibrary } from "../types/Currency.sol"; import { Address, AddressLibrary } from "../types/Address.sol"; import { FxStableMath } from "../libs/math/FxStableMath.sol"; import { ExponentialMovingAverageV8 } from "../libs/math/ExponentialMovingAverageV8.sol"; import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import { IPriceOracle } from "../interfaces/IPriceOracle.sol"; import { DTreasury } from "../declarations/DTreasury.sol"; import { GroupStateHelper, GroupSettings } from "../types/GroupStateHelper.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { CustomRevert } from "../libs/CustomRevert.sol"; import { IDEXRouter } from "../interfaces/IDEXRouter.sol"; import { IStrategy } from "../interfaces/IStrategy.sol"; import { GroupState } from "../types/CommonTypes.sol"; import { FullMath } from "../libs/math/FullMath.sol"; /** * @title TreasuryStateLibrary * @notice Library for managing treasury state and calculations. */ library TreasuryStateLibrary { using CurrencyLibrary for Currency; using AddressLibrary for Address; using FxStableMath for FxStableMath.SwapState; using ExponentialMovingAverageV8 for ExponentialMovingAverageV8.EMAStorage; using GroupStateHelper for GroupSettings; using CustomRevert for bytes4; error ErrorInvalidTwapPrice(); error ErrorSwapFailed(); error ErrorWithdrawFromStrategy(); error StrategyUnderflow(); event BaseTokenCapsUpdated(uint256 newCaps); event BaseTokenPriceUpdated(uint256 newPrice); event SwapExecuted(address indexed fromToken, address indexed toToken, uint256 amountIn, uint256 amountOut); event BaseTokenTransferred(address indexed recipient, uint256 amount); event StrategyWithdrawal(address indexed strategy, uint256 amount); event EMALeverageRatioUpdated(uint256 newEMAValue); event GroupEMALeverageRatioInitialized(uint256 initialValue); uint256 private constant PRECISION = 1e18; /** * @notice Updates the base token caps in the treasury state. * @param self The treasury state storage. * @param newCaps The new base token caps. */ function updateBaseTokenCaps(DTreasury.TreasuryState storage self, uint256 newCaps) internal { self.baseTokenCaps = newCaps; emit BaseTokenCapsUpdated(newCaps); } /** * @notice Updates the base token price in the treasury state. * @param self The treasury state storage. * @param newPrice The new base token price. */ function updateBaseTokenPrice(DTreasury.TreasuryState storage self, uint256 newPrice) internal { self.baseTokenPrice = newPrice; emit BaseTokenPriceUpdated(newPrice); } /** * @notice Loads the swap state with proper precision handling. * @param self The treasury state storage. * @param group The group state. * @return _state The loaded swap state. */ function loadSwapState( DTreasury.TreasuryState storage self, GroupState memory group ) internal view returns (FxStableMath.SwapState memory _state) { // Fetch decimals uint8 baseTokenDecimals = GroupSettings.wrap(group.groupSettings).getBaseTokenDecimals(); uint8 aTokenDecimals = GroupSettings.wrap(group.groupSettings).getATokenDecimals(); uint8 xTokenDecimals = GroupSettings.wrap(group.groupSettings).getXTokenDecimals(); // Normalize baseSupply to 18 decimals _state.baseSupply = normalizeDecimals(self.totalBaseTokens, baseTokenDecimals); // Fetch base token price (already in 18 decimals) (_state.baseTwapNav, _state.baseNav) = fetchBaseTokenPrice(self, group); if (_state.baseSupply == 0) { _state.aNav = PRECISION; _state.xNav = PRECISION; } else { // Fetch token supplies and normalize to 18 decimals uint256 aSupplyRaw = IERC20Upgradeable(group.core.aToken.toAddress()).totalSupply(); uint256 xSupplyRaw = IERC20Upgradeable(group.core.xToken.toAddress()).totalSupply(); _state.aSupply = normalizeDecimals(aSupplyRaw, aTokenDecimals); _state.xSupply = normalizeDecimals(xSupplyRaw, xTokenDecimals); // Fetch aNav (assuming it's already in 18 decimals) _state.beta = IAToken(group.core.aToken.toAddress()).beta(); if (_state.beta) { _state.aNav = IAToken(group.core.aToken.toAddress()).nav(); } else { _state.aNav = PRECISION; } if (_state.xSupply == 0) { // No xToken, treat the nav of xToken as 1.0 _state.xNav = PRECISION; } else { uint256 _baseVal = _state.baseSupply * _state.baseNav; uint256 _aVal = _state.aSupply * _state.aNav; if (_baseVal >= _aVal) { _state.xNav = (_baseVal - _aVal) / _state.xSupply; } else { // Under-collateralized _state.xNav = 0; } } } } /** * @notice Fetches the base token price from the price oracle. * @param group The group state. * @return _twap The time-weighted average price. * @return _price The selected price */ function fetchBaseTokenPrice( DTreasury.TreasuryState storage /*self*/, GroupState memory group ) internal view returns (uint256 _twap, uint256 _price) { bool isValid; address priceOracle = group.extended.priceOracle.toAddress(); (isValid, _price) = IPriceOracle(priceOracle).getPrice(group.core.baseToken.toAddress()); if (!isValid || _price == 0) ErrorInvalidTwapPrice.selector.revertWith(); // Prices are already in 18 decimals return (_price, _price); } /** * @notice Checks if the treasury is under-collateralized. * @param self The treasury state storage. * @param group The group state. * @return True if under-collateralized, false otherwise. */ function isUnderCollateral(DTreasury.TreasuryState storage self, GroupState memory group) internal view returns (bool) { FxStableMath.SwapState memory _state = loadSwapState(self, group); return _state.xNav == 0; } /** * @notice Gets the collateral ratio of the treasury. * @param self The treasury state storage. * @param group The group state. * @return The collateral ratio. */ function getCollateralRatio(DTreasury.TreasuryState storage self, GroupState memory group) internal view returns (uint256) { FxStableMath.SwapState memory _state = loadSwapState(self, group); if (_state.baseSupply == 0) return PRECISION; if (_state.aSupply == 0 || _state.aNav == 0) return PRECISION * PRECISION; return FullMath.mulDiv(_state.baseSupply * _state.baseNav, PRECISION, _state.aSupply * _state.aNav); } /** * @notice Calculates the maximum mintable AToken based on the new collateral ratio. * @param self The treasury state storage. * @param group The group state. * @param _newCollateralRatio The new desired collateral ratio. * @return _maxBaseIn The maximum base tokens that can be input. * @return _maxATokenMintable The maximum AToken that can be minted. */ function maxMintableAToken( DTreasury.TreasuryState storage self, GroupState memory group, uint256 _newCollateralRatio ) internal view returns (uint256 _maxBaseIn, uint256 _maxATokenMintable) { FxStableMath.SwapState memory _state = loadSwapState(self, group); (_maxBaseIn, _maxATokenMintable) = _state.maxMintableAToken(_newCollateralRatio); } /** * @notice Calculates the maximum redeemable AToken based on the new collateral ratio. * @param self The treasury state storage. * @param group The group state. * @param _newCollateralRatio The new desired collateral ratio. * @return _maxBaseOut The maximum base tokens that can be output. * @return _maxATokenRedeemable The maximum AToken that can be redeemed. */ function maxRedeemableAToken( DTreasury.TreasuryState storage self, GroupState memory group, uint256 _newCollateralRatio ) internal view returns (uint256 _maxBaseOut, uint256 _maxATokenRedeemable) { FxStableMath.SwapState memory _state = loadSwapState(self, group); (_maxBaseOut, _maxATokenRedeemable) = _state.maxRedeemableAToken(_newCollateralRatio); } /** * @notice Updates the Exponential Moving Average (EMA) of the leverage ratio. * @param self The treasury state storage. * @param _state The current swap state. */ function updateEMALeverageRatio(DTreasury.TreasuryState storage self, FxStableMath.SwapState memory _state) internal { uint256 _ratio = _state.leverageRatio(); self.emaLeverageRatio.saveValue(uint96(_ratio)); emit EMALeverageRatioUpdated(_ratio); } function getEMAValue(DTreasury.TreasuryState storage self) internal view returns (uint256) { return self.emaLeverageRatio.emaValue(); } function initializeGroupEMALeverageRatio(DTreasury.TreasuryState storage self) internal { self.emaLeverageRatio.lastTime = uint40(block.timestamp); self.emaLeverageRatio.lastValue = uint96(PRECISION * 2); self.emaLeverageRatio.lastEmaValue = uint96(PRECISION * 2); self.emaLeverageRatio.sampleInterval = 1 days; emit GroupEMALeverageRatioInitialized(PRECISION * 2); } /** * @dev Normalizes a token amount to 18 decimals. * @param amount The amount to normalize. * @param tokenDecimals The decimals of the token. * @return The normalized amount. */ function normalizeDecimals(uint256 amount, uint8 tokenDecimals) internal pure returns (uint256) { if (tokenDecimals == 18) { return amount; } uint256 factor; if (tokenDecimals < 18) { factor = 10 ** (18 - tokenDecimals); return amount * factor; } else { factor = 10 ** (tokenDecimals - 18); return amount / factor; } } /** * @dev Denormalizes a token amount from 18 decimals to the token's decimals. * @param amount The amount to denormalize. * @param tokenDecimals The decimals of the token. * @return The denormalized amount. */ function denormalizeDecimals(uint256 amount, uint8 tokenDecimals) internal pure returns (uint256) { if (tokenDecimals == 18) { return amount; } uint256 factor; if (tokenDecimals < 18) { factor = 10 ** (18 - tokenDecimals); return amount / factor; } else { factor = 10 ** (tokenDecimals - 18); return amount * factor; } } /** * @notice Transfers base tokens to the recipient, withdrawing from strategy if necessary. * @param baseToken The base token. * @param strategyAddress The strategy address. * @param treasuryState The treasury state. * @param amount The amount of base tokens to transfer. * @param recipient The recipient address. */ function transferBaseToken( address self, uint8 baseTokenDecimals, Currency baseToken, address strategyAddress, DTreasury.TreasuryState storage treasuryState, uint256 amount, address recipient ) internal { uint256 amountNormalized = normalizeDecimals(amount, baseTokenDecimals); uint256 balance = baseToken.balanceOf(self); uint256 balanceNormalized = normalizeDecimals(balance, baseTokenDecimals); if (balanceNormalized < amountNormalized) { uint256 diff = amountNormalized - balanceNormalized; if (diff == 0) return; IStrategy strategy = IStrategy(strategyAddress); bool success = strategy.withdrawToTreasury(diff); if (!success) ErrorWithdrawFromStrategy.selector.revertWith(); if (treasuryState.strategyUnderlying < diff) StrategyUnderflow.selector.revertWith(); treasuryState.strategyUnderlying -= diff; balance = baseToken.balanceOf(self); balanceNormalized = normalizeDecimals(balance, baseTokenDecimals); if (amountNormalized > balanceNormalized) { amountNormalized = balanceNormalized; amount = denormalizeDecimals(amountNormalized, baseTokenDecimals); } } treasuryState.totalBaseTokens -= amountNormalized; baseToken.safeTransfer(recipient, amount); emit BaseTokenTransferred(recipient, amount); } /** * @notice Swaps tokens using the specified router. * @param self The address of the contract using this library * @param swapRouter The address of the swap router. * @param from The address of the token to swap from. * @param to The address of the token to swap to. * @param amount The amount of tokens to swap. * @param minOutAmount The minimum acceptable amount of tokens to receive. * @return swappedAmount The amount of tokens received after the swap. */ function swapTokens( address self, address swapRouter, address from, address to, uint256 amount, uint256 minOutAmount ) internal returns (uint256 swappedAmount) { IDEXRouter router = IDEXRouter(swapRouter); uint256 deadline = block.timestamp + 30; address[] memory path = new address[](2); path[0] = from; path[1] = to; Currency fromToken = Currency.wrap(from); uint256 currentAllowance = fromToken.allowance(self, swapRouter); if (currentAllowance < amount) { fromToken.safeIncreaseAllowance(swapRouter, amount - currentAllowance); } swappedAmount = _executeSwap(router, amount, minOutAmount, path, self, deadline); if (swappedAmount < minOutAmount) { ErrorSwapFailed.selector.revertWith(); } emit SwapExecuted(from, to, amount, swappedAmount); return swappedAmount; } function _executeSwap( IDEXRouter router, uint256 amount, uint256 minOutAmount, address[] memory path, address to, uint256 deadline ) private returns (uint256) { try router.swapExactTokensForTokens(amount, minOutAmount, path, to, deadline) returns (uint256[] memory amounts) { return amounts[amounts.length - 1]; } catch { ErrorSwapFailed.selector.revertWith(); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency, CurrencyLibrary } from "../types/Currency.sol"; import { GroupStateHelper, GroupSettings } from "../types/GroupStateHelper.sol"; import { GroupState, FeeModel } from "../types/CommonTypes.sol"; import { GroupId } from "../types/GroupId.sol"; import { DTreasury } from "../declarations/DTreasury.sol"; import { TreasuryStateLibrary } from "./TreasuryStateLibrary.sol"; import { IDXToken } from "../interfaces/IDXToken.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IWToken } from "../interfaces/IWToken.sol"; import { IRebalancePool } from "../interfaces/IRebalancePool.sol"; import { CustomRevert } from "../libs/CustomRevert.sol"; import { FullMath } from "../libs/math/FullMath.sol"; import { IProtocolMinimum as IProtocol } from "../interfaces/IProtocolMinimum.sol"; /** * @title TreasuryHarvestLibrary * @notice This library orchestrates fee and yield harvesting for a specific group. * @dev It handles collecting fees, distributing base tokens, minting aTokens, and managing * yield fees. The library relies on external calls to tokens and Rebalance Pools, and * carefully handles potential revert scenarios via `try/catch` and bubble-up reverts. */ library TreasuryHarvestLibrary { using CurrencyLibrary for Currency; using GroupStateHelper for GroupSettings; using TreasuryStateLibrary for *; using CustomRevert for bytes4; // ========================= // ======== Errors ========= // ========================= error ZeroAmount(); error WrongFeeModel(GroupId groupId); error ErrorDistributingYield(); error ErrorFeeCollectionFailed(GroupId groupId); error ErrorDistributingTokens(GroupId groupId); // ========================= // ======== Events ========= // ========================= event FeesCollected(GroupId indexed groupId, uint256 amount); event FeesHarvested(GroupId indexed groupId, uint256 dxTokenBalance, address feeCollector); event YieldHarvested(GroupId indexed groupId, uint256 yieldAmount, address feeCollector); event ATokensMintedToPool(GroupId indexed groupId, uint256 aTokenAmount, address recipient); event TokensSwappedToPool(GroupId indexed groupId, address fromToken, address toToken, uint256 amountIn, uint256 amountOut); // ========================= // ======== Structs ======== // ========================= /** * @notice Parameters used to harvest yield or fees. * @param sendTokens If true, will swap base tokens into stablecoins * instead of attempting to mint aTokens (when mint capacity is exceeded). * @param swapRouter Address of the DEX/router used to swap base tokens for stablecoins. * @param stablecoin The address of the stablecoin into which base tokens may be swapped. * @param minAmountOut The minimum amount of stablecoins that must be received from the swap * for the transaction not to revert. */ struct HarvestParams { bool sendTokens; address swapRouter; address stablecoin; uint256 minAmountOut; } /** * @notice Collects any accrued fees from dxToken. * @dev Calls `collectFees` on the dxToken. Reverts if no fees were collected. * @param groupState The current group state, which includes the dxToken address. * @return The amount of dxToken fees collected. */ function collectFees(GroupState memory groupState, GroupId groupId) internal returns (uint256) { IDXToken dxToken = IDXToken(groupState.core.xToken.toAddress()); uint256 dxTokenBalanceBefore = dxToken.balanceOf(address(this)); // Attempt to collect fees from dxToken try dxToken.collectFees() { // Get the balance of dxToken after fees have been collected uint256 dxTokenBalanceAfter = dxToken.balanceOf(address(this)); uint256 collectedAmount = dxTokenBalanceAfter - dxTokenBalanceBefore; // Revert if no fees were actually collected if (collectedAmount == 0) ZeroAmount.selector.revertWith(); // Emit an event to log the fees collected emit FeesCollected(groupId, collectedAmount); return collectedAmount; } catch { CustomRevert.bubbleUpAndRevertWith(dxToken.collectFees.selector, address(dxToken)); } } /** * @notice Harvests fees (not yield) based on the group's fee model. * @dev For management fees, the dxTokens are simply transferred to the feeCollector. * For funding fees, dxTokens are burned and then aTokens are minted (or stablecoins are swapped). * @param groupId The ID of the group for which fees are harvested. * @param groupState The current group state data. * @param treasuryState The TreasuryState storage reference for updating internal state. * @param harvestParams Parameters controlling how the harvested tokens might be swapped or minted. * @param dxTokenBalance The amount of dxTokens available for fee harvesting. * @param feeCollector The address to which management fees should be sent. * @param protocol The Protocol contract address (for calculating stability ratio, etc). */ function harvestFees( GroupId groupId, GroupState memory groupState, DTreasury.TreasuryState storage treasuryState, HarvestParams memory harvestParams, uint256 dxTokenBalance, address feeCollector, address protocol ) internal { IDXToken dxToken = IDXToken(groupState.core.xToken.toAddress()); // Determine the fee model for this group FeeModel feeModel = dxToken.getFeeModel(); if (feeModel == FeeModel.MANAGEMENT_FEE) { // Simply transfer dxTokens to fee collector groupState.core.xToken.safeTransfer(feeCollector, dxTokenBalance); return; } if (feeModel == FeeModel.VARIABLE_FUNDING_FEE || feeModel == FeeModel.FIXED_FUNDING_FEE) { // For funding fees, burn dxTokens try dxToken.burn(address(this), dxTokenBalance) {} catch { CustomRevert.bubbleUpAndRevertWith(dxToken.burn.selector, address(dxToken)); } // Calculate baseTokenAmount from dxTokens uint256 baseTokenAmount = dxToken.dxTokenToBaseToken(dxTokenBalance); uint8 baseTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getBaseTokenDecimals(); // apply yield and get net harvestable amount (baseTokenAmount, ) = _applyYield(groupState, baseTokenAmount, feeCollector); // Normalize baseTokenAmount to an 18-decimal scale (for internal accounting) uint256 baseTokenAmountNormalized = TreasuryStateLibrary.normalizeDecimals( baseTokenAmount, baseTokenDecimals ); // Distribute base tokens either as aToken or stablecoin, depending on mint capacity _distributeBaseTokens( groupState, groupId, treasuryState, baseTokenAmount, baseTokenAmountNormalized, harvestParams, protocol ); emit FeesHarvested(groupId, dxTokenBalance, feeCollector); return; } // If none of the recognized fee models applies, revert. WrongFeeModel.selector.revertWith(groupId); } /** * @notice Harvests yield for a group, applies any yield fees, and distributes the net amount. * @dev A portion of the yield is sent to the feeCollector as a yield fee (if applicable). * @param groupId The ID of the group for which yield is being harvested. * @param groupState The current group state data. * @param treasuryState The TreasuryState storage reference for updating internal state. * @param harvestParams Parameters controlling how the base tokens might be swapped or minted. * @param harvestableAmount The total base token amount of yield harvested. * @param feeCollector The address to which the yield fee is sent. * @param protocol The Protocol contract address (for calculating stability ratio, etc). */ function harvestYield( GroupId groupId, GroupState memory groupState, DTreasury.TreasuryState storage treasuryState, HarvestParams memory harvestParams, uint256 harvestableAmount, address feeCollector, address protocol ) internal { // Apply yield fees and get net harvestable amount (harvestableAmount, ) = _applyYield(groupState, harvestableAmount, feeCollector); // Normalize the base token amount for internal accounting uint8 baseTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getBaseTokenDecimals(); uint256 baseTokenAmountNormalized = TreasuryStateLibrary.normalizeDecimals( harvestableAmount, baseTokenDecimals ); // Distribute the net base tokens (either as stablecoin or aTokens) _distributeBaseTokens( groupState, groupId, treasuryState, harvestableAmount, baseTokenAmountNormalized, harvestParams, protocol ); emit YieldHarvested(groupId, harvestableAmount, feeCollector); } /** * @notice Calculates how many aTokens should be minted given a certain amount of base tokens, * and also how many aTokens can be minted at maximum without breaching collateral targets. * @param groupState The current group state data. * @param groupId The ID of the group for which aTokens will be minted. * @param baseTokenAmountNormalized The normalized amount of base tokens to convert into aTokens. * @param aToken The IAToken contract reference (whose NAV is used to compute minted supply). * @param protocol The Protocol contract address (for stability ratio checks). * @return aTokenToMint How many aTokens should be minted given the current NAV. * @return aTokenMintableMax The maximum number of aTokens that can be minted without breaching collateral. */ function calculateMintingParams( DTreasury.TreasuryState storage treasuryState, GroupState memory groupState, GroupId groupId, uint256 baseTokenAmountNormalized, IAToken aToken, address protocol ) internal view returns (uint256 aTokenToMint, uint256 aTokenMintableMax) { // Fetch the current base token price from an oracle or similar feed (, uint256 newPrice) = TreasuryStateLibrary.fetchBaseTokenPrice(treasuryState, groupState); // NAV of the aToken is used to determine how many aTokens 1 base token is worth uint256 aTokenNav = aToken.nav(); // aTokenToMint = (baseTokenAmountNormalized * newPrice) / aTokenNav aTokenToMint = FullMath.mulDiv(baseTokenAmountNormalized, newPrice, aTokenNav); // Check how many aTokens we can mint before breaching collateral/stability constraints (, aTokenMintableMax) = TreasuryStateLibrary.maxMintableAToken( treasuryState, groupState, uint256(IProtocol(protocol).stabilityRatio(groupId)) ); } /** * @notice Distributes base tokens to the Rebalance Pool either by minting aTokens or swapping * them into stablecoins, depending on the mint capacity and user preference. * @dev If the aToken mint capacity is insufficient and `sendTokens == true`, base tokens * are swapped into stablecoins. Otherwise, the function reverts. * @param groupState The current group state data. * @param groupId The ID of the group for which distribution is happening. * @param treasuryState The TreasuryState storage reference for updating internal state. * @param baseTokenAmount The actual (denormalized) amount of base tokens. * @param baseTokenAmountNormalized The normalized base token amount (scaled to 18 decimals internally). * @param harvestParams Struct containing swap and stablecoin parameters. * @param protocol The Protocol contract address (for stability ratio checks). */ function _distributeBaseTokens( GroupState memory groupState, GroupId groupId, DTreasury.TreasuryState storage treasuryState, uint256 baseTokenAmount, uint256 baseTokenAmountNormalized, HarvestParams memory harvestParams, address protocol ) private { IAToken aToken = IAToken(groupState.core.aToken.toAddress()); Currency stableCoinCurrency = Currency.wrap(harvestParams.stablecoin); // Compute how many aTokens we *need* to mint and how many are *allowed* to mint (uint256 aTokenToMint, uint256 aTokenMintableMax) = calculateMintingParams( treasuryState, groupState, groupId, baseTokenAmountNormalized, aToken, protocol ); // If we cannot mint the entire required amount of aTokens if (aTokenMintableMax < aTokenToMint) { // If we are NOT allowed to send stablecoins, revert if (!harvestParams.sendTokens) ErrorDistributingTokens.selector.revertWith(groupId); // Decrease the treasury's totalBaseTokens because we'll unwrap and swap them treasuryState.totalBaseTokens -= baseTokenAmountNormalized; // 1. Unwrap the wrapped base tokens into their underlying (e.g., WETH -> ETH or WMATIC -> MATIC). uint256 unwrappedBaseTokens = IWToken(groupState.core.baseToken.toAddress()).unwrap(baseTokenAmount); // 2. Swap from base tokens -> stablecoins uint256 stablecoinAmount = TreasuryStateLibrary.swapTokens( address(this), harvestParams.swapRouter, // We should swap from the *yield-bearing token* (not the base token) groupState.core.yieldBearingToken.toAddress(), stableCoinCurrency.toAddress(), unwrappedBaseTokens, harvestParams.minAmountOut ); // 3. Transfer the stablecoins to the Rebalance Pool stableCoinCurrency.safeTransfer( groupState.extended.rebalancePool.toAddress(), stablecoinAmount ); emit TokensSwappedToPool(groupId, groupState.core.baseToken.toAddress(), harvestParams.stablecoin, unwrappedBaseTokens, stablecoinAmount); } else { // We can mint the full aToken amount from the base tokens // Increase the treasury's totalBaseTokens accordingly treasuryState.totalBaseTokens += baseTokenAmountNormalized; // Convert aTokenToMint from normalized (18 decimals) to the actual aToken decimals uint8 aTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getATokenDecimals(); uint256 aTokenToMintDenorm = TreasuryStateLibrary.denormalizeDecimals(aTokenToMint, aTokenDecimals); // Mint aTokens directly to the Rebalance Pool aToken.mint(groupState.extended.rebalancePool.toAddress(), aTokenToMintDenorm); // Update the Rebalance Pool’s NAV to reflect the newly minted aTokens IRebalancePool(groupState.extended.rebalancePool.toAddress()).updateNAV(); emit ATokensMintedToPool(groupId, aTokenToMintDenorm, groupState.extended.rebalancePool.toAddress()); } } /** * @notice Applies a yield fee to the harvestable amount (if any) and transfers that fee * portion to the feeCollector. Returns the net amount after fee. * @param groupState The current group state data (for accessing baseToken). * @param harvestableAmount The total yield (in base tokens) to be distributed. * @param feeCollector The address to which yield fees should be sent. * @return _harvestableAmount The net (post-fee) amount of base tokens. * @return _feeAmount The fee amount that was deducted and sent to the feeCollector. */ function _applyYield( GroupState memory groupState, uint256 harvestableAmount, address feeCollector ) private returns (uint256 _harvestableAmount, uint256 _feeAmount) { IRebalancePool rebalancePool = IRebalancePool(groupState.extended.rebalancePool.toAddress()); uint256 yieldFeePercentage = rebalancePool.yieldFeePercentage(); uint256 BASE_POINTS = 10_000; // If there's a yield fee, calculate and transfer it if (yieldFeePercentage > 0) { _feeAmount = (harvestableAmount * yieldFeePercentage) / BASE_POINTS; _harvestableAmount = harvestableAmount - _feeAmount; if (_feeAmount > 0) { groupState.core.baseToken.safeTransfer(feeCollector, _feeAmount); } } else { // If no yield fee, the entire amount is harvestable _harvestableAmount = harvestableAmount; } return (_harvestableAmount, _feeAmount); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency, CurrencyLibrary } from "../types/Currency.sol"; import { GroupStateHelper, GroupSettings } from "../types/GroupStateHelper.sol"; import { GroupState } from "../types/CommonTypes.sol"; import { GroupId } from "../types/GroupId.sol"; import { DTreasury } from "../declarations/DTreasury.sol"; import { TreasuryStateLibrary } from "./TreasuryStateLibrary.sol"; import { IAToken } from "../interfaces/IAToken.sol"; import { IWToken } from "../interfaces/IWToken.sol"; import { IRebalancePool } from "../interfaces/IRebalancePool.sol"; import { FullMath } from "../libs/math/FullMath.sol"; import { CurrencyLibrary } from "../types/Currency.sol"; /** * @title TreasuryRebalanceLibrary * @notice This library handles "rebalanceUp" and "rebalanceDown" for a given group, * adjusting the collateral ratio to ensure protocol stability or efficiency. * @dev Refactored into smaller, reusable helper functions for improved readability. */ library TreasuryRebalanceLibrary { using CurrencyLibrary for Currency; using GroupStateHelper for GroupSettings; using TreasuryStateLibrary for DTreasury.TreasuryState; error InvalidRatio(); error ZeroAddress(); error ZeroAmount(); // Precision factor used in validations (e.g. checking CR > 100%) uint256 internal constant PRECISION = 1e18; struct RebalanceUpParams { uint256 targetCollateralRatio; address swapRouter; address stablecoin; uint256 minAmountOut; } struct RebalanceDownParams { uint256 targetCollateralRatio; uint256 convertAmount; address stablecoin; address swapRouter; uint256 minAmountOut; } /** * @notice Rebalances the protocol upward when the collateral ratio is below the stability ratio. * Burns aTokens in exchange for stablecoins, thus increasing the effective CR. * @dev If the current CR is below the protocol's stability ratio, this method pulls it closer * to (or above) that stability ratio. * * Steps (High-Level): * 1. Compute how many aTokens to burn. * 2. Convert the burned aTokens to base tokens, unwrap, then swap them to stablecoins. * 3. Send those stablecoins to the Rebalance Pool. * 4. Decrease `totalBaseTokens` accordingly in treasury storage. * * @param state The storage state of the Treasury (i.e. `treasuryStates[groupId]`). * @param groupState The current group state info. * @param params The parameters for the rebalance up operation. */ function rebalanceUp( DTreasury.TreasuryState storage state, GroupState memory groupState, RebalanceUpParams memory params ) internal { // Compute the normalized amount of aTokens to burn uint256 aTokenToBurn = _computeATokenToBurn(state, groupState, params.targetCollateralRatio); // Burn aTokens from Rebalance Pool, get the equivalent base tokens uint256 baseTokenAmountNormalized = _burnATokensForBase(state, groupState, aTokenToBurn); // 4. Unwrap & Swap base tokens -> stablecoins uint256 stablecoinReceived = _swapBaseForStablecoin( groupState, baseTokenAmountNormalized, params.swapRouter, params.stablecoin, params.minAmountOut ); // 5. Transfer stablecoins to Rebalance Pool & update treasury state Currency.wrap(params.stablecoin).safeTransfer(groupState.extended.rebalancePool.toAddress(), stablecoinReceived); state.totalBaseTokens -= baseTokenAmountNormalized; } /** * @notice Rebalances the protocol downward when the collateral ratio is too high. * Converts stablecoins to base tokens, then mints aTokens, effectively reducing the CR. * @dev If the current CR is above some target, this brings it down closer to that target CR. * * Steps (High-Level): * 1. Transfer stablecoins from Rebalance Pool -> Treasury. * 2. Swap stablecoins -> base tokens, then wrap them. * 3. Normalize base token amount, compute how many aTokens we can mint, and mint them. * 4. Increase `totalBaseTokens` accordingly in treasury storage. * * @param state The storage state of the Treasury (i.e. `treasuryStates[groupId]`). * @param groupState The current group state info. * @param params The parameters for the rebalance down operation. */ function rebalanceDown( DTreasury.TreasuryState storage state, GroupState memory groupState, RebalanceDownParams memory params ) internal { // Transfer stablecoins from Rebalance Pool -> Treasury uint256 finalConvertAmount = _transferStablecoinsToTreasury(groupState, params.stablecoin, params.convertAmount); // Swap stablecoins -> base tokens, then wrap uint256 baseTokenAmountNormalized = _swapStablecoinForBaseWrapped( state, groupState, finalConvertAmount, params.stablecoin, params.swapRouter, params.minAmountOut ); // Mint aTokens from the base tokens uint256 aTokenOut = _mintATokensFromBase(state, groupState, baseTokenAmountNormalized); if (aTokenOut == 0) revert ZeroAmount(); // i.e., minting failed // Update treasury storage to reflect new base token total state.totalBaseTokens += baseTokenAmountNormalized; } /** * @notice Computes how many aTokens we need to burn to reach the `targetCollateralRatio`. * @return aTokenToBurn (normalized to 18 decimals, not the actual token decimals) */ function _computeATokenToBurn( DTreasury.TreasuryState storage state, GroupState memory groupState, uint256 targetCollateralRatio ) private view returns (uint256) { (, uint256 aTokenToBurn) = state.maxRedeemableAToken(groupState, targetCollateralRatio); return aTokenToBurn; } /** * @notice Burns aTokens from the Rebalance Pool and calculates the normalized base token value. * @dev 1) Denormalize aTokenToBurn (to match aToken decimals), * 2) burn them from Rebalance Pool, * 3) compute baseTokenAmountNormalized = (aTokenToBurn * aTokenNav) / basePrice */ function _burnATokensForBase( DTreasury.TreasuryState storage state, GroupState memory groupState, uint256 aTokenToBurnNormalized ) private returns (uint256 baseTokenAmountNormalized) { IAToken aToken = IAToken(groupState.core.aToken.toAddress()); address rebalancePool = groupState.extended.rebalancePool.toAddress(); // Denormalize amount to aToken decimals uint8 aTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getATokenDecimals(); uint256 aTokenBurnAmountDenorm = TreasuryStateLibrary.denormalizeDecimals(aTokenToBurnNormalized, aTokenDecimals); // Burn from Rebalance Pool aToken.burn(rebalancePool, aTokenBurnAmountDenorm); // Calculate how many base tokens this is worth (in normalized form) (, uint256 basePrice) = state.fetchBaseTokenPrice(groupState); baseTokenAmountNormalized = FullMath.mulDiv(aTokenToBurnNormalized, aToken.nav(), basePrice); } /** * @notice Unwraps the base tokens and swaps them for stablecoins. * @dev 1) Convert normalized base tokens -> actual decimals, * 2) unwrap WETH->ETH or WMATIC->MATIC, * 3) swap via `TreasuryStateLibrary.swapTokens`. */ function _swapBaseForStablecoin( GroupState memory groupState, uint256 baseTokenAmountNormalized, address swapRouter, address stablecoin, uint256 minAmountOut ) private returns (uint256 stablecoinReceived) { // Denormalize to get actual base token decimals uint8 baseTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getBaseTokenDecimals(); uint256 baseTokenAmount = TreasuryStateLibrary.denormalizeDecimals(baseTokenAmountNormalized, baseTokenDecimals); // Unwrap (e.g., WETH -> ETH) baseTokenAmount = IWToken(groupState.core.baseToken.toAddress()).unwrap(baseTokenAmount); // Swap base token -> stablecoin stablecoinReceived = TreasuryStateLibrary.swapTokens( address(this), swapRouter, groupState.core.yieldBearingToken.toAddress(), stablecoin, baseTokenAmount, minAmountOut ); } /** * @notice Transfers stablecoins from Rebalance Pool to Treasury, returning the final amount to convert. * @dev If the Rebalance Pool has less than `convertAmount`, use the pool's entire balance. */ function _transferStablecoinsToTreasury( GroupState memory groupState, address stablecoin, uint256 convertAmount ) private returns (uint256) { address rebalancePool = groupState.extended.rebalancePool.toAddress(); IRebalancePool rPool = IRebalancePool(rebalancePool); Currency stableCoinCurrency = Currency.wrap(stablecoin); // Check pool balance, cap convertAmount if insufficient uint256 rPoolBalance = stableCoinCurrency.balanceOf(rebalancePool); if (rPoolBalance < convertAmount) { convertAmount = rPoolBalance; } // Transfer stablecoins from Rebalance Pool -> Treasury rPool.transferTokenToTreasury(stableCoinCurrency.toAddress(), convertAmount); return convertAmount; } /** * @notice Swaps stablecoins into base tokens, then wraps them. * @dev 1) Approve & swap stablecoin -> base tokens, * 2) wrap base tokens (ETH->WETH, etc.), * 3) normalize the final base token amount to 18 decimals. */ function _swapStablecoinForBaseWrapped( DTreasury.TreasuryState storage /*state*/, GroupState memory groupState, uint256 finalConvertAmount, address stablecoin, address swapRouter, uint256 minAmountOut ) private returns (uint256 baseTokenAmountNormalized) { // Approve stablecoins for swapping Currency stableCoinCurrency = Currency.wrap(stablecoin); stableCoinCurrency.safeIncreaseAllowance(swapRouter, finalConvertAmount); // Perform swap (stablecoin -> base token) uint256 baseTokenAmount = TreasuryStateLibrary.swapTokens( address(this), swapRouter, stablecoin, groupState.core.yieldBearingToken.toAddress(), finalConvertAmount, minAmountOut ); // Wrap base tokens (e.g., ETH -> WETH) groupState.core.yieldBearingToken.safeIncreaseAllowance(groupState.core.baseToken.toAddress(), baseTokenAmount); baseTokenAmount = IWToken(groupState.core.baseToken.toAddress()).wrap(baseTokenAmount); // Normalize (scale to 18 decimals internally) uint8 baseTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getBaseTokenDecimals(); baseTokenAmountNormalized = TreasuryStateLibrary.normalizeDecimals(baseTokenAmount, baseTokenDecimals); } /** * @notice Converts the given `baseTokenAmountNormalized` into aTokens, checking capacity (max mintable). * @dev 1) Use `aToken.nav()` and `basePrice` to compute how many aTokens to mint, * 2) Verify we can mint that many (not exceeding `maxMintableAToken`), * 3) Mint aTokens to Rebalance Pool. * @return aTokenOut The final aToken amount (in normalized form) minted. */ function _mintATokensFromBase( DTreasury.TreasuryState storage state, GroupState memory groupState, uint256 baseTokenAmountNormalized ) private returns (uint256 aTokenOut) { IAToken aToken = IAToken(groupState.core.aToken.toAddress()); GroupSettings groupSettings = GroupSettings.wrap(groupState.groupSettings); (, uint256 basePrice) = state.fetchBaseTokenPrice(groupState); uint256 aTokenPrice = aToken.nav(); // aTokenOut = (baseTokenAmountNormalized * basePrice) / aTokenPrice aTokenOut = FullMath.mulDiv(baseTokenAmountNormalized, basePrice, aTokenPrice); // Check capacity uint256 stabilityRatio = uint256(GroupStateHelper.getStabilityRatio(groupSettings)); (, uint256 aTokenMintableMax) = state.maxMintableAToken(groupState, stabilityRatio); if (aTokenMintableMax < aTokenOut) { revert InvalidRatio(); // i.e., can't mint that many without breaking CR constraints } // Convert to aToken decimals for actual mint uint8 aTokenDecimals = GroupSettings.wrap(groupState.groupSettings).getATokenDecimals(); uint256 aTokenOutDenorm = TreasuryStateLibrary.denormalizeDecimals(aTokenOut, aTokenDecimals); // Mint aTokens directly to the Rebalance Pool aToken.mint(groupState.extended.rebalancePool.toAddress(), aTokenOutDenorm); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; /// @notice https://forum.openzeppelin.com/t/safeerc20-vs-safeerc20upgradeable/17326 import { SafeERC20Upgradeable, IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import { CustomRevert } from "../libs/CustomRevert.sol"; // Custom type `Currency` to represent either an ERC20 token or the native currency (e.g., ETH) type Currency is address; /** * @title CurrencyLibrary * @dev A library for handling operations related to currencies, supporting both ERC20 tokens and native currency. * Provides utility functions for balance checks, transfers, approvals, and comparisons. */ library CurrencyLibrary { // Use SafeERC20Upgradeable for IERC20Upgradeable token operations to ensure safety using SafeERC20Upgradeable for IERC20Upgradeable; // Use CustomRevert for standardized error handling via selectors using CustomRevert for bytes4; // Define a constant representing the native currency (address(0)) Currency public constant NATIVE = Currency.wrap(address(0)); // Custom error definitions for various invalid operations involving native currency error NativeCurrencyTransfersNotAllowed(); error NativeCurrencyTransferFromNotAllowed(); error NativeCurrencyApprovalNotAllowed(); error NativeCurrencyDoesNotHaveTotalSupply(); error NativeCurrencyIncreaseAllowanceNotAllowed(); error NativeCurrencyDecreaseAllowanceNotAllowed(); error ArbitraryTransfersNotAllowed(); /** * @notice Checks if two currencies are equal. * @param currency The first currency to compare. * @param other The second currency to compare. * @return True if both currencies are the same, false otherwise. */ function equals(Currency currency, Currency other) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(other); } /** * @notice Retrieves the balance of the specified owner for the given currency. * @param currency The currency to check (ERC20 token or native). * @param owner The address of the owner whose balance is queried. * @return The balance of the owner in the specified currency. */ function balanceOf(Currency currency, address owner) internal view returns (uint256) { if (isNative(currency)) { return owner.balance; // For native currency, return the ETH balance } else { return IERC20Upgradeable(Currency.unwrap(currency)).balanceOf(owner); // For ERC20 tokens, use balanceOf } } /** * @notice Safely transfers a specified amount of the currency to a recipient. * @param currency The currency to transfer (must be an ERC20 token). * @param to The recipient address. * @param amount The amount to transfer. * @dev Native currency transfers are not allowed and will revert. */ function safeTransfer(Currency currency, address to, uint256 amount) internal { if (isNative(currency)) { // Revert if attempting to transfer native currency using ERC20 methods NativeCurrencyTransfersNotAllowed.selector.revertWith(); } else { IERC20Upgradeable(Currency.unwrap(currency)).safeTransfer(to, amount); } } /** * @notice Safely transfers a specified amount of the currency from one address to another. * @param currency The currency to transfer (must be an ERC20 token). * @param safeFrom The address to transfer from. * @param to The recipient address. * @param amount The amount to transfer. * @dev Native currency transfers are not allowed and will revert. * @dev Arbitrary transfers (i.e., not initiated by the sender) are also not allowed and will revert. * @notice Slither false positive. The function is internal and only used within the library */ //slither-disable-next-line arbitrary-send-erc20 function safeTransferFrom(Currency currency, address safeFrom, address to, uint256 amount) internal { if (isNative(currency)) { // Revert if attempting to transfer ERC20 tokens from an address other than the sender // This is to prevent arbitrary transfers, which are not allowed in the context of this library // This logic has the priority, so overrides any other inhereted logic NativeCurrencyTransferFromNotAllowed.selector.revertWith(); } else { if (safeFrom != msg.sender) ArbitraryTransfersNotAllowed.selector.revertWith(); IERC20Upgradeable(Currency.unwrap(currency)).safeTransferFrom(safeFrom, to, amount); } } /** * @notice Retrieves the allowance of a spender for the given owner's currency. * @param currency The currency to check (must be an ERC20 token). * @param owner The address of the owner of the currency. * @param spender The address of the spender. * @return The allowance of the spender for the owner's currency. */ function allowance(Currency currency, address owner, address spender) internal view returns (uint256) { if (isNative(currency)) { return 0; // For native currency, return 0 as allowance is not applicable } else { return IERC20Upgradeable(Currency.unwrap(currency)).allowance(owner, spender); // For ERC20 tokens, use allowance } } /** * @notice Safely approves a spender to spend a specified amount of the currency. * @param currency The currency to approve (must be an ERC20 token). * @param spender The address authorized to spend the tokens. * @param amount The amount to approve. * @dev Approving native currency is not allowed and will revert. */ function safeApprove(Currency currency, address spender, uint256 amount) internal { if (!isNative(currency)) { IERC20Upgradeable(Currency.unwrap(currency)).safeApprove(spender, amount); } else { // Revert if attempting to approve native currency NativeCurrencyApprovalNotAllowed.selector.revertWith(); } } /** * @notice Safely increases the allowance of a spender for the currency. * @param currency The currency to modify allowance for (must be an ERC20 token). * @param spender The address authorized to spend the tokens. * @param addedValue The amount to increase the allowance by. * @dev Increasing allowance for native currency is not allowed and will revert. */ function safeIncreaseAllowance(Currency currency, address spender, uint256 addedValue) internal { if (!isNative(currency)) { IERC20Upgradeable(Currency.unwrap(currency)).safeIncreaseAllowance(spender, addedValue); } else { // Revert if attempting to increase allowance for native currency NativeCurrencyIncreaseAllowanceNotAllowed.selector.revertWith(); } } /** * @notice Checks if the given currency is the native currency. * @param currency The currency to check. * @return True if `currency` is the native currency, false otherwise. */ function isNative(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == Currency.unwrap(NATIVE); } /** * @notice Checks if the given currency is the zero address. * @param currency The currency to check. * @return True if `currency` is the zero address, false otherwise. */ function isZero(Currency currency) internal pure returns (bool) { return Currency.unwrap(currency) == address(0); } /** * @notice Converts the currency address to a unique identifier. * @param currency The currency to convert. * @return The uint256 representation of the currency's address. */ function toId(Currency currency) internal pure returns (uint256) { return uint160(Currency.unwrap(currency)); } /** * @notice Unwraps the `Currency` type to retrieve the underlying address. * @param currency The currency to unwrap. * @return The underlying address of the currency. */ function toAddress(Currency currency) internal pure returns (address) { return Currency.unwrap(currency); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { GroupKey } from "./GroupKey.sol"; type GroupId is bytes32; // @notice library for computing the ID of a group library GroupIdLibrary { using GroupIdLibrary for GroupId; function toId(GroupKey memory groupKey) internal pure returns (GroupId groupId) { groupId = GroupId.wrap(keccak256(abi.encode(groupKey))); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { ITokenRegistryMinimum as ITokenRegistry } from "../interfaces/ITokenRegistryMinimum.sol"; import { DTokenRegistry } from "../declarations/DTokenRegistry.sol"; import { GroupId } from "../types/GroupId.sol"; import { IProtocol } from "../interfaces/IProtocol.sol"; import { Address, AddressLibrary } from "../types/Address.sol"; import { Currency, CurrencyLibrary } from "../types/Currency.sol"; import { CustomRevert } from "./CustomRevert.sol"; import { GroupStateHelper, GroupSettings } from "../types/GroupStateHelper.sol"; import { GroupState, CollateralInfo } from "../types/CommonTypes.sol"; library CacheLibrary { using CurrencyLibrary for Currency; using AddressLibrary for Address; using CustomRevert for bytes4; struct CachedGroupState { GroupState data; uint256 lastUpdateBlock; bool exists; } struct Storage { mapping(GroupId => CachedGroupState) cachedStates; } event CacheUpdated(GroupId indexed groupId); error ConfigNotReady(GroupId groupId); error InvalidTokenRegistry(address tokenRegistry); error InvalidGroupConfiguration(GroupId groupId); error EmptyCollateralListOnUpdate(GroupId groupId); /** * @notice Retrieves the cached group state, updating the cache if necessary. * @param self The storage containing cached group states. * @param groupId The ID of the group. * @return The group state. */ function getGroupState(Storage storage self, GroupId groupId) internal view returns (GroupState memory) { CachedGroupState storage cachedState = self.cachedStates[groupId]; if (!cachedState.exists) { ConfigNotReady.selector.revertWith(groupId); } return cachedState.data; } /** * @notice Updates the cache for a specific group ID. * @param self The storage containing cached group states. * @param tokenRegistry The token registry to fetch group state from. * @param groupId The ID of the group. */ function updateCache(Storage storage self, ITokenRegistry tokenRegistry, GroupId groupId) internal { CachedGroupState storage cachedState = self.cachedStates[groupId]; GroupState memory groupState = tokenRegistry.getGroup(groupId); if (groupState.core.aToken.isZero()) { InvalidGroupConfiguration.selector.revertWith(groupId); } uint256 len = groupState.acceptableCollaterals.length; if (len > 0) { delete cachedState.data.acceptableCollaterals; for (uint256 i = 0; i < len; ) { cachedState.data.acceptableCollaterals.push(groupState.acceptableCollaterals[i]); unchecked { ++i; } } } else { EmptyCollateralListOnUpdate.selector.revertWith(groupId); } /// @dev Validate core tokens with simple zero checks. /// @dev Token registry should have already validated these but this is another layer of fundamental validation. _simpleValidateGroupCoreTokens(groupState.core, groupId); _simpleValidateGroupExtendedTokens(groupState.extended, groupId); cachedState.data.core = groupState.core; cachedState.data.extended = groupState.extended; cachedState.data.feesPacked = groupState.feesPacked; cachedState.data.groupSettings = groupState.groupSettings; cachedState.data.hookContract = groupState.hookContract; cachedState.lastUpdateBlock = block.number; cachedState.exists = true; emit CacheUpdated(groupId); } /** * @notice Validates the core tokens of a group. * @param core The core tokens of the group. * @param groupId The ID of the group. * @dev This is a simple validation that checks for zero addresses and cartesian checks. * @dev Token registry should have already validated these but this is another layer of fundamental validation. */ function _simpleValidateGroupCoreTokens(DTokenRegistry.GroupCore memory core, GroupId groupId) private pure { if (core.aToken.isZero() || core.xToken.isZero() || core.baseToken.isZero() || core.yieldBearingToken.isZero()) { InvalidGroupConfiguration.selector.revertWith(groupId); } /// @dev cartesian check if ( core.aToken.equals(core.xToken) || core.aToken.equals(core.baseToken) || core.aToken.equals(core.yieldBearingToken) || core.xToken.equals(core.baseToken) || core.xToken.equals(core.yieldBearingToken) || core.baseToken.equals(core.yieldBearingToken) ) { InvalidGroupConfiguration.selector.revertWith(groupId); } } /** * @notice Validates the extended tokens of a group. * @param extended The extended tokens of the group. * @param groupId The ID of the group. * @dev This is a simple validation that checks for zero addresses. * @dev Token registry should have already validated these but this is another layer of fundamental validation. */ function _simpleValidateGroupExtendedTokens(DTokenRegistry.GroupExtended memory extended, GroupId groupId) private pure { if ( extended.priceOracle.isZero() || extended.rateProvider.isZero() || extended.swapRouter.isZero() || extended.treasury.isZero() || extended.feeCollector.isZero() || extended.strategy.isZero() || extended.rebalancePool.isZero() ) InvalidGroupConfiguration.selector.revertWith(groupId); } /** * @notice Forces the cache to update for a specific group ID. * @param self The storage containing cached group states. * @param tokenRegistry The token registry to fetch group state from. * @param groupId The ID of the group. */ function forceUpdate(Storage storage self, address tokenRegistry, GroupId groupId) internal { if (tokenRegistry == address(0)) InvalidTokenRegistry.selector.revertWith(groupId); updateCache(self, ITokenRegistry(tokenRegistry), groupId); } function getGroupTreasury(Storage storage self, GroupId groupId) internal view returns (address) { if (!self.cachedStates[groupId].exists) { ConfigNotReady.selector.revertWith(groupId); } return self.cachedStates[groupId].data.extended.treasury.toAddress(); } function getGroupHookContract(Storage storage self, GroupId groupId) internal view returns (address) { if (!self.cachedStates[groupId].exists) { ConfigNotReady.selector.revertWith(groupId); } return self.cachedStates[groupId].data.hookContract.toAddress(); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; // Import the CustomRevert library for standardized error handling import { CustomRevert } from "../libs/CustomRevert.sol"; /** * @title Address * @dev Defines a user-defined value type `Address` that wraps the built-in `address` type. */ type Address is address; /** * @title AddressLibrary * @dev A library for performing various operations on the `Address` type. */ library AddressLibrary { // Apply the library functions to the `Address` type using AddressLibrary for Address; // Use the CustomRevert library for standardized error handling via selectors using CustomRevert for bytes4; // Custom error definitions for more descriptive revert reasons error ZeroAddress(); error FailedCall(string reason); error NonContractAddress(); error UnableToSendValue(); /** * @notice Checks if the given `Address` is the zero address. * @param addr The `Address` to check. * @return True if `addr` is the zero address, false otherwise. */ function isZero(Address addr) internal pure returns (bool) { return Address.unwrap(addr) == address(0); } /** * @notice Determines if the given `Address` is a contract. * @param addr The `Address` to check. * @return True if `addr` is a contract, false otherwise. * * @dev This method relies on the fact that contracts have non-zero code size. * It returns false for contracts in construction, since the code is only stored at the end of the constructor execution. */ function isContract(Address addr) internal view returns (bool) { return Address.unwrap(addr).code.length > 0; } /** * @notice Compares two `Address` instances for equality. * @param a The first `Address`. * @param b The second `Address`. * @return True if both addresses are equal, false otherwise. */ function equals(Address a, Address b) internal pure returns (bool) { address addrA = Address.unwrap(a); address addrB = Address.unwrap(b); return addrA == addrB; } /** * @notice Converts an `Address` to a `uint160`. * @param addr The `Address` to convert. * @return The `uint160` representation of the address. */ function toUint160(Address addr) internal pure returns (uint160) { return uint160(Address.unwrap(addr)); } /** * @notice Creates an `Address` from a `uint160`. * @param addr The `uint160` value to convert. * @return A new `Address` instance. */ function fromUint160(uint160 addr) internal pure returns (Address) { return Address.wrap(address(addr)); } /** * @notice Unwraps the `Address` type to retrieve the underlying address. * @param addr The `Address` to unwrap. * @return The underlying `address`. */ function toAddress(Address addr) internal pure returns (address) { return Address.unwrap(addr); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; /// @dev This library implements formulas for minting and redeeming stable coin token (aToken) and leveraged (xToken) /// tokens in a system where: /// - There is a base token with a certain Net Asset Value (NAV). /// - A stable coin token (aToken) with its own NAV. /// - A leveraged token (xToken) with its own NAV. /// All values are scaled by 1e18 before being passed to these functions. /// /// The core equation governing the system is: /// n * v = nf * vf + nx * vx /// /// Where: /// n = current total base supply /// v = baseNav (NAV of base token) /// nf = aSupply (supply of stable coin token) /// vf = aNav (NAV of stable coin token) /// nx = xSupply (supply of leveraged token) /// vx = xNav (NAV of leveraged token) /// /// The "collateral ratio" (cr) or "target collateral ratio" (ncr) is defined as: /// cr = (total base value) / (stable coin token value) = (n * v) / (nf * vf) /// /// Operations involve adjusting supplies (minting or redeeming tokens) to reach a new collateral ratio (ncr). /// We define: /// dn = change in base supply (how many base tokens are added or removed) /// df = change in stable coin token supply (how many stable coin tokens are added or removed) /// /// By setting: /// ((n + dn) * v) / ((nf + df)*vf) = ncr /// /// and using the base equation n * v = nf * vf + nx * vx, we can derive formulas for dn and df /// depending on whether we are minting or redeeming under a desired collateral ratio. library FxStableMath { /************* * Constants * *************/ /// @dev The precision (scaling factor) used for calculations. uint256 internal constant PRECISION = 1e18; /// @dev The maximum leverage ratio allowed. uint256 internal constant MAX_LEVERAGE_RATIO = 100e18; /*********** * Structs * ***********/ struct SwapState { // Current supply of the base token uint256 baseSupply; // Current NAV of the base token (scaled by 1e18) uint256 baseNav; // Current TWAP NAV of the base token (scaled by 1e18), used for stable calculations uint256 baseTwapNav; // Current supply of the stable coin token uint256 aSupply; // Current NAV of the stable coin token (scaled by 1e18) uint256 aNav; // Current supply of the leveraged token uint256 xSupply; // Current NAV of the leveraged token (scaled by 1e18) uint256 xNav; // A boolean parameter `beta` that may adjust behavior in some calculations bool beta; } /** * @notice Compute how much base token (dn) and stable coin tokens (df) can be minted to achieve a new collateral ratio, * if the current collateral ratio is less than the new target. * * Variables (for reference): * n: current total base supply * v: baseNav * nf: aSupply * vf: aNav * nx: xSupply * vx: xNav * ncr: newCollateralRatio * * Core equations: * Initially: * n * v = nf * vf + nx * vx * * After adding some amount of base tokens (dn) and stable coin tokens (df): * (n + dn) * v = (nf + df) * vf + nx * vx * * Define collateral ratio as: * ((n + dn) * v) / ((nf + df) * vf) = ncr * * From the above, solving for df and dn: * df = ((n * v) - (ncr * nf * vf)) / ((ncr - 1) * vf) * dn = ((n * v) - (ncr * nf * vf)) / ((ncr - 1) * v) * * Here, df and dn tell us how much stable coin token and base token must be added to achieve ncr. * If dn > 0, we need to add that many base tokens; if df > 0, we can mint that many stable coin tokens. * * @dev If the current collateral ratio is already >= ncr, then we return 0 because no minting is needed. * * @param state Current state of the system. * @param _newCollateralRatio The desired new collateral ratio (scaled by 1e18). * @return _maxBaseIn The amount of base token required (corresponds to dn). * @return _maxATokenMintable The amount of stable coin token (aToken) that can be minted (corresponds to df). */ function maxMintableAToken( SwapState memory state, uint256 _newCollateralRatio ) internal pure returns (uint256 _maxBaseIn, uint256 _maxATokenMintable) { // Calculate scaled values uint256 _baseVal = state.baseSupply * (state.baseNav) * (PRECISION); uint256 _aVal = _newCollateralRatio * (state.aSupply) * state.aNav; // If baseVal > aVal, we can mint if (_baseVal > _aVal) { // Adjust ncr to (ncr - 1)*PRECISION _newCollateralRatio = _newCollateralRatio - (PRECISION); uint256 _delta = _baseVal - _aVal; // dn = delta / ((ncr - 1)*v) _maxBaseIn = _delta / (state.baseNav * (_newCollateralRatio)); // df = delta / ((ncr - 1)*vf) _maxATokenMintable = _delta / (state.aNav * (_newCollateralRatio)); } } /** * @notice Compute how much base token (dn) and leveraged tokens (xToken) can be minted to achieve a new collateral ratio, * if the current collateral ratio is less than the new target. * * Equations: * n * v = nf * vf + nx * vx * * After adding dn base tokens and dx leveraged tokens: * (n + dn)*v = nf*vf + (nx + dx)*vx * * The new collateral ratio condition: * ((n + dn)*v) / (nf*vf) = ncr * * From this, solving for dn and dx: * dn = (ncr * nf * vf - n * v) / v * dx = (ncr * nf * vf - n * v) / vx * * @dev If the current collateral ratio >= ncr, we return 0 because no minting is needed. * * @param state The current state. * @param _newCollateralRatio The desired new collateral ratio (scaled by 1e18). * @return _maxBaseIn The amount of base token needed (dn). * @return _maxXTokenMintable The amount of leveraged token (xToken) that can be minted (dx). */ function maxMintableXToken( SwapState memory state, uint256 _newCollateralRatio ) internal pure returns (uint256 _maxBaseIn, uint256 _maxXTokenMintable) { uint256 _baseVal = state.baseSupply * state.baseNav * PRECISION; uint256 _aVal = _newCollateralRatio * state.aSupply * state.aNav; if (_aVal > _baseVal) { uint256 _delta = _aVal - _baseVal; // dn = delta / (v * PRECISION) _maxBaseIn = _delta / (state.baseNav * (PRECISION)); // dx = delta / (vx * PRECISION) _maxXTokenMintable = _delta / (state.xNav * (PRECISION)); } } /** * @notice Compute how many stable coin tokens (aToken) can be redeemed and how much base token (dn) is released * to reach the new collateral ratio if the current ratio is greater than the target. * * Equations: * Initially: * n * v = nf * vf + nx * vx * * After removing dn base tokens and df stable coin tokens: * (n - dn)*v = (nf - df)*vf + nx*vx * * The new collateral ratio: * ((n - dn)*v) / ((nf - df)*vf) = ncr * * Solve these for df and dn: * df = (ncr * nf * vf - n * v) / ((ncr - 1)*vf) * dn = (ncr * nf * vf - n * v) / ((ncr - 1)*v) * * Here, df and dn now represent how many stable coin tokens and base tokens must be removed (redeemed) * to achieve ncr. If df > 0, it means we should redeem that many aTokens; if dn > 0, that many base tokens * can be released. * * @dev If the current collateral ratio <= ncr, no redemption is needed, so return 0. * * @param state Current state. * @param _newCollateralRatio Desired collateral ratio (scaled by 1e18). * @return _maxBaseOut The amount of base token released (dn). * @return _maxATokenRedeemable The amount of stable coin token that can be redeemed (df). */ function maxRedeemableAToken( SwapState memory state, uint256 _newCollateralRatio ) internal pure returns (uint256 _maxBaseOut, uint256 _maxATokenRedeemable) { uint256 _baseVal = state.baseSupply * (state.baseNav) * (PRECISION); uint256 _aVal = _newCollateralRatio * (state.aSupply) * (PRECISION); if (_aVal > _baseVal) { uint256 _delta = _aVal - _baseVal; // Adjust ncr to (ncr - 1)*PRECISION _newCollateralRatio = _newCollateralRatio - (PRECISION); // df = delta / ((ncr - 1)*vf) _maxATokenRedeemable = _delta / (_newCollateralRatio * (state.aNav)); // dn = delta / ((ncr - 1)*v) _maxBaseOut = _delta / (_newCollateralRatio * (state.baseNav)); } else { _maxBaseOut = 0; _maxATokenRedeemable = 0; } } /** * @notice Compute how many leveraged tokens (xToken) can be redeemed and how much base token is released * if the current collateral ratio is greater than the target. * * Equations: * n * v = nf * vf + nx * vx * * After removing dn base tokens and dx leveraged tokens: * (n - dn)*v = nf*vf + (nx - dx)*vx * * The new collateral ratio: * ((n - dn)*v) / (nf*vf) = ncr * * Solve for dn and dx: * dn = (n * v - ncr * nf * vf) / v * dx = (n * v - ncr * nf * vf) / vx * * If dn > 0, that means base tokens can be redeemed; if dx > 0, that many xTokens can be redeemed. * * @dev If current collateral ratio <= ncr, return 0. * * @param state Current state. * @param _newCollateralRatio Desired collateral ratio (scaled by 1e18). * @return _maxBaseOut The base token released (dn). * @return _maxXTokenRedeemable The leveraged tokens (xToken) redeemable (dx). */ function maxRedeemableXToken( SwapState memory state, uint256 _newCollateralRatio ) internal pure returns (uint256 _maxBaseOut, uint256 _maxXTokenRedeemable) { uint256 _baseVal = state.baseSupply * (state.baseNav) * (PRECISION); uint256 _aVal = _newCollateralRatio * (state.aSupply) * (state.aNav); if (_baseVal > _aVal) { uint256 _delta = _baseVal - _aVal; // dx = delta / (vx * PRECISION) _maxXTokenRedeemable = _delta / (state.xNav * (PRECISION)); // dn = delta / (v * PRECISION) _maxBaseOut = _delta / (state.baseNav * (PRECISION)); } else { _maxBaseOut = 0; _maxXTokenRedeemable = 0; } } /** * @notice Mint stable coin tokens (aToken) given a certain amount of base tokens (dn). * * Equations: * n * v = nf * vf + nx * vx * After adding dn base and df fraction tokens: * (n + dn)*v = (nf + df)*vf + nx*vx * * Solve for df given dn: * df = (dn * v) / vf * * @param state Current state. * @param _baseIn Amount of base token supplied. * @return _aTokenOut Amount of stable coin token minted (df). */ function mintAToken(SwapState memory state, uint256 _baseIn) internal pure returns (uint256 _aTokenOut) { // df = (dn * v) / vf _aTokenOut = (_baseIn * state.baseNav) / state.aNav; } /** * @notice Mint leveraged tokens (xToken) given a certain amount of base tokens (dn). * * Equations: * n * v = nf * vf + nx * vx * After adding dn base tokens and dx leveraged tokens: * (n + dn)*v = nf*vf + (nx + dx)*vx * * Solve for dx: * dx = (dn * v * nx) / (n * v - nf * vf) * * @param state Current state. * @param _baseIn Amount of base token supplied. * @return _xTokenOut Amount of leveraged token minted (dx). */ function mintXToken(SwapState memory state, uint256 _baseIn) internal pure returns (uint256 _xTokenOut) { // dx = (dn * v * nx) / (n * v - nf * vf) _xTokenOut = _baseIn * state.baseNav * state.xSupply; _xTokenOut = _xTokenOut / (state.baseSupply * state.baseNav - state.aSupply * state.aNav); } /** * @notice Redeem base tokens by supplying stable coin tokens (aToken) and/or leveraged tokens (xToken). * * Equations: * n * v = nf * vf + nx * vx * After removing df fraction tokens and dx leveraged tokens: * (n - dn)*v = (nf - df)*vf + (nx - dx)*vx * * The amount of baseOut (dn*v) depends on how many fraction and leveraged tokens are provided. * * If xSupply = 0 (no leveraged tokens): * baseOut = (aTokenIn * vf) / v * * If xSupply > 0: * baseOut = [ (aTokenIn * vf) + (xTokenIn * (n*v - nf*vf) / nx ) ] / v * * @param state Current state. * @param _aTokenIn stable coin tokens supplied. * @param _xTokenIn Leveraged tokens supplied. * @return _baseOut Amount of base token redeemed. */ function redeem(SwapState memory state, uint256 _aTokenIn, uint256 _xTokenIn) internal pure returns (uint256 _baseOut) { uint256 _xVal = state.baseSupply * state.baseNav - state.aSupply * state.aNav; if (state.xSupply == 0) { _baseOut = (_aTokenIn * state.aNav) / state.baseNav; } else { _baseOut = _aTokenIn * state.aNav; _baseOut += (_xTokenIn * _xVal) / state.xSupply; _baseOut /= state.baseNav; } } /** * @notice Compute the current leverage ratio for the xToken. * * Define: * rho = (aSupply * aNav) / (baseSupply * baseTwapNav) * * When beta = false, leverage ratio = 1 / (1 - rho) * If under-collateralized (rho >= 1), leverage ratio = MAX_LEVERAGE_RATIO * * @param state Current state. * @return ratio Current leverage ratio. */ function leverageRatio(SwapState memory state) internal pure returns (uint256 ratio) { if (state.beta) return PRECISION; if(state.baseSupply == 0 || state.baseNav == 0 || state.baseTwapNav == 0) return 0; // rho = (aSupply * aNav * PRECISION) / (baseSupply * baseTwapNav) uint256 rho = (state.aSupply * state.aNav * PRECISION) / (state.baseSupply * state.baseTwapNav); if (rho >= PRECISION) { // Under-collateralized ratio = MAX_LEVERAGE_RATIO; } else { // ratio = 1 / (1 - rho) ratio = (PRECISION * PRECISION) / (PRECISION - rho); if (ratio > MAX_LEVERAGE_RATIO) ratio = MAX_LEVERAGE_RATIO; } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { GroupId } from "../types/GroupId.sol"; // solhint-disable /// @title Library for reverting with custom errors efficiently /// @notice Contains functions for reverting with custom errors with different argument types efficiently /// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with /// `CustomError.selector.revertWith()` /// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately library CustomRevert { /// @dev Reverts with the selector of a custom error in the scratch space function revertWith(bytes4 selector) internal pure { assembly("memory-safe") { mstore(0, selector) revert(0, 0x04) } } /// @dev Reverts with a custom error with an address argument in the scratch space function revertWith(bytes4 selector, address addr) internal pure { assembly("memory-safe") { mstore(0, selector) mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x24) } } /// @dev Reverts with a custom error with an int24 argument in the scratch space function revertWith(bytes4 selector, int24 value) internal pure { assembly("memory-safe") { mstore(0, selector) mstore(0x04, signextend(2, value)) revert(0, 0x24) } } /// @dev Reverts with a custom error with a uint160 argument in the scratch space function revertWith(bytes4 selector, uint160 value) internal pure { assembly("memory-safe") { mstore(0, selector) mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x24) } } /// @dev Reverts with a custom error with two int24 arguments function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure { assembly("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), signextend(2, value1)) mstore(add(fmp, 0x24), signextend(2, value2)) revert(fmp, 0x44) } } /// @dev Reverts with a custom error with two uint160 arguments function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure { assembly("memory-safe") { let fmp := mload(0x40) mstore(fmp, selector) mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff)) revert(fmp, 0x44) } } /// @dev Reverts with a custom error with two address arguments function revertWith(bytes4 selector, address value1, address value2) internal pure { assembly("memory-safe") { mstore(0, selector) mstore(0x04, and(value1, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(0x24, and(value2, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0, 0x44) } } /// @dev Reverts with a custom error with a bytes32 argument in the scratch space function revertWith(bytes4 selector, bytes32 value) internal pure { assembly("memory-safe") { mstore(0, selector) mstore(0x04, value) revert(0, 0x24) } } /// @dev Reverts with a custom error with a bytes32 argument in the scratch space function revertWith(bytes4 selector, GroupId value) internal pure { bytes32 valueBytes = GroupId.unwrap(value); assembly("memory-safe") { mstore(0, selector) mstore(0x04, valueBytes) revert(0, 0x24) } } /// @dev Reverts with a custom error with a bytes32 and an address argument function revertWith(bytes4 selector, GroupId value, address addr) internal pure { bytes32 valueBytes = GroupId.unwrap(value); assembly("memory-safe") { mstore(0x00, selector) mstore(0x04, valueBytes) mstore(0x24, and(addr, 0xffffffffffffffffffffffffffffffffffffffff)) revert(0x00, 0x44) } } /// @dev Reverts with a custom error with a bytes32, address, and uint256 arguments function revertWith(bytes4 selector, GroupId value, address addr, uint256 amount) internal pure { bytes32 valueBytes = GroupId.unwrap(value); assembly("memory-safe") { mstore(0x00, selector) mstore(0x04, valueBytes) mstore(0x24, and(addr, 0xffffffffffffffffffffffffffffffffffffffff)) mstore(0x44, amount) revert(0x00, 0x64) } } /// @notice bubble up the revert message returned by a call and revert with the selector provided /// @dev this function should only be used with custom errors of the type `CustomError(address target, bytes revertReason)` function bubbleUpAndRevertWith(bytes4 selector, address addr) internal pure { assembly("memory-safe") { let size := returndatasize() let fmp := mload(0x40) // Encode selector, address, offset, size, data mstore(fmp, selector) mstore(add(fmp, 0x04), addr) mstore(add(fmp, 0x24), 0x40) mstore(add(fmp, 0x44), size) returndatacopy(add(fmp, 0x64), 0, size) // Ensure the size is a multiple of 32 bytes let encodedSize := add(0x64, mul(div(add(size, 31), 32), 32)) revert(fmp, encodedSize) } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { ExponentialMovingAverageV8 } from "../libs/math/ExponentialMovingAverageV8.sol"; library DTreasury { using ExponentialMovingAverageV8 for ExponentialMovingAverageV8.EMAStorage; struct GroupUpdateParams { uint256 baseTokenCaps; uint256 baseIn; bool beta; } struct TreasuryState { ExponentialMovingAverageV8.EMAStorage emaLeverageRatio; uint256 totalBaseTokens; uint256 baseTokenCaps; uint256 lastSettlementTimestamp; uint256 baseTokenPrice; bool inited; uint256 strategyUnderlying; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency } from "./Currency.sol"; import { DTokenRegistry } from "../declarations/DTokenRegistry.sol"; import { Address } from "../types/Address.sol"; // Enums representing different fee models that can be applied. enum OperationTypes { OP_TYPE_MINT_VT, OP_TYPE_MINT_YT, OP_TYPE_REDEEM_VT, OP_TYPE_REDEEM_YT } enum FeeModel { NONE, // No fees. MANAGEMENT_FEE, // Management fee model. VARIABLE_FUNDING_FEE, // Fee that varies based on funding. FIXED_FUNDING_FEE, // Fixed fee for funding. CURATED_PAIRS_FEE, // Curated pairs fee model. BLANK_FEE // Blank fee model. } // Information about acceptable collaterals struct CollateralInfo { Currency token; // Token address for collateral uint8 decimals; // Decimals for the collateral token uint256 minAmount; // Minimum amount for both usage minting and redeeming (as desired token) uint256 maxAmount; // Maximum amount for both usage minting and redeeming (as desired token) } // DefaultFeeParams defines the basic fee structure with base, min, and max fees. struct DefaultFeeParams { uint24 baseFee; // The base fee applied when no flags are present. uint24 minFee; // The minimum fee allowed for dynamic fee models. uint24 maxFee; // The maximum fee allowed. } // FeeParams defines specific fees for different token types and operations. struct FeeParams { uint24 mintFeeVT; // Minting fee for volatile tokens (VT). uint24 redeemFeeVT; // Redemption fee for volatile tokens (VT). uint24 mintFeeYT; // Minting fee for yield tokens (YT). uint24 redeemFeeYT; // Redemption fee for yield tokens (YT). uint24 stabilityMintFeeVT; // Stability minting fee for volatile tokens (VT). uint24 stabilityMintFeeYT; // Stability minting fee for yield tokens (YT). uint24 stabilityRedeemFeeVT; // Stability redemption fee for volatile tokens (VT). uint24 stabilityRedeemFeeYT; // Stability redemption fee for yield tokens (YT). uint24 yieldFeeVT; // Yield fee for volatile tokens (VT). uint24 yieldFeeYT; // Yield fee for yield tokens (YT). uint24 protocolFee; // Protocol fee. } // FeePermissions define the flexibility of the fee model (dynamic fees, delegation). struct FeePermissions { bool isDynamic; // Whether the fee model is dynamic. bool allowDelegation; // Whether fee delegation is allowed. } struct GroupState { DTokenRegistry.GroupCore core; DTokenRegistry.GroupExtended extended; bytes32 feesPacked; CollateralInfo[] acceptableCollaterals; Address hookContract; bytes32 groupSettings; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { DTokenRegistry } from "../declarations/DTokenRegistry.sol"; import { WordCodec } from "../libs/WordCodec.sol"; import { Address, AddressLibrary } from "../types/Address.sol"; import { Currency, CurrencyLibrary } from "../types/Currency.sol"; import { DefaultFeeParams, FeeParams, FeePermissions, CollateralInfo, GroupState } from "../types/CommonTypes.sol"; import { ITokenRegistry } from "../interfaces/ITokenRegistry.sol"; /** * @title GroupStateHelper * @notice Library for managing group settings and fee parameters in a space-efficient manner using bit packing * @dev Uses WordCodec for bit manipulation operations to store and retrieve various parameters */ type GroupSettings is bytes32; library GroupStateHelper { using WordCodec for bytes32; using CurrencyLibrary for Currency; using AddressLibrary for address; // Group Settings bit layout (total 256 bits): uint256 private constant A_TOKEN_DECIMALS_OFFSET = 0; // [0-7]: aToken decimals (8 bits) uint256 private constant X_TOKEN_DECIMALS_OFFSET = 8; // [8-15]: xToken decimals (8 bits) uint256 private constant BASE_TOKEN_DECIMALS_OFFSET = 16; // [16-23]: baseToken decimals (8 bits) uint256 private constant YIELD_BEARING_TOKEN_DECIMALS_OFFSET = 24; // [24-31]: yieldBearingToken decimals (8 bits) uint256 private constant HOOK_PERMISSIONS_OFFSET = 32; // [32-47]: hook permissions (16 bits) uint256 private constant FEE_PERMISSIONS_OFFSET = 48; // [48-49]: fee permissions (2 bits) uint256 private constant FEE_MODEL_OFFSET = 50; // [50-57]: fee model (8 bits) uint256 private constant WRAPPING_REQUIRED_OFFSET = 58; // [58]: wrapping required (1 bit) uint256 private constant STABILITY_RATIO_OFFSET = 59; // [59-154]: stability ratio (96 bits) uint256 private constant STABILITY_TRIGGER_RATIO_OFFSET = 155; // [155-250]: stability triggering ratio (96 bits) // Fee Parameters bit layout (total 256 bits): uint256 private constant MAX_FEE_OFFSET = 0; // [0-15]: max fee (16 bits) uint256 private constant MIN_FEE_OFFSET = 16; // [16-31]: min fee (16 bits) uint256 private constant BASE_FEE_OFFSET = 32; // [32-47]: base fee (16 bits) uint256 private constant YIELD_FEE_VT_OFFSET = 48; // [48-63]: yield fee VT (16 bits) uint256 private constant YIELD_FEE_YT_OFFSET = 64; // [64-79]: yield fee YT (16 bits) uint256 private constant REDEEM_FEE_YT_OFFSET = 80; // [80-103]: redeem fee YT (24 bits) uint256 private constant MINT_FEE_YT_OFFSET = 104; // [104-127]: mint fee YT (24 bits) uint256 private constant REDEEM_FEE_VT_OFFSET = 128; // [128-151]: redeem fee VT (24 bits) uint256 private constant MINT_FEE_VT_OFFSET = 152; // [152-175]: mint fee VT (24 bits) uint256 private constant STABILITY_MINT_FEE_VT_OFFSET = 176; // [176-191]: stability mint fee VT (16 bits) uint256 private constant STABILITY_MINT_FEE_YT_OFFSET = 192; // [192-207]: stability mint fee YT (16 bits) uint256 private constant STABILITY_REDEEM_FEE_VT_OFFSET = 208; // [208-223]: stability redeem fee VT (16 bits) uint256 private constant STABILITY_REDEEM_FEE_YT_OFFSET = 224; // [224-239]: stability redeem fee YT (16 bits) uint256 private constant PROTOCOL_FEE_OFFSET = 240; // [240-255]: protocol fee (16 bits) // Common bit lengths uint256 private constant LENGTH_1BIT = 1; uint256 private constant LENGTH_2BITS = 2; uint256 private constant LENGTH_8BITS = 8; uint256 private constant LENGTH_16BITS = 16; uint256 private constant LENGTH_24BITS = 24; uint256 private constant LENGTH_96BITS = 96; /** * @notice Retrieves the aToken decimals from group settings * @param groupSettings The packed group settings * @return The aToken decimals */ function getATokenDecimals(GroupSettings groupSettings) internal pure returns (uint8) { return uint8(GroupSettings.unwrap(groupSettings).decodeUint(A_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS)); } /** * @notice Retrieves the xToken decimals from group settings * @param groupSettings The packed group settings * @return The xToken decimals */ function getXTokenDecimals(GroupSettings groupSettings) internal pure returns (uint8) { return uint8(GroupSettings.unwrap(groupSettings).decodeUint(X_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS)); } /** * @notice Retrieves the baseToken decimals from group settings * @param groupSettings The packed group settings * @return The baseToken decimals */ function getBaseTokenDecimals(GroupSettings groupSettings) internal pure returns (uint8) { return uint8(GroupSettings.unwrap(groupSettings).decodeUint(BASE_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS)); } /** * @notice Retrieves the yieldBearingToken decimals from group settings * @param groupSettings The packed group settings * @return The yieldBearingToken decimals */ function getYieldBearingTokenDecimals(GroupSettings groupSettings) internal pure returns (uint8) { return uint8(GroupSettings.unwrap(groupSettings).decodeUint(YIELD_BEARING_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS)); } /** * @notice Retrieves the hook permissions from group settings * @param groupSettings The packed group settings * @return The hook permissions */ function getHookPermissions(GroupSettings groupSettings) internal pure returns (uint16) { return uint16(GroupSettings.unwrap(groupSettings).decodeUint(HOOK_PERMISSIONS_OFFSET, LENGTH_16BITS)); } /** * @notice Retrieves the fee permissions from group settings * @param groupSettings The packed group settings * @return FeePermissions struct containing permission flags */ function getFeePermissions(GroupSettings groupSettings) internal pure returns (FeePermissions memory) { bytes32 raw = GroupSettings.unwrap(groupSettings); return FeePermissions({ isDynamic: raw.decodeBool(FEE_PERMISSIONS_OFFSET + 1), allowDelegation: raw.decodeBool(FEE_PERMISSIONS_OFFSET) }); } /** * @notice Retrieves the fee model from group settings * @param groupSettings The packed group settings * @return The fee model */ function getFeeModel(GroupSettings groupSettings) internal pure returns (uint8) { return uint8(GroupSettings.unwrap(groupSettings).decodeUint(FEE_MODEL_OFFSET, LENGTH_8BITS)); } /** * @notice Checks if wrapping is required from group settings * @param groupSettings The packed group settings * @return True if wrapping is required, false otherwise */ function isWrappingRequired(GroupSettings groupSettings) internal pure returns (bool) { return GroupSettings.unwrap(groupSettings).decodeBool(WRAPPING_REQUIRED_OFFSET); } /** * @notice Retrieves the stability ratio from group settings * @param groupSettings The packed group settings * @return The stability ratio (scaled by 1e18) */ function getStabilityRatio(GroupSettings groupSettings) internal pure returns (uint96) { return uint96(GroupSettings.unwrap(groupSettings).decodeUint(STABILITY_RATIO_OFFSET, LENGTH_96BITS)); } /** * @notice Retrieves the stability triggering ratio from group settings * @param groupSettings The packed group settings * @return The stability triggering ratio (scaled by 1e18) */ function getStabilityTriggeringRatio(GroupSettings groupSettings) internal pure returns (uint96) { return uint96(GroupSettings.unwrap(groupSettings).decodeUint(STABILITY_TRIGGER_RATIO_OFFSET, LENGTH_96BITS)); } /** * @notice Sets the aToken decimals in group settings * @param groupSettings Current group settings * @param decimals The new aToken decimals * @return Updated group settings */ function setATokenDecimals(GroupSettings groupSettings, uint8 decimals) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(decimals), A_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the xToken decimals in group settings * @param groupSettings Current group settings * @param decimals The new xToken decimals * @return Updated group settings */ function setXTokenDecimals(GroupSettings groupSettings, uint8 decimals) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(decimals), X_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the baseToken decimals in group settings * @param groupSettings Current group settings * @param decimals The new baseToken decimals * @return Updated group settings */ function setBaseTokenDecimals(GroupSettings groupSettings, uint8 decimals) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(decimals), BASE_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the yieldBearingToken decimals in group settings * @param groupSettings Current group settings * @param decimals The new yieldBearingToken decimals * @return Updated group settings */ function setYieldBearingTokenDecimals(GroupSettings groupSettings, uint8 decimals) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(decimals), YIELD_BEARING_TOKEN_DECIMALS_OFFSET, LENGTH_8BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the hook permissions in group settings * @param groupSettings Current group settings * @param hookPermissions The new hook permissions * @return Updated group settings */ function setHookPermissions(GroupSettings groupSettings, uint16 hookPermissions) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(hookPermissions), HOOK_PERMISSIONS_OFFSET, LENGTH_16BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the fee permissions in group settings * @param groupSettings Current group settings * @param permissions The new fee permissions * @return Updated group settings */ function setFeePermissions(GroupSettings groupSettings, FeePermissions memory permissions) internal pure returns (GroupSettings) { bytes32 raw = GroupSettings.unwrap(groupSettings); raw = raw.insertBool(permissions.allowDelegation, FEE_PERMISSIONS_OFFSET); raw = raw.insertBool(permissions.isDynamic, FEE_PERMISSIONS_OFFSET + 1); return GroupSettings.wrap(raw); } /** * @notice Sets the fee model in group settings * @param groupSettings Current group settings * @param feeModel The new fee model * @return Updated group settings */ function setFeeModel(GroupSettings groupSettings, uint8 feeModel) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(feeModel), FEE_MODEL_OFFSET, LENGTH_8BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the wrapping required flag in group settings * @param groupSettings Current group settings * @param wrappingRequired The new wrapping required flag * @return Updated group settings */ function setWrappingRequired(GroupSettings groupSettings, bool wrappingRequired) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertBool(wrappingRequired, WRAPPING_REQUIRED_OFFSET); return GroupSettings.wrap(updated); } /** * @notice Sets the stability ratio in group settings * @param groupSettings Current group settings * @param stabilityRatio The new stability ratio (scaled by 1e18) * @return Updated group settings */ function setStabilityRatio(GroupSettings groupSettings, uint96 stabilityRatio) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint(uint256(stabilityRatio), STABILITY_RATIO_OFFSET, LENGTH_96BITS); return GroupSettings.wrap(updated); } /** * @notice Sets the stability triggering ratio in group settings * @param groupSettings Current group settings * @param stabilityTriggeringRatio The new stability triggering ratio (scaled by 1e18) * @return Updated group settings */ function setStabilityTriggeringRatio(GroupSettings groupSettings, uint96 stabilityTriggeringRatio) internal pure returns (GroupSettings) { bytes32 updated = GroupSettings.unwrap(groupSettings).insertUint( uint256(stabilityTriggeringRatio), STABILITY_TRIGGER_RATIO_OFFSET, LENGTH_96BITS ); return GroupSettings.wrap(updated); } /** * @notice Retrieves all fee parameters from packed fees * @param feesPacked The packed fees * @return FeeParams struct containing all fee parameters */ function getFeeParams(bytes32 feesPacked) internal pure returns (FeeParams memory) { return FeeParams({ mintFeeVT: uint24(feesPacked.decodeUint(MINT_FEE_VT_OFFSET, LENGTH_24BITS)), redeemFeeVT: uint24(feesPacked.decodeUint(REDEEM_FEE_VT_OFFSET, LENGTH_24BITS)), mintFeeYT: uint24(feesPacked.decodeUint(MINT_FEE_YT_OFFSET, LENGTH_24BITS)), redeemFeeYT: uint24(feesPacked.decodeUint(REDEEM_FEE_YT_OFFSET, LENGTH_24BITS)), // Upcast 16-bit stability fees to 24-bit stabilityMintFeeVT: uint24(uint16(feesPacked.decodeUint(STABILITY_MINT_FEE_VT_OFFSET, LENGTH_16BITS))), stabilityMintFeeYT: uint24(uint16(feesPacked.decodeUint(STABILITY_MINT_FEE_YT_OFFSET, LENGTH_16BITS))), stabilityRedeemFeeVT: uint24(uint16(feesPacked.decodeUint(STABILITY_REDEEM_FEE_VT_OFFSET, LENGTH_16BITS))), stabilityRedeemFeeYT: uint24(uint16(feesPacked.decodeUint(STABILITY_REDEEM_FEE_YT_OFFSET, LENGTH_16BITS))), // Upcast 16-bit yield fees to 24-bit yieldFeeVT: uint24(uint16(feesPacked.decodeUint(YIELD_FEE_VT_OFFSET, LENGTH_16BITS))), yieldFeeYT: uint24(uint16(feesPacked.decodeUint(YIELD_FEE_YT_OFFSET, LENGTH_16BITS))), protocolFee: uint16(feesPacked.decodeUint(PROTOCOL_FEE_OFFSET, LENGTH_16BITS)) }); } /** * @notice Retrieves the default fee parameters from packed fees * @param feesPacked The packed fees * @return DefaultFeeParams struct containing min, max and base fees */ function getDefaultFeeParams(bytes32 feesPacked) internal pure returns (DefaultFeeParams memory) { return DefaultFeeParams({ baseFee: uint24(feesPacked.decodeUint(BASE_FEE_OFFSET, LENGTH_16BITS)), maxFee: uint16(feesPacked.decodeUint(MAX_FEE_OFFSET, LENGTH_16BITS)), minFee: uint16(feesPacked.decodeUint(MIN_FEE_OFFSET, LENGTH_16BITS)) }); } /** * @notice Retrieves the max fee from packed fees * @param feesPacked The packed fees * @return The max fee value (24-bit) */ function getMaxFee(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(MAX_FEE_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the min fee from packed fees * @param feesPacked The packed fees * @return The min fee value (24-bit) */ function getMinFee(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(MIN_FEE_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the base fee from packed fees * @param feesPacked The packed fees * @return The base fee value (24-bit) */ function getBaseFee(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(BASE_FEE_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the yield fee VT from packed fees * @param feesPacked The packed fees * @return The yield fee VT value (24-bit) */ function getYieldFeeVT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(YIELD_FEE_VT_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the yield fee YT from packed fees * @param feesPacked The packed fees * @return The yield fee YT value (24-bit) */ function getYieldFeeYT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(YIELD_FEE_YT_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the mint fee VT from packed fees * @param feesPacked The packed fees * @return The mint fee VT value (24-bit) */ function getMintFeeVT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(feesPacked.decodeUint(MINT_FEE_VT_OFFSET, LENGTH_24BITS)); } /** * @notice Retrieves the redeem fee VT from packed fees * @param feesPacked The packed fees * @return The redeem fee VT value (24-bit) */ function getRedeemFeeVT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(feesPacked.decodeUint(REDEEM_FEE_VT_OFFSET, LENGTH_24BITS)); } /** * @notice Retrieves the mint fee YT from packed fees * @param feesPacked The packed fees * @return The mint fee YT value (24-bit) */ function getMintFeeYT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(feesPacked.decodeUint(MINT_FEE_YT_OFFSET, LENGTH_24BITS)); } /** * @notice Retrieves the redeem fee YT from packed fees * @param feesPacked The packed fees * @return The redeem fee YT value (24-bit) */ function getRedeemFeeYT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(feesPacked.decodeUint(REDEEM_FEE_YT_OFFSET, LENGTH_24BITS)); } /** * @notice Retrieves the stability mint fee VT from packed fees * @param feesPacked The packed fees * @return The stability mint fee VT value (24-bit) */ function getStabilityMintFeeVT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(STABILITY_MINT_FEE_VT_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the stability mint fee YT from packed fees * @param feesPacked The packed fees * @return The stability mint fee YT value (24-bit) */ function getStabilityMintFeeYT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(STABILITY_MINT_FEE_YT_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the stability redeem fee VT from packed fees * @param feesPacked The packed fees * @return The stability redeem fee VT value (24-bit) */ function getStabilityRedeemFeeVT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(STABILITY_REDEEM_FEE_VT_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the stability redeem fee YT from packed fees * @param feesPacked The packed fees * @return The stability redeem fee YT value (24-bit) */ function getStabilityRedeemFeeYT(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(STABILITY_REDEEM_FEE_YT_OFFSET, LENGTH_16BITS))); } /** * @notice Retrieves the protocol fee from packed fees * @param feesPacked The packed fees * @return The protocol fee value (24-bit) */ function getProtocolFee(bytes32 feesPacked) internal pure returns (uint24) { return uint24(uint16(feesPacked.decodeUint(PROTOCOL_FEE_OFFSET, LENGTH_16BITS))); } /** * @notice Sets the max fee in packed fees * @param feesPacked Current packed fees * @param maxFee The new max fee value (truncated to 16-bit) * @return Updated packed fees */ function setMaxFee(bytes32 feesPacked, uint24 maxFee) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(maxFee)), MAX_FEE_OFFSET, LENGTH_16BITS); } /** * @notice Sets the min fee in packed fees * @param feesPacked Current packed fees * @param minFee The new min fee value (truncated to 16-bit) * @return Updated packed fees */ function setMinFee(bytes32 feesPacked, uint24 minFee) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(minFee)), MIN_FEE_OFFSET, LENGTH_16BITS); } /** * @notice Sets the base fee in packed fees * @param feesPacked Current packed fees * @param baseFee The new base fee value (truncated to 16-bit) * @return Updated packed fees */ function setBaseFee(bytes32 feesPacked, uint24 baseFee) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(baseFee)), BASE_FEE_OFFSET, LENGTH_16BITS); } /** * @notice Sets the yield fee VT in packed fees * @param feesPacked Current packed fees * @param yieldFeeVT The new yield fee VT value (truncated to 16-bit) * @return Updated packed fees */ function setYieldFeeVT(bytes32 feesPacked, uint24 yieldFeeVT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(yieldFeeVT)), YIELD_FEE_VT_OFFSET, LENGTH_16BITS); } /** * @notice Sets the yield fee YT in packed fees * @param feesPacked Current packed fees * @param yieldFeeYT The new yield fee YT value (truncated to 16-bit) * @return Updated packed fees */ function setYieldFeeYT(bytes32 feesPacked, uint24 yieldFeeYT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(yieldFeeYT)), YIELD_FEE_YT_OFFSET, LENGTH_16BITS); } /** * @notice Sets the mint fee VT in packed fees * @param feesPacked Current packed fees * @param mintFeeVT The new mint fee VT value * @return Updated packed fees */ function setMintFeeVT(bytes32 feesPacked, uint24 mintFeeVT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(mintFeeVT), MINT_FEE_VT_OFFSET, LENGTH_24BITS); } /** * @notice Sets the redeem fee VT in packed fees * @param feesPacked Current packed fees * @param redeemFeeVT The new redeem fee VT value * @return Updated packed fees */ function setRedeemFeeVT(bytes32 feesPacked, uint24 redeemFeeVT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(redeemFeeVT), REDEEM_FEE_VT_OFFSET, LENGTH_24BITS); } /** * @notice Sets the mint fee YT in packed fees * @param feesPacked Current packed fees * @param mintFeeYT The new mint fee YT value * @return Updated packed fees */ function setMintFeeYT(bytes32 feesPacked, uint24 mintFeeYT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(mintFeeYT), MINT_FEE_YT_OFFSET, LENGTH_24BITS); } /** * @notice Sets the redeem fee YT in packed fees * @param feesPacked Current packed fees * @param redeemFeeYT The new redeem fee YT value * @return Updated packed fees */ function setRedeemFeeYT(bytes32 feesPacked, uint24 redeemFeeYT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(redeemFeeYT), REDEEM_FEE_YT_OFFSET, LENGTH_24BITS); } /** * @notice Sets the stability mint fee VT in packed fees * @param feesPacked Current packed fees * @param stabilityMintFeeVT The new stability mint fee VT value (truncated to 16-bit) * @return Updated packed fees */ function setStabilityMintFeeVT(bytes32 feesPacked, uint24 stabilityMintFeeVT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(stabilityMintFeeVT)), STABILITY_MINT_FEE_VT_OFFSET, LENGTH_16BITS); } /** * @notice Sets the stability mint fee YT in packed fees * @param feesPacked Current packed fees * @param stabilityMintFeeYT The new stability mint fee YT value (truncated to 16-bit) * @return Updated packed fees */ function setStabilityMintFeeYT(bytes32 feesPacked, uint24 stabilityMintFeeYT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(stabilityMintFeeYT)), STABILITY_MINT_FEE_YT_OFFSET, LENGTH_16BITS); } /** * @notice Sets the stability redeem fee VT in packed fees * @param feesPacked Current packed fees * @param stabilityRedeemFeeVT The new stability redeem fee VT value (truncated to 16-bit) * @return Updated packed fees */ function setStabilityRedeemFeeVT(bytes32 feesPacked, uint24 stabilityRedeemFeeVT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(stabilityRedeemFeeVT)), STABILITY_REDEEM_FEE_VT_OFFSET, LENGTH_16BITS); } /** * @notice Sets the stability redeem fee YT in packed fees * @param feesPacked Current packed fees * @param stabilityRedeemFeeYT The new stability redeem fee YT value (truncated to 16-bit) * @return Updated packed fees */ function setStabilityRedeemFeeYT(bytes32 feesPacked, uint24 stabilityRedeemFeeYT) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(stabilityRedeemFeeYT)), STABILITY_REDEEM_FEE_YT_OFFSET, LENGTH_16BITS); } /** * @notice Sets the protocol fee in packed fees * @param feesPacked Current packed fees * @param protocolFee The new protocol fee value (truncated to 16-bit) * @return Updated packed fees */ function setProtocolFee(bytes32 feesPacked, uint24 protocolFee) internal pure returns (bytes32) { return feesPacked.insertUint(uint256(uint16(protocolFee)), PROTOCOL_FEE_OFFSET, LENGTH_16BITS); } // Group Core Components Getters /** * @notice Retrieves the hook contract from group state * @param groupState The group state * @return The hook contract address wrapper */ function getHookContract(GroupState memory groupState) internal pure returns (Address) { return groupState.hookContract; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ 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, an admin role * bearer except when using {AccessControl-_setupRole}. */ 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 `account`. */ function renounceRole(bytes32 role, address account) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol) pragma solidity ^0.8.0; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/MathUpgradeable.sol"; import "./math/SignedMathUpgradeable.sol"; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = MathUpgradeable.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, MathUpgradeable.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 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); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency } from "../types/Currency.sol"; import { Address } from "../types/Address.sol"; import { DefaultFeeParams, FeeParams, FeePermissions, CollateralInfo } from "../types/CommonTypes.sol"; library DTokenRegistry { // Core tokens of the group (immutable) struct GroupCore { Currency aToken; // Yield-bearing token Currency xToken; // Leverage token Currency baseToken; // Base token for the group - wrapped Avax Currency yieldBearingToken; // Example: staked AVAX (immutable) Currency wethToken; // WETH token address for the router } // Decimals for each core token struct GroupDecimals { uint8 aTokenDecimals; uint8 xTokenDecimals; uint8 baseTokenDecimals; uint8 yieldBearingTokenDecimals; } // Extended group settings (mutable) struct GroupExtended { Address priceOracle; // Price Oracle address Address rateProvider; // Rate provider address Address swapRouter; // Swap Router Address treasury; // Treasury address Address feeCollector; // Fee collector address Address strategy; // Strategy contract address Currency rebalancePool; // Rebalance pool address } // Metadata for the group (partially mutable) struct GroupMeta { uint96 stabilityRatio; // Mutable stability ratio (this is 2^96-1 and we have max 5e18) uint96 stabilityConditionsTriggeringRate; // Mutable stability fee trigger (this is 2^96-1 and we have max 5e18) uint8 feeModel; // Immutable fee model used for this group bool isWrappingRequired; // Immutable wrapping requirement flag } // Struct representing full group setup during creation struct GroupSetup { GroupCore core; GroupDecimals decimals; GroupExtended extended; GroupMeta meta; FeeParams fees; DefaultFeeParams defaultFees; FeePermissions feePermissions; CollateralInfo[] acceptableCollaterals; } // Data used for updating mutable parts of the group struct GroupUpdate { GroupExtended extended; GroupMeta meta; CollateralInfo[] acceptableCollaterals; FeeParams feeParams; DefaultFeeParams defaultFees; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { LogExpMathV8 } from "./LogExpMathV8.sol"; // solhint-disable not-rely-on-time /// @dev See https://en.wikipedia.org/wiki/Exponential_smoothing /// It is the same as `ExponentialMovingAverageV7` with `unchecked` scope. library ExponentialMovingAverageV8 { /************* * Constants * *************/ /// @dev The precision used to compute EMA. uint256 private constant PRECISION = 1e18; /*********** * Structs * ***********/ /// @dev Compiler will pack this into single `uint256`. /// @param lastTime The last timestamp when the storage is updated. /// @param sampleInterval The sampling time interval used in the EMA. /// @param lastValue The last value in the data sequence, with precision 1e18. /// @param lastEmaValue The last EMA value computed, with precision 1e18. struct EMAStorage { uint40 lastTime; uint24 sampleInterval; uint96 lastValue; uint96 lastEmaValue; } /// @dev Save value of EMA storage. /// @param s The EMA storage. /// @param value The new value, with precision 1e18. function saveValue(EMAStorage storage s, uint96 value) internal { s.lastEmaValue = uint96(emaValue(s)); s.lastValue = value; s.lastTime = uint40(block.timestamp); } /// @dev Return the current ema value. /// @param s The EMA storage. function emaValue(EMAStorage storage s) internal view returns (uint256) { unchecked { if (uint256(s.lastTime) < block.timestamp) { uint256 dt = block.timestamp - uint256(s.lastTime); uint256 e = (dt * PRECISION) / s.sampleInterval; if (e > 41e18) { return s.lastValue; } else { uint256 alpha = uint256(LogExpMathV8.exp(-int256(e))); return (s.lastValue * (PRECISION - alpha) + s.lastEmaValue * alpha) / PRECISION; } } else { return s.lastEmaValue; } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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 amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` 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 amount) external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import { GroupId } from "../types/GroupId.sol"; /** * @title IAToken * @notice Interface for AToken, an ERC20-compatible token with minting, burning, and * additional functionality for treasury and rebalance management. */ interface IAToken is IERC20Upgradeable { /** * @dev Emitted when the treasury address is updated. * @param oldTreasury The previous treasury address. * @param newTreasury The new treasury address. */ event UpdateTreasuryAddress(address indexed oldTreasury, address indexed newTreasury); /** * @dev Emitted when the rebalance pool address is updated. * @param oldRebalancePool The previous rebalance pool address. * @param newRebalancePool The new rebalance pool address. */ event UpdateRebalancePool(address indexed oldRebalancePool, address indexed newRebalancePool); /** * @dev Emitted when tokens are minted to an address. * @param to The address receiving the minted tokens. * @param amount The amount of tokens minted. */ event Minted(address indexed to, uint256 indexed amount); /** * @dev Emitted when tokens are burned from an address. * @param from The address from which tokens are burned. * @param amount The amount of tokens burned. */ event Burned(address indexed from, uint256 indexed amount); /** * @dev Emitted when a group is updated. * @param groupId The identifier of the updated group. */ event UpdateGroup(GroupId indexed groupId); /** * @dev Emitted when the max supply is updated. * @param oldMaxSupply The previous max supply. * @param newMaxSupply The new max supply. */ event UpdateMaxSupply(uint256 indexed oldMaxSupply, uint256 indexed newMaxSupply); // Custom Errors error InvalidDecimals(); error ErrorNotPermitted(); error ErrorZeroAddress(); error ErrorZeroAmount(); error ErrorExceedsMaxSupply(); error ErrorCannotRecoverToken(); error ErrorParameterUnchanged(); /** * @notice Returns the beta status of the token. */ function beta() external view returns (bool); /** * @notice Returns the Net Asset Value (NAV) of the token. * @return The current NAV as an unsigned integer. */ function nav() external view returns (uint256); /** * @notice Returns the number of decimals used by the token. * @return The number of decimals. */ function decimals() external view returns (uint8); /** * @notice Mints tokens to a specified address. * @dev Emits a {Minted} event. * @param _to The address to receive the minted tokens. * @param _amount The amount of tokens to mint. */ function mint(address _to, uint256 _amount) external; /** * @notice Burns tokens from a specified address. * @dev Emits a {Burned} event. * @param _from The address from which tokens are burned. * @param _amount The amount of tokens to burn. */ function burn(address _from, uint256 _amount) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; interface IDEXRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); // function getAmountsOut( // uint256 amountIn, // address[] calldata path // ) external view returns (uint256[] memory amounts); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; interface IStrategy { error ErrorNotPermitted(); error ErrorZeroAmount(); error ErrorZeroAddress(); error ErrorCannotRecoverToken(); error ZeroGroupId(); function withdrawToTreasury(uint256 _diff) external returns (bool); function emergencyWithdraw() external returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // solhint-disable /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0 = a * b; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly ("memory-safe") { let mm := mulmod(a, b, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1, "FullMath: denominator too small"); // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { assembly ("memory-safe") { result := div(prod0, denominator) } return result; } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly ("memory-safe") { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly ("memory-safe") { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (0 - denominator) & denominator; // Divide denominator by power of two assembly ("memory-safe") { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly ("memory-safe") { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly ("memory-safe") { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // 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**256. Since the preconditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) { unchecked { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) != 0) { require(++result > 0, "FullMath: addition overflow"); } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import { FeeModel } from "../types/CommonTypes.sol"; interface IDXToken is IERC20Upgradeable { /********** * Events * **********/ /// @notice Emitted when the cooling-off period is updated. /// @param oldValue The value of the previous cooling-off period. /// @param newValue The value of the current cooling-off period. event UpdateCoolingOffPeriod(uint256 indexed oldValue, uint256 indexed newValue); /// @notice Emitted when the management fee rate is updated. /// @param oldRate The previous management fee rate. /// @param newRate The new management fee rate. event UpdateManagementFeeRate(uint256 indexed oldRate, uint256 indexed newRate); /// @notice Emitted when the funding fee rate is updated. /// @param oldRate The previous funding fee rate. /// @param newRate The new funding fee rate. event UpdateFundingFeeRate(uint256 indexed oldRate, uint256 indexed newRate); /// @notice Emitted when the fixed yield amount is updated. /// @param oldRate The previous fixed yield amount. /// @param newRate The new fixed yield amount. event UpdateVariableFundingFeeRate(uint256 indexed oldRate, uint256 indexed newRate); /// @notice Emitted when fees are collected. /// @param amount The amount of fees collected. event FeesCollected(uint256 indexed amount); /// @notice Emitted when tokens are minted. /// @param to The address receiving the minted tokens. /// @param amount The amount of tokens minted. event Minted(address indexed to, uint256 indexed amount); /// @notice Emitted when tokens are burned. /// @param from The address whose tokens are burned. /// @param amount The amount of tokens burned. event Burned(address indexed from, uint256 indexed amount); /// @notice Emitted when the cooling-off period is triggered. /// @param account The account triggering the cooling-off period. /// @param timestamp The timestamp when triggered. event CoolingOffPeriodTriggered(address indexed account, uint256 indexed timestamp); /// @notice Emitted when the associated group is updated. /// @param groupId The new associated group ID. event UpdateGroup(bytes32 indexed groupId); /// @notice Emitted when the treasury address is updated. /// @param oldTreasury The old treasury address. /// @param newTreasury The new treasury address. event UpdateTreasuryAddress(address indexed oldTreasury, address indexed newTreasury); /// @notice Emitted when the max supply is updated. /// @param oldMaxSupply The old max supply. /// @param newMaxSupply The new max supply. event UpdateMaxSupply(uint256 indexed oldMaxSupply, uint256 indexed newMaxSupply); /********** * Errors * **********/ /// @dev Thrown when an address is zero. error ZeroAddress(); /// @dev Thrown when decimals are invalid. error InvalidDecimals(); /// @dev Thrown when the cooling-off period is too large. error CoolingOffPeriodTooLarge(); /// @dev Thrown when trying to mint or burn an amount below the minimum. error ErrorMinimumMintingAmount(); /// @dev Thrown when trying to burn an amount below the minimum. error ErrorMinimumBurningAmount(); /// @dev Thrown when minting exceeds the max supply. error ExceedsMaxSupply(); /// @dev Thrown when cooling-off period is active. error CoolingOffPeriodActive(); /// @dev Thrown when parameter is unchanged. error ParameterUnchanged(); /// @dev Thrown when management fee is invalid. error InvalidManagementFee(); /// @dev Thrown when funding fee rate is invalid. error InvalidFundingFeeRate(); /// @dev Thrown when fixed yield amount is invalid. error InvalidFixedYieldAmount(); /// @dev Thrown when fee model is invalid. error InvalidFeeModel(); /// @dev Thrown when base supply is zero. error BaseSupplyZero(); /// @dev Thrown when transfer amount exceeds balance. error TransferAmountExceedsBalance(); /// @dev Thrown when burn amount exceeds balance. error BurnAmountExceedsBalance(); /// @dev Thrown cannot recover token. error CannotRecoverToken(); /// @dev Thrown when invalid base token price. error InvalidBaseTokenPrice(); /// @dev Thrown when an operation is not permitted. error NotPermitted(); /************************* * Public View Functions * *************************/ /// @notice Returns the NAV of the token. function nav() external view returns (uint256); /// @notice Converts DXToken amount to base token amount. function dxTokenToBaseToken(uint256 dxTokenAmount) external view returns (uint256 baseTokenAmount); /// @notice Returns the fee model. function getFeeModel() external view returns (FeeModel); /**************************** * Public Mutated Functions * ****************************/ /// @notice Mints tokens to a specified address. function mint(address _to, uint256 _amount) external; /// @notice Burns tokens from a specified address. function burn(address _from, uint256 _amount) external; /// @notice Collects accumulated fees. function collectFees() external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import { GroupId } from "../types/GroupId.sol"; /** * @title IWToken * @notice Interface for the WToken contract, enabling wrapping and unwrapping of an underlying token. */ interface IWToken is IERC20Upgradeable { /** * @dev Emitted when tokens are wrapped into WTokens. * @param user The address of the user wrapping tokens. * @param underlyingAmount The amount of underlying tokens wrapped. * @param amount The amount of tokens wrapped. */ event TokenWrapped(address indexed user, uint256 indexed underlyingAmount, uint256 indexed amount); /** * @dev Emitted when WTokens are unwrapped into underlying tokens. * @param user The address of the user unwrapping tokens. * @param underlyingAmount The amount of underlying tokens unwrapped. * @param amount The amount of WTokens unwrapped. */ event TokenUnwrapped(address indexed user, uint256 indexed underlyingAmount, uint256 indexed amount); /** * @dev Emitted when the treasury address is updated. * @param oldTreasury The address of the previous treasury contract. * @param newTreasury The address of the new treasury contract. */ event UpdateTreasuryAddress(address indexed oldTreasury, address indexed newTreasury); /** * @dev Emitted when the associated group ID is updated. * @param groupId New group identifier. */ event UpdateGroup(GroupId indexed groupId); event Rebase(uint256 indexed epoch, uint256 indexed newScalar); event RateProviderUpdated(address indexed rateProvider); // Custom Errors error ErrorZeroAddress(); error InvalidDecimals(); error ErrorZeroAmount(); error ErrorNotPermitted(); error ErrorCannotRecoverToken(); error ErrorMaxUnderlyingExceeded(); /** * @notice Wraps underlying tokens into WTokens. * @param underlyingAmount The amount of underlying tokens to wrap. * @return wrappedAmount amount of WTokens minted. */ function wrap(uint256 underlyingAmount) external returns (uint256 wrappedAmount); /** * @notice Unwraps WTokens back into underlying tokens. * @param burnAmount The amount of WTokens to burn. * @return amount of underlying tokens returned. */ function unwrap(uint256 burnAmount) external returns (uint256 amount); /** * @notice rebase the WToken */ function rebase() external; function updateRateProvider(address _rateProvider) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { IERC4626Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol"; /** * @title IRebalancePool * @notice Interface for the RebalancePool contract implementing ERC4626 */ interface IRebalancePool is IERC4626Upgradeable { /// @notice Errors error ZeroAddress(); error ZeroDeposit(); error InvalidDepositAmount(); error ZeroRedeem(); error TokenAlreadyAdded(address token); error ZeroShares(); error InvalidPriceFromOracle(); error NotPermitted(); error InvalidYieldFee(); error RedeemingNotAvailableYet(); error CannotRecoverToken(); error UpdatingNotAvailableYet(); error InvalidCoolingPeriod(); error CoolingPeriodTriggered(); /// @notice Events event YieldDistributed(uint256 indexed assets, uint256 indexed shares); event NAVUpdated(address indexed caller, uint256 indexed totalAssets, uint256 indexed totalSupply); event CoolingOffPeriodUpdated(uint256 indexed oldPeriod, uint256 indexed newPeriod); event FeeCollectorUpdated(address indexed oldCollector, address indexed newCollector); event PriceOracleUpdated(address indexed oldOracle, address indexed newOracle); event OtherERC20Withdrawn(address indexed receiver, address indexed token, uint256 indexed amount); event DepositMade(address indexed depositor, address indexed receiver, uint256 indexed amount); event YieldFeeUpdated(uint256 indexed newFee); /// @notice Function to update NAV externally function updateNAV() external; /// @notice Get NAV per share function getNavPerShare() external view returns (uint256); /// @notice Override decimals function decimals() external view override returns (uint8); /// @notice Get cooling off period function coolingOffPeriod() external view returns (uint256); /// @notice Transfer tokens to treasury function transferTokenToTreasury(address token, uint256 amount) external; /// @notice Get yieldFeePercentage function yieldFeePercentage() external view returns (uint256); /// @notice Get base points function BASE_POINTS() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { GroupId } from "../types/GroupId.sol"; interface IProtocolMinimum { function stabilityRatio(GroupId groupId) external view returns (uint96); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../extensions/IERC20PermitUpgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 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 SafeERC20Upgradeable { using AddressUpgradeable for address; /** * @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(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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. */ function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @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. */ function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20PermitUpgradeable token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @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). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @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 silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token)); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { DTokenRegistry } from "../declarations/DTokenRegistry.sol"; /** * @title GroupKey * @dev Struct representing the core group key information. */ struct GroupKey { /** * @dev The core group information from the DTokenRegistry. */ DTokenRegistry.GroupCore core; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { GroupId } from "../types/GroupId.sol"; import { GroupState } from "../types/CommonTypes.sol"; interface ITokenRegistryMinimum { // Getter functions for group state function getGroup(GroupId groupId) external view returns (GroupState memory); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency } from "../types/Currency.sol"; import { GroupKey } from "../types/GroupKey.sol"; import { GroupId } from "../types/GroupId.sol"; import { DProtocol } from "../declarations/DProtocol.sol"; interface IProtocol { /** * @notice Emitted when ERC20 tokens are recovered. * @param tokenAddress The address of the recovered token. * @param amount The amount of tokens recovered. */ event ERC20Recovered(Currency indexed tokenAddress, uint256 indexed amount); /** * @notice Emitted when native tokens are withdrawn. * @param amount The amount of native tokens withdrawn. */ event NativeTokenWithdrawn(uint256 indexed amount); /** * @notice Emitted when tokens are minted. * @param groupId The group ID. * @param token The token address. * @param recipient The recipient address. * @param sender The sender address. * @param ytMinted The amount of aTokens minted. * @param vtMinted The amount of vTokens minted. */ event MintToken( GroupId indexed groupId, address indexed token, address indexed recipient, address sender, uint256 ytMinted, uint256 vtMinted ); /** * @notice Emitted when tokens are redeemed. * @param groupId The group ID. * @param token The token address. * @param recipient The recipient address. * @param sender The sender address. * @param baseOut The amount of base tokens received. */ event RedeemToken( GroupId indexed groupId, address indexed token, address indexed recipient, address sender, uint256 baseOut ); /** * @notice Emitted when the minting is paused. * @param groupId The group ID. */ event RedeemLockUpdated(GroupId indexed groupId, bool indexed enabled); event FeeDelegated(address indexed hookContract, uint256 indexed protocolFeeAmount, uint256 indexed hookRemainingFee); event FeeCollected(address indexed feeCollector, address indexed token, uint256 indexed amount); /** * @notice Emitted when fees are settled. * @param hookContract The hook contract address. * @param token The token address. * @param amount The amount of fees settled. */ event FeesSettled(address indexed hookContract, address indexed token, uint256 indexed amount); // Custom Errors // todo: bytes32 groupId error ZeroAddress(); error ZeroAmount(); error ErrorMinTokenAmount(); error NotPermitted(); error ZeroGroupId(); error ConfigNotReady(); error NoFeesOwed(); error InvalidOperationType(); error InvalidRatios(); error ErrorMintPaused(); error ErrorRedeemPaused(); error UnsupportedCollateralType(); error InvalidMinMaxCollateralAmount(); error InsufficientAllowance(); error InsufficientBalance(address token); error ErrorInsufficientTokenOutput(); error ErrorInsufficientBaseOutput(); error InvalidSlippageRequested(); error TreasuryGroupUpdateFailed(); error InvalidMinimumAmount(uint256 minimumAmount, uint256 amountReceived); error MaximumAmountExceeded(GroupId groupId, uint256 preparedAmount, uint256 maxAmount); error InvalidPaymentAmount(); error TransferFailed(GroupId groupId, address recipient, uint256 amount); error ErrorATokenMintingPausedInStabilityMode(GroupId groupId); error RedeemLocked(GroupId groupId); error EarlyExit(GroupId groupId); error EmptyCollateralListOnUpdate(GroupId groupId); error InvalidGroupConfiguration(GroupId groupId); error NativeTokenWithdrawnFailed(uint256 amount); /** * @notice Mints tokens based on the provided parameters. * @param groupKey The key identifying the group. * @param params The mint parameters. * @return result The result of the mint operation. */ function mintToken( GroupKey calldata groupKey, DProtocol.MintParams calldata params ) external payable returns (DProtocol.MintResult memory result); /** * @notice Redeems tokens based on the provided parameters. * @param groupKey The key identifying the group. * @param params The redeem parameters. * @return baseOut The amount of base tokens received. */ function redeemToken(GroupKey calldata groupKey, DProtocol.RedeemParams calldata params) external returns (uint256 baseOut); /** * @notice Returns the stability ratio for a group. * @param groupId The group identifier. * @return The stability ratio. */ function stabilityRatio(GroupId groupId) external view returns (uint96); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; // solhint-disable no-inline-assembly /// @dev A subset copied from the following contracts: /// /// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol` /// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol` library WordCodec { /// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word, /// replacing the old value. Returns the new word. function insertUint(bytes32 word, uint256 value, uint256 offset, uint256 bitLength) internal pure returns (bytes32 result) { // Equivalent to: // uint256 mask = (1 << bitLength) - 1; // bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset)); // result = clearedWord | bytes32(value << offset); assembly("memory-safe") { let mask := sub(shl(bitLength, 1), 1) let clearedWord := and(word, not(shl(offset, mask))) result := or(clearedWord, shl(offset, value)) } } /// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word. function decodeUint(bytes32 word, uint256 offset, uint256 bitLength) internal pure returns (uint256 result) { // Equivalent to: // result = uint256(word >> offset) & ((1 << bitLength) - 1); assembly("memory-safe") { result := and(shr(offset, word), sub(shl(bitLength, 1), 1)) } } /// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns /// the new word. /// function insertInt(bytes32 word, int256 value, uint256 offset, uint256 bitLength) internal pure returns (bytes32) { unchecked { uint256 mask = (1 << bitLength) - 1; bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset)); // Integer values need masking to remove the upper bits of negative values. return clearedWord | bytes32((uint256(value) & mask) << offset); } } /// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word. function decodeInt(bytes32 word, uint256 offset, uint256 bitLength) internal pure returns (int256 result) { unchecked { int256 maxInt = int256((1 << (bitLength - 1)) - 1); uint256 mask = (1 << bitLength) - 1; int256 value = int256(uint256(word >> offset) & mask); // In case the decoded value is greater than the max positive integer that can be represented with bitLength // bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit // representation. // // Equivalent to: // result = value > maxInt ? (value | int256(~mask)) : value; assembly { result := or(mul(gt(value, maxInt), not(mask)), value) } } } /// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word. function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) { // Equivalent to: // result = (uint256(word >> offset) & 1) == 1; assembly { result := and(shr(offset, word), 1) } } /// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new /// word. function insertBool(bytes32 word, bool value, uint256 offset) internal pure returns (bytes32 result) { // Equivalent to: // bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset)); // bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset); assembly("memory-safe") { let clearedWord := and(word, not(shl(offset, 1))) result := or(clearedWord, shl(offset, value)) } } function clearWordAtPosition(bytes32 word, uint256 offset, uint256 bitLength) internal pure returns (bytes32 clearedWord) { unchecked { uint256 mask = (1 << bitLength) - 1; clearedWord = bytes32(uint256(word) & ~(mask << offset)); } } /// @dev Encodes an address into a 256 bit word at a given offset. function insertAddress(bytes32 word, address value, uint256 offset) internal pure returns (bytes32 result) { assembly("memory-safe") { let clearedWord := and(word, not(shl(offset, 0xffffffffffffffffffffffffffffffffffffffff))) result := or(clearedWord, shl(offset, value)) } } /// @dev Decodes an address from a 256 bit word at a given offset. function decodeAddress(bytes32 word, uint256 offset) internal pure returns (address result) { assembly("memory-safe") { result := and(shr(offset, word), 0xffffffffffffffffffffffffffffffffffffffff) } } /// @dev Encodes an enum value into a 256 bit word at a given offset. function insertEnum(bytes32 word, uint8 value, uint256 offset) internal pure returns (bytes32 result) { assembly("memory-safe") { let clearedWord := and(word, not(shl(offset, 0xff))) result := or(clearedWord, shl(offset, value)) } } /// @dev Decodes an enum value from a 256 bit word at a given offset. function decodeEnum(bytes32 word, uint256 offset) internal pure returns (uint8 result) { assembly("memory-safe") { result := and(shr(offset, word), 0xff) } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; import { Currency } from "../types/Currency.sol"; import { GroupId } from "../types/GroupId.sol"; import { GroupKey } from "../types/GroupKey.sol"; import { DTokenRegistry } from "../declarations/DTokenRegistry.sol"; import { GroupState, FeePermissions, FeeParams, DefaultFeeParams, CollateralInfo } from "../types/CommonTypes.sol"; interface ITokenRegistry { // Events event GroupAdded(GroupId indexed groupId); event GroupUpdated(GroupId indexed groupId); event CollateralAdded(GroupId indexed groupId, Currency indexed token, uint8 indexed decimals); event CollateralRemoved(GroupId indexed groupId, Currency indexed token); event HookContractSet(GroupId indexed groupId, address indexed newHookContract, bool indexed isDynamic, bool isDelegated); event HookPermissionsSet(GroupId indexed groupId, uint256 indexed newPermissions); event UpdateFeePermissions(GroupId indexed groupId, bool indexed isDynamic, bool indexed allowDelegation); // Custom Errors error AddressNotContract(address addr); error NotPermitted(); error GroupNotFound(GroupId groupId); error GroupAlreadyExists(GroupId groupId); error InvalidDecimals(); error InvalidMinMaxCollateralAmount(); error CollateralAlreadyExists(); error MultipleNativeTokensNotAllowed(); error CollateralNotFound(); error InvalidGroupSetup(); error ZeroAddress(); error EmptyCollateralList(); error MaxCollateralsLimitReached(); error StabilityRatioTooLarge(); error stabilityConditionsTriggeringRateTooLarge(); error InvalidStabilityTriggeringRatio(GroupId groupId); error FeesTooHigh(); error InvalidMaxFee(); error InvalidMinFee(); error InvalidBaseFee(); error InvalidYieldFee(); error InvalidStabilityFee(); error InvalidProtocolFee(); error InvalidFeeFlags(); error FeesAreNotCompatibleWithDefaultFees(); error CannotRecoverToken(); // Group management functions (Manager Role) function addGroup( DTokenRegistry.GroupSetup calldata setup, // Full group setup address hookContract, // Hook contract for the group uint256 hookPermissions // Hook permissions ) external; // Collateral management functions (Manager Role) function addCollateral(GroupKey calldata key, CollateralInfo calldata collateral) external; function removeCollateral(GroupKey calldata key, Currency token) external; // Getter functions for group state function getGroup(GroupId groupId) external view returns (GroupState memory); function getStabilityRatio(GroupId groupId) external view returns (uint96); function getStabilityTriggeringRatio(GroupId groupId) external view returns (uint96); function getProtocolFee(GroupId groupId) external view returns (uint24); function getFeePermissions(GroupId groupId) external view returns (FeePermissions memory); function getFeeParams(GroupId groupId) external view returns (FeeParams memory); function getMintFeeVT(GroupId groupId) external view returns (uint24); function getRedeemFeeVT(GroupId groupId) external view returns (uint24); function getMintFeeYT(GroupId groupId) external view returns (uint24); function getRedeemFeeYT(GroupId groupId) external view returns (uint24); function getYieldFeeYT(GroupId groupId) external view returns (uint24); function getStabilityMintFeeVT(GroupId groupId) external view returns (uint24); function getStabilityMintFeeYT(GroupId groupId) external view returns (uint24); function getStabilityRedeemFeeVT(GroupId groupId) external view returns (uint24); function getStabilityRedeemFeeYT(GroupId groupId) external view returns (uint24); function getHookContract(GroupId groupId) external view returns (address); function getHookPermissions(GroupId groupId) external view returns (uint256); function validateCollateral(GroupId groupId, Currency currency) external view returns (bool); function isWrappingRequired(GroupId groupId) external view returns (bool); function getFeeModel(GroupId groupId) external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return 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 up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. 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^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // 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^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice 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) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMathUpgradeable { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @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[EIP 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 v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity 0.8.28; /* solhint-disable */ /** * @dev Copied from https://github.com/balancer/balancer-v2-monorepo/blob/master/pkg/solidity-utils/contracts/math/LogExpMath.sol * * Some modifications are made due to compile error. * * It is the same as `LogExpMathV8` with `unchecked` scope. * * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMathV8 { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. require(x >> 255 == 0, "X_OUT_OF_BOUNDS"); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. require(y < MILD_EXPONENT_BOUND, "Y_OUT_OF_BOUNDS"); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y require(MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, "PRODUCT_OUT_OF_BOUNDS"); return uint256(exp(logx_times_y)); } } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { unchecked { require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "INVALID_EXPONENT"); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { unchecked { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { unchecked { // The real natural logarithm is not defined for negative numbers or zero. require(a > 0, "OUT_OF_BOUNDS"); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { unchecked { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { unchecked { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC4626.sol) pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../utils/SafeERC20Upgradeable.sol"; import "../../../interfaces/IERC4626Upgradeable.sol"; import "../../../utils/math/MathUpgradeable.sol"; import {Initializable} from "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626]. * * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends * the ERC20 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 uses virtual assets and shares to 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, 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: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]. * ==== * * _Available since v4.7._ */ abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable { using MathUpgradeable for uint256; IERC20Upgradeable private _asset; uint8 private _underlyingDecimals; /** * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777). */ function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing { __ERC4626_init_unchained(asset_); } function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing { (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(IERC20Upgradeable asset_) private view returns (bool, uint8) { (bool success, bytes memory encodedDecimals) = address(asset_).staticcall( abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector) ); 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(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) { return _underlyingDecimals + _decimalsOffset(); } /** @dev See {IERC4626-asset}. */ function asset() public view virtual override returns (address) { return address(_asset); } /** @dev See {IERC4626-totalAssets}. */ function totalAssets() public view virtual override returns (uint256) { return _asset.balanceOf(address(this)); } /** @dev See {IERC4626-convertToShares}. */ function convertToShares(uint256 assets) public view virtual override returns (uint256) { return _convertToShares(assets, MathUpgradeable.Rounding.Down); } /** @dev See {IERC4626-convertToAssets}. */ function convertToAssets(uint256 shares) public view virtual override returns (uint256) { return _convertToAssets(shares, MathUpgradeable.Rounding.Down); } /** @dev See {IERC4626-maxDeposit}. */ function maxDeposit(address) public view virtual override returns (uint256) { return type(uint256).max; } /** @dev See {IERC4626-maxMint}. */ function maxMint(address) public view virtual override returns (uint256) { return type(uint256).max; } /** @dev See {IERC4626-maxWithdraw}. */ function maxWithdraw(address owner) public view virtual override returns (uint256) { return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down); } /** @dev See {IERC4626-maxRedeem}. */ function maxRedeem(address owner) public view virtual override returns (uint256) { return balanceOf(owner); } /** @dev See {IERC4626-previewDeposit}. */ function previewDeposit(uint256 assets) public view virtual override returns (uint256) { return _convertToShares(assets, MathUpgradeable.Rounding.Down); } /** @dev See {IERC4626-previewMint}. */ function previewMint(uint256 shares) public view virtual override returns (uint256) { return _convertToAssets(shares, MathUpgradeable.Rounding.Up); } /** @dev See {IERC4626-previewWithdraw}. */ function previewWithdraw(uint256 assets) public view virtual override returns (uint256) { return _convertToShares(assets, MathUpgradeable.Rounding.Up); } /** @dev See {IERC4626-previewRedeem}. */ function previewRedeem(uint256 shares) public view virtual override returns (uint256) { return _convertToAssets(shares, MathUpgradeable.Rounding.Down); } /** @dev See {IERC4626-deposit}. */ function deposit(uint256 assets, address receiver) public virtual override returns (uint256) { require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max"); uint256 shares = previewDeposit(assets); _deposit(_msgSender(), receiver, assets, shares); return shares; } /** @dev See {IERC4626-mint}. * * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero. * In this case, the shares will be minted without requiring any assets to be deposited. */ function mint(uint256 shares, address receiver) public virtual override returns (uint256) { require(shares <= maxMint(receiver), "ERC4626: mint more than max"); uint256 assets = previewMint(shares); _deposit(_msgSender(), receiver, assets, shares); return assets; } /** @dev See {IERC4626-withdraw}. */ function withdraw(uint256 assets, address receiver, address owner) public virtual override returns (uint256) { require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max"); uint256 shares = previewWithdraw(assets); _withdraw(_msgSender(), receiver, owner, assets, shares); return shares; } /** @dev See {IERC4626-redeem}. */ function redeem(uint256 shares, address receiver, address owner) public virtual override returns (uint256) { require(shares <= maxRedeem(owner), "ERC4626: redeem more than max"); 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, MathUpgradeable.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, MathUpgradeable.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 ERC777, `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 SafeERC20Upgradeable.safeTransferFrom(_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 ERC777, `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); SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets); emit Withdraw(caller, receiver, owner, assets, shares); } function _decimalsOffset() internal view virtual returns (uint8) { return 0; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.28; library DProtocol { struct MintParams { uint8 operationType; // Type of mint operation uint256 baseIn; // Amount of base token input uint24 slippage; // The slippage tolerance address paymentToken; // Token used for payment bytes hookData; // Hook data if any } struct RedeemParams { uint8 operationType; // Type of redeem operation uint256 baseOut; // Amount of tokens to redeem uint24 slippage; // The slippage tolerance address desiredCollateral; // Desired collateral to receive bytes hookData; // Hook data if any } struct MintResult { uint256 ytMinted; // Amount of YT Tokens minted uint256 vtMinted; // Amount of VT Tokens minted } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import {Initializable} from "../../proxy/utils/Initializable.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}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * 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 ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override 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 `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` 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 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * 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 `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `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. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` 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. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20Upgradeable.sol"; import "../token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; /** * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626]. * * _Available since v4.7._ */ interface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable { 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 redeemption 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 v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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); }
{ "remappings": [ "@aave/=node_modules/@aave/", "@account-abstraction/=node_modules/@account-abstraction/", "@chainlink/=node_modules/@chainlink/", "@eth-optimism/=node_modules/@chainlink/contracts/node_modules/@eth-optimism/", "@openzeppelin/=node_modules/@openzeppelin/", "@uniswap/=node_modules/@uniswap/", "base64-sol/=node_modules/base64-sol/", "ds-test/=lib/ds-test/", "eth-gas-reporter/=node_modules/eth-gas-reporter/", "forge-std/=lib/forge-std/src/", "hardhat/=node_modules/hardhat/", "solidity-bytes-utils/=node_modules/solidity-bytes-utils/", "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/", "solmate/=lib/solmate/src/", "abdk-libraries-solidity/=node_modules/abdk-libraries-solidity/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "shanghai", "viaIR": true, "libraries": { "src/libs/ValidationLibrary.sol": { "ValidationLibrary": "0xeFFc2aB7f7E6c6d5E2d84F8519876695EE295159" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"ErrorCollateralRatioTooSmall","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"ErrorDistributingYield","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"ErrorExceedTotalCap","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"address","name":"token","type":"address"}],"name":"ErrorInsufficientBalance","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"ErrorInvalidTwapPrice","type":"error"},{"inputs":[],"name":"ErrorSwapFailed","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"ErrorUnderCollateral","type":"error"},{"inputs":[],"name":"ErrorWithdrawFromStrategy","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"GroupAlreadyInitialized","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"InvalidBaseTokenCap","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"InvalidGroupConfiguration","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"InvalidPrice","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"address","name":"rateProvider","type":"address"}],"name":"InvalidRate","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"InvalidRatio","type":"error"},{"inputs":[],"name":"InvalidRatio","type":"error"},{"inputs":[],"name":"InvalidTokenType","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"maxAmount","type":"uint256"}],"name":"MaximumAmountExceeded","type":"error"},{"inputs":[],"name":"NotPermitted","type":"error"},{"inputs":[],"name":"OnlyStrategy","type":"error"},{"inputs":[],"name":"RenounceRoleProhibited","type":"error"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"StrategyUnderflow","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroAmount","type":"error"},{"inputs":[],"name":"ZeroAmount","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"aTokenAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"}],"name":"ATokensMintedToPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newCaps","type":"uint256"}],"name":"BaseTokenCapsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newPrice","type":"uint256"}],"name":"BaseTokenPriceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"BaseTokenTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"CacheUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newEMAValue","type":"uint256"}],"name":"EMALeverageRatioUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FeesCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"xTokenAmount","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"baseTokenAmount","type":"uint256"}],"name":"FeesDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"dxTokenBalance","type":"uint256"},{"indexed":false,"internalType":"address","name":"feeCollector","type":"address"}],"name":"FeesHarvested","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"initialValue","type":"uint256"}],"name":"GroupEMALeverageRatioInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"baseTokenPrice","type":"uint256"}],"name":"GroupInitialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"xTokenAmount","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"aTokenAmount","type":"uint256"}],"name":"HarvestFees","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"yieldBaseTokens","type":"uint256"}],"name":"HarvestYield","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"newCollateralRatio","type":"uint256"}],"name":"RebalanceDownPerformed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"newCollateralRatio","type":"uint256"}],"name":"RebalanceUpPerformed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"oldPrice","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"newPrice","type":"uint256"}],"name":"Settle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"fromToken","type":"address"},{"indexed":true,"internalType":"address","name":"toToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"SwapExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"fromToken","type":"address"},{"indexed":false,"internalType":"address","name":"toToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"TokensSwappedToPool","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TransferToStrategy","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":true,"internalType":"uint256","name":"oldBaseTokenCap","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"newBaseTokenCap","type":"uint256"}],"name":"UpdateBaseTokenCap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldFeeCollector","type":"address"},{"indexed":true,"internalType":"address","name":"newFeeCollector","type":"address"}],"name":"UpdateFeeCollector","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"GroupId","name":"groupId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"yieldAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"feeCollector","type":"address"}],"name":"YieldHarvested","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"CACHE_UPDATER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"HARVESTER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PROTOCOL_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"collateralRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"currentBaseTokenPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeCollector","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenRegistry","type":"address"},{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"forceUpdateGroupCache","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"getTreasuryState","outputs":[{"components":[{"components":[{"internalType":"uint40","name":"lastTime","type":"uint40"},{"internalType":"uint24","name":"sampleInterval","type":"uint24"},{"internalType":"uint96","name":"lastValue","type":"uint96"},{"internalType":"uint96","name":"lastEmaValue","type":"uint96"}],"internalType":"struct ExponentialMovingAverageV8.EMAStorage","name":"emaLeverageRatio","type":"tuple"},{"internalType":"uint256","name":"totalBaseTokens","type":"uint256"},{"internalType":"uint256","name":"baseTokenCaps","type":"uint256"},{"internalType":"uint256","name":"lastSettlementTimestamp","type":"uint256"},{"internalType":"uint256","name":"baseTokenPrice","type":"uint256"},{"internalType":"bool","name":"inited","type":"bool"},{"internalType":"uint256","name":"strategyUnderlying","type":"uint256"}],"internalType":"struct DTreasury.TreasuryState","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"components":[{"internalType":"bool","name":"sendTokens","type":"bool"},{"internalType":"address","name":"swapRouter","type":"address"},{"internalType":"address","name":"stablecoin","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct TreasuryHarvestLibrary.HarvestParams","name":"params","type":"tuple"}],"name":"harvestFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"components":[{"internalType":"bool","name":"sendTokens","type":"bool"},{"internalType":"address","name":"swapRouter","type":"address"},{"internalType":"address","name":"stablecoin","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct TreasuryHarvestLibrary.HarvestParams","name":"params","type":"tuple"}],"name":"harvestYield","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"harvestable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_protocol","type":"address"},{"internalType":"address","name":"_feeCollector","type":"address"},{"internalType":"address","name":"_admin","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenRegistry","type":"address"},{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"components":[{"internalType":"uint256","name":"baseTokenCaps","type":"uint256"},{"internalType":"uint256","name":"baseIn","type":"uint256"},{"internalType":"bool","name":"beta","type":"bool"}],"internalType":"struct DTreasury.GroupUpdateParams","name":"params","type":"tuple"}],"name":"initializeGroup","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"isUnderCollateral","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"","type":"bytes32"}],"name":"lastHarvestTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"leverageRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_newCollateralRatio","type":"uint256"}],"name":"maxMintableAToken","outputs":[{"internalType":"uint256","name":"_maxBaseIn","type":"uint256"},{"internalType":"uint256","name":"_maxATokenMintable","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_newCollateralRatio","type":"uint256"}],"name":"maxRedeemableAToken","outputs":[{"internalType":"uint256","name":"_maxBaseOut","type":"uint256"},{"internalType":"uint256","name":"_maxATokenRedeemable","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_baseIn","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"mintAToken","outputs":[{"internalType":"uint256","name":"_aTokenOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_baseIn","type":"uint256"},{"internalType":"address","name":"_recipient","type":"address"}],"name":"mintXToken","outputs":[{"internalType":"uint256","name":"_xTokenOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocol","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"components":[{"internalType":"uint256","name":"targetCollateralRatio","type":"uint256"},{"internalType":"uint256","name":"convertAmount","type":"uint256"},{"internalType":"address","name":"stablecoin","type":"address"},{"internalType":"address","name":"swapRouter","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct TreasuryRebalanceLibrary.RebalanceDownParams","name":"params","type":"tuple"}],"name":"rebalanceDown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"components":[{"internalType":"uint256","name":"targetCollateralRatio","type":"uint256"},{"internalType":"address","name":"swapRouter","type":"address"},{"internalType":"address","name":"stablecoin","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct TreasuryRebalanceLibrary.RebalanceUpParams","name":"params","type":"tuple"}],"name":"rebalanceUp","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_aTokenIn","type":"uint256"},{"internalType":"uint256","name":"_xTokenIn","type":"uint256"},{"internalType":"address","name":"_owner","type":"address"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"_baseOut","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"address","name":"","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"}],"name":"totalBaseToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"transferToStrategy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"","type":"bytes32"}],"name":"treasuryStates","outputs":[{"components":[{"internalType":"uint40","name":"lastTime","type":"uint40"},{"internalType":"uint24","name":"sampleInterval","type":"uint24"},{"internalType":"uint96","name":"lastValue","type":"uint96"},{"internalType":"uint96","name":"lastEmaValue","type":"uint96"}],"internalType":"struct ExponentialMovingAverageV8.EMAStorage","name":"emaLeverageRatio","type":"tuple"},{"internalType":"uint256","name":"totalBaseTokens","type":"uint256"},{"internalType":"uint256","name":"baseTokenCaps","type":"uint256"},{"internalType":"uint256","name":"lastSettlementTimestamp","type":"uint256"},{"internalType":"uint256","name":"baseTokenPrice","type":"uint256"},{"internalType":"bool","name":"inited","type":"bool"},{"internalType":"uint256","name":"strategyUnderlying","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"GroupId","name":"groupId","type":"bytes32"},{"internalType":"uint256","name":"_baseTokenCap","type":"uint256"}],"name":"updateBaseTokenCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newFeeCollector","type":"address"}],"name":"updateFeeCollector","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
60808060405234610117575f5460ff8160081c16159182809361010a575b80156100f3575b1561009a575060ff1981166001175f5581610088575b5061004f575b604051615ef4908161011c8239f35b61ff00195f54165f557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a1610040565b61ffff1916610101175f90815561003a565b62461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b1580156100245750600160ff831614610024565b50600160ff83161061001d565b5f80fdfe6080806040526004361015610034575b503615610025576339218f3b60e01b5f5260045ffd5b6339218f3b60e01b5f5260045ffd5b5f905f3560e01c90816301ffc9a7146129c45750806302768de41461299d578063248a9ca3146129725780632569e86c146127c85780632f2ff15d1461272257806335046416146126fb57806336568abe146126d25780633f4ba83a1461263f5780634943d301146125895780634d9d6024146125615780635c975abb1461253f57806363a560ec1461251857806373602fb41461245057806373f6cefc146122b557806379850ce7146121b35780637ac6f8ab146121485780638456cb591461209a578063861980521461204d5780638ce744261461202557806391d1485414611fdc578063973ed91f14611f5e578063a05a600b14611a4b578063a217fddf14611a2f578063a86ba52a146116d1578063aa95d40114611672578063b37b486214611648578063c0c53b8b14611245578063c1b8f40f14611186578063c415b95c1461115d578063d246c5bc14610d53578063d2c35ce814610ccf578063d547741f14610c0e578063e3dab55014610ae4578063e526fed214610ac5578063e63ab1e914610a9d578063e6b6312814610989578063e88fb871146108ae578063f3c479971461083f578063f665b214146103d65763fde0b0820361000f57346103d35761020236612a89565b90929161020d612f4b565b610215612fa1565b61021d613096565b6001600160a01b03606060206102328461314c565b015101511630036103c15761024681612c8e565b6103af57805f5260fe60205260405f20906102608161314c565b9461027b61027561026f612c40565b886133a4565b826134f7565b91600184019061028c848354612c62565b60028601541061039d57506102ed6102f6936102e286946080946102bd6102b68d61030d9b61353a565b80986138a5565b6102c8848254612c62565b90558a5160400151309033906001600160a01b031661392b565b602084015190612d1d565b91015190612d30565b610307610301612cfe565b866133a4565b906139ac565b9251516001600160a01b031690813b15610399576040516340c10f1960e01b81526001600160a01b0391909116600482015260248101849052919081908390604490829084905af1801561038e57610370575b6020836001609755604051908152f35b9061037c5f9282612b37565b80031261038a575f80610360565b5f80fd5b6040513d5f823e3d90fd5b8280fd5b639d1bab0960e01b5f5260045260245ffd5b63658242c560e01b5f5260045260245ffd5b635dbad7a160e01b8352600452602482fd5b80fd5b50346103d35760a03660031901126103d357600435608036602319011261083b5760405161040381612ae3565b6024358152610410612a73565b6020820190815261041f612a47565b60408301908152606083016084358152610437612f4b565b6001600160a01b036060602061044c8861314c565b015101511630036108275761045f612fe5565b6104688561314c565b9160a083019283519287895260fe6020526001600160601b0360408a2094603b1c166104948386613f5f565b87516001600160a01b0316158015610815575b6108065788519182159283156107fb575b5082156107f0575b5081156107dd575b506107c9576104d987518386614284565b83515160208501805160c001518951919694506001600160a01b0392831693928e9291169061050b9060ff16846139ac565b90843b1561039957604051632770a7eb60e21b81526001600160a01b039190911660048201526024810191909152818160448183885af180156107be576107a5575b5050845151835160409081015181516341976e0960e01b81526001600160a01b03918216600482015294928f929186916024918391165afa938415610798578194610764575b5015801561075c575b61074d578c9493929160206004926040519384809263c1590cd760e01b82525afa918215610742578692610708575b50906105d792916152d5565b97518551925197516001600160a01b03938416939190911691906020906106049060101c60ff168b6139ac565b602460018060a01b0360408551015116916040519788938492636f074d1f60e11b845260048401525af19384156106fd578c946106b7575b5096600196959361067e9593610664936106879a60608b8060a01b0391510151169030615619565b9151905160c0015160a086901b8690039081169116614af3565b01918254612eb9565b905551907f0f471384eb459a67f4e6a9130f154a67b2fccb91ca6f319e9aa6dd472a0ec26d8380a3600160975580f35b91949296959350966020823d6020116106f5575b816106d860209383612b37565b8101031261038a579051909694959294919390929161068761063c565b3d91506106cb565b6040513d8e823e3d90fd5b92915094506020823d60201161073a575b8161072660209383612b37565b8101031261038a5790518c946105d76105cb565b3d9150610719565b6040513d88823e3d90fd5b630ae7ae7760e21b8d5260048dfd5b50821561059c565b905061078991935060403d604011610791575b6107818183612b37565b810190612ce1565b92905f610593565b503d610777565b50604051903d90823e3d90fd5b816107af91612b37565b6107ba578b5f61054d565b8b80fd5b6040513d84823e3d90fd5b630303022d60e21b89526004889052602489fd5b670de0b6b3a7640000915011155f6104c8565b81101591505f6104c0565b82101592505f6104b8565b63d92e233d60e01b8b5260048bfd5b5084516001600160a01b0316156104a7565b635dbad7a160e01b86526004859052602486fd5b5080fd5b50346103d35760203660031901126103d357600435906001600160a01b036060602061086a8561314c565b0151015116300361089c578160406108949261088760209561314c565b92815260fe855220613f5f565b604051908152f35b602491635dbad7a160e01b8252600452fd5b50346103d3576108bd36612c0e565b906108c6612fe5565b6001600160a01b03606060206108db8461314c565b015101511630036103c15781158015610971575b8015610959575b6109475780835260fe60205260026040842001549080845260fe6020526109208360408620614ac0565b7f2077bbe429859a2793babc143041af43b6197d85275f53cac01450607f2fedfe8480a480f35b63118341d960e01b8352600452602482fd5b5080835260fe602052600160408420015482106108f6565b5080835260fe602052600260408420015482146108ef565b50346103d35761099836612c0e565b906109a1612f4b565b6001600160a01b03606060206109b68461314c565b015101511630036103c1576109ca8161314c565b602081015160a001516001600160a01b03163303610a8e5781845260fe602052604084206001610a0a610a046109fe612c40565b856133a4565b866134f7565b9160068101610a1a848254612c62565b905501908154818110610a7a5791610a37610a4e94928794612eb9565b9055516040015133906001600160a01b0316614af3565b7f7baa823fe1737fb055aa4f86aecc858a61acddcb591ea0b95311bfaaff59a2248380a3600160975580f35b63040b0a2d60e01b87526004859052602487fd5b63ade5da5f60e01b8452600484fd5b50346103d357806003193601126103d35760206040515f516020615e9f5f395f51905f528152f35b50346103d35760203660031901126103d3576020610894600435612e8d565b50346103d35760403660031901126103d357610afe612a5d565b610b06612f4b565b5f516020615e5f5f395f51905f528252606560209081526040808420335f908152925290205460ff1615610b4957610b419060243590614346565b600160975580f35b610c0a610b5533615366565b610bf26011610b705f516020615e5f5f395f51905f5261544c565b9260376040519485927f416363657373436f6e74726f6c3a206163636f756e74200000000000000000006020850152610bb28151809260208688019101613383565b83017001034b99036b4b9b9b4b733903937b6329607d1b83820152610be1825180936020604885019101613383565b01010301601f198101835282612b37565b60405162461bcd60e51b815291829160048301614b57565b0390fd5b50346103d35760403660031901126103d357600435610c2b612a31565b90610c4a610c45825f526065602052600160405f20015490565b6130f5565b80835260656020526040832060018060a01b0383165f5260205260ff60405f205416610c74578280f35b8083526065602090815260408085206001600160a01b03949094165f81815294909252909220805460ff191690553391907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b8480a45f808280f35b50346103d35760203660031901126103d357610ce9612a5d565b610cf1612fe5565b6001600160a01b03168015610d445760fd80546001600160a01b0319811683179091556001600160a01b03167fcc882185e6edeeb762130016ea1faf3d7aa9c01b199bfd646f965b58ab7410638380a380f35b63d92e233d60e01b8252600482fd5b50346103d35760a03660031901126103d357610d6d612a5d565b602435606036604319011261039957610d84612f4b565b610d8c612fe5565b6001600160a01b0382161561114e57604435801561113a5781845260fe6020526040842090600582019360ff85541661112657836001600160a01b0360606020610dd58461314c565b01510151163003611116575b610df69150610def9061314c565b9183614ac0565b602081015151815160409081015181516341976e0960e01b81526001600160a01b039182166004820152969287916024918391165afa94851561074257869087966110f2575b501580156110ea575b6110db57908291856004889501557f4b02072719fa9787c31ae0719421e5b921c10e6da6eaf9a4f7ddda13dc2b3ddd6020604051888152a160643590610e95610e8f6109fe612c40565b836134f7565b6001850181905584547b1bc16d674ec80000000000000000000000000000015180000000000073ffffffffffffffffffffffff000000ffffffffff73ffffffffffffffffffffffff000000ffffffffff199092164264ffffffffff16176503782dace9d960531b179190911617909455604051671bc16d674ec8000081527fd2148a73b824404e6bde3e68b87ff1d3c2b24c734dc65de8efaa37a0be423e1a90602090a1805460ff19166001179055671bc16d674ec80000610f578785612d1d565b049260843580151581036110d7576110cc575b50610fac610f91610f85610f7f610301612cfe565b866139ac565b94610307610301612c6f565b835160400151909290309033906001600160a01b031661392b565b8151602001516001600160a01b0316803b156110c8576040516340c10f1960e01b8152306004820152602481019290925284908290604490829084905af19081156110bd5784916110a8575b505051516001600160a01b0316803b15610399576040516340c10f1960e01b8152306004820152602481019290925282908290604490829084905af180156107be57611093575b5080827f0cd738c9c0bbe501d6da72544aaef2b26bfdcbffa10507ff2755918321897c56828694a47fc737d26127da3bd7f66d0d10fe580666127260220a2ff721985d1b2f5ed3da968380a3600160975580f35b8161109d91612b37565b61039957825f61103f565b816110b291612b37565b61039957825f610ff8565b6040513d86823e3d90fd5b8480fd5b60011c92505f610f6a565b8580fd5b630ae7ae7760e21b8652600486fd5b508415610e45565b905061110e91955060403d604011610791576107818183612b37565b94905f610e3c565b61111f91614346565b5f83610de1565b630cee99df60e01b86526004849052602486fd5b63118341d960e01b84526004829052602484fd5b63d92e233d60e01b8352600483fd5b50346103d357806003193601126103d35760fd546040516001600160a01b039091168152602090f35b50346103d35761119536612c0e565b91906001600160a01b03606060206111ac8461314c565b0151015116300361123257670de0b6b3a764000083111561121f576112046103076111f160409584876111e16112139761314c565b978892815260fe60205220614284565b92906103076111fe612c40565b876133a4565b9361120d612cfe565b906133a4565b82519182526020820152f35b6315063bef60e21b825260045260249150fd5b635dbad7a160e01b825260045260249150fd5b50346103d35760603660031901126103d35761125f612a5d565b611267612a31565b61126f612a73565b9183549260ff8460081c16159384809561163b575b8015611624575b156115c85760ff1981166001178655846115b7575b506001600160a01b03821691821580156115a6575b8015611595575b61158657611395906112fd60ff885460081c166112d881614224565b6112e181614224565b6112ea81614224565b60016097556112f881614224565b614224565b60ff1960c9541660c95586805260656020526040872060018060a01b0384165f5260205260ff60405f20541615611540575b5f516020615e9f5f395f51905f52875260656020526040872060018060a01b0384165f5260205260ff60405f205416156114ed575b5f516020615e7f5f395f51905f528752606560205260408720845f5260205260ff60405f20541615611499576139de565b61139e816139de565b5f516020615e3f5f395f51905f52855260656020526040852060018060a01b0382165f5260205260ff60405f20541615611440575b506001600160601b0360a01b60fc54161760fc5560018060a01b03166001600160601b0360a01b60fd54161760fd556114095780f35b61ff001981541681557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a180f35b5f516020615e3f5f395f51905f528086526065602090815260408088206001600160a01b03949094165f81815294909252909220805460ff191660011790553391905f516020615e1f5f395f51905f528780a45f6113d3565b5f516020615e7f5f395f51905f528752606560205260408720845f5260205260405f20600160ff1982541617905533845f516020615e7f5f395f51905f525f516020615e1f5f395f51905f528a80a46139de565b5f516020615e9f5f395f51905f52808852606560209081526040808a206001600160a01b0387165f8181529190935220805460ff1916600117905533915f516020615e1f5f395f51905f528a80a4611364565b8680526065602090815260408089206001600160a01b0386165f8181529190935220805460ff191660011790553390885f516020615e1f5f395f51905f528180a461132f565b63d92e233d60e01b8652600486fd5b506001600160a01b038416156112bc565b506001600160a01b038216156112b5565b61ffff19166101011785555f6112a0565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b15801561128b5750600160ff82161461128b565b50600160ff821610611284565b50346103d35760203660031901126103d3576040602091600435815260ff83522054604051908152f35b50346103d35761168136612b9d565b61168c929192612f4b565b611694613037565b6001600160a01b03606060206116a98661314c565b015101511630036116be57610b419192612d4e565b50602491635dbad7a160e01b8252600452fd5b50346103d35760803660031901126103d3576024356004356044356116f4612a47565b936116fd612f4b565b611705612fa1565b61170d613096565b6001600160a01b03606060206117228661314c565b01510151163003611a1b576117368361314c565b91835f5260fe60205260405f2093611758611752610301612cfe565b876134f7565b61176c6117666111fe612c6f565b846134f7565b906117848960208851015160018060a01b0316613fda565b6064019283606411611a07578415159384908690826119fd575b50506119d457836117af888a61353a565b936117ba858b6138a5565b60c085015161194757506103af57506117ec9160606102ed6117e19360018b015490612d1d565b6103076111fe612c40565b95806118cb575b50611843575b6020856118368882888861181461180e612c40565b826133a4565b8151604001519188015160a001516001600160a01b0390811692169030614056565b6001609755604051908152f35b825160200151611861908290309089906001600160a01b031661392b565b8251602001516001600160a01b031690813b1561039957604051632770a7eb60e21b81523060048201526024810191909152919081908390604490829084905af1801561038e57156117f957906118bc5f9282979497612b37565b80031261038a57925f806117f9565b8451516118e690829030908b906001600160a01b031661392b565b8451516001600160a01b031690813b156110c857604051632770a7eb60e21b815230600482015260248101919091529084908290604490829084905af1801561038e57156117f3578061193a855f93612b37565b80031261038a575f6117f3565b9150506117ec928051916119616020830193845190612d1d565b9160a061198360608301519461197d6080850196875190612d1d565b90612eb9565b9101908151155f146119ae575050506119a9926119a1915190612d1d565b905190612d30565b6117e1565b906119a16119ce926119c86119a9986119a1975190612d1d565b94612d1d565b90612c62565b86516020015163cd7af51b60e01b5f9081526004929092526001600160a01b0316602452604490fd5b109050855f61179e565b634e487b7160e01b5f52601160045260245ffd5b635dbad7a160e01b81526004839052602490fd5b50346103d357806003193601126103d357602090604051908152f35b503461038a5760c036600319011261038a5760043560a036602319011261038a57604051611a7881612aff565b6024358152602081016044358152611a8e612a47565b60408301908152608435906001600160a01b038216820361038a5760608401918252608084019160a4358352611ac2612f4b565b6001600160a01b0360606020611ad78961314c565b01510151163003611f4b57611aea612fe5565b611af38661314c565b9060a0820192835194885f5260fe60205260405f209560018060a01b03845116158015611f39575b611f2a57875115611f1b57603b1c6001600160601b0316611b3c8588613f5f565b89518015928315611f10575b508215611f05575b5050611ef6578151965160208501805160c0015190989193916001600160a01b039081169116611b808183613fda565b858110611eee575b50803b1561038a57604051636f59f5a760e11b81526001600160a01b03929092166004830152602482018590525f908290604490829084905af1801561038e57611ecb575b5051925190518a93602093611c0c9390916001600160a01b039182169116611bf6838383615afb565b8751606001516001600160a01b03169130615619565b83516060810151604090910151611c319183916001600160a01b039081169116615afb565b602460018060a01b0360408651015116916040519485938492630ea598cb60e41b845260048401525af18015611ec0578890611e8c575b611c7b915060ff845160101c16906134f7565b81518051845187515160409384015184516341976e0960e01b81526001600160a01b039182166004820152959995979381169693949293929188916024918391165afa958615611e81578b908c97611e5d575b50158015611e55575b611e465760405163c1590cd760e01b815295602087600481895afa9687156106fd578c97611e0e575b5090611d186001600160601b0397611d26938b6152d5565b968793603b1c169088613e9e565b905010611dff5790611d3e60ff8a94935116856139ac565b905160c001516001600160a01b031690823b15611dfb576040516340c10f1960e01b81526001600160a01b0392909216600483015260248201529082908290604490829084905af180156107be57611de6575b505015611dd7576001611da79101918254612c62565b905551907f42286d04e4c524c8cc0ee3f3e851a993a5cb29c5b4d2d6b408bbecdc01ec99e48380a3600160975580f35b631f2a200560e01b8552600485fd5b81611df091612b37565b6110d757855f611d91565b8380fd5b63648564d360e01b8952600489fd5b9650906020873d602011611e3e575b81611e2a60209383612b37565b8101031261038a5795519590611d18611d00565b3d9150611e1d565b630ae7ae7760e21b8b5260048bfd5b508515611cd7565b9050611e7991965060403d604011610791576107818183612b37565b95905f611cce565b6040513d8d823e3d90fd5b506020813d602011611eb8575b81611ea660209383612b37565b8101031261038a57611c7b9051611c68565b3d9150611e99565b6040513d8a823e3d90fd5b611c0c929b5092611ee15f602095969396612b37565b5f9b925092939093611bcd565b94505f611b88565b630303022d60e21b5f5260045ffd5b101590505f80611b50565b81111592505f611b48565b631f2a200560e01b5f5260045ffd5b63d92e233d60e01b5f5260045ffd5b5082516001600160a01b031615611b1b565b85635dbad7a160e01b5f5260045260245ffd5b3461038a57602036600319011261038a5760043560606020611f7f8361314c565b015101516001600160a01b03163003611fca57805f5260fe602052611fa660405f2061516e565b8015611fb757604051908152602090f35b50630303022d60e21b5f5260045260245ffd5b635dbad7a160e01b5f5260045260245ffd5b3461038a57604036600319011261038a57611ff5612a31565b6004355f52606560205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b3461038a575f36600319011261038a5760fc546040516001600160a01b039091168152602090f35b3461038a57602036600319011261038a576004356001600160a01b03606060206120768461314c565b01510151163003611fca575f5260fe6020526020600160405f200154604051908152f35b3461038a575f36600319011261038a57335f9081527fbfe93621c6aa2dbf737e9056c9b79e4d30ee4f6b28b18be2cb71aac8a7bf258e602052604090205460ff1615612121576120e8612fa1565b600160ff1960c954161760c9557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b610c0a61212d33615366565b610bf26011610b705f516020615e9f5f395f51905f5261544c565b3461038a5761215636612c0e565b6001600160a01b036060602061216b8561314c565b015101511630036121a057906112136112046103076111f160409561218f8661314c565b955f5260fe60205285875f20613e9e565b50635dbad7a160e01b5f5260045260245ffd5b3461038a576121c136612b9d565b906121ca612f4b565b6001600160a01b03606060206121df8461314c565b01510151163003611fca576121f2613037565b60018251151514806122a0575b8061228b575b612279578061224e6122175f9361314c565b82845260fe6020526040842061222d8483613a85565b60fd5460fc5491976001600160a01b03928316949290911692889287613c1a565b7fffad48306557376fc515a68c2431cd2699d06bfa2151ac89cdedf0a55d41aba88280a46001609755005b63d92e233d60e01b5f5260045260245ffd5b5060408201516001600160a01b031615612205565b5060208201516001600160a01b0316156121ff565b3461038a57602036600319011261038a576004355f60c06040516122d881612ab3565b6040516122e481612ae3565b83815283602082015283604082015283606082015281528260208201528260408201528260608201528260808201528260a0820152015260018060a01b036060602061232f8461314c565b01510151163003611fca575f5260fe60205261014060405f2060c06040519161235783612ab3565b61236081612b59565b9283815260018201548060208301526002830154806040840152600384015491826060850152600485015493846080820152600660ff6005880154161515968760a08401520154968791015260c06040516123ba81612ab3565b8881526020810192835260408101938452606081019485526080810195865260a081019687520195865261242660405180986001600160601b036060809264ffffffffff815116855262ffffff6020820151166020860152826040820151166040860152015116910152565b5160808701525160a08601525160c08501525160e084015251151561010083015251610120820152f35b3461038a57602036600319011261038a576004356001600160a01b03606060206124798461314c565b01510151163003611fca5761248d8161314c565b602081015151905160409081015181516341976e0960e01b81526001600160a01b0391821660048201529283916024918391165afa90811561038e575f905f926124f6575b50156124e357602090604051908152f35b5063cd97203f60e01b5f5260045260245ffd5b9050612511915060403d604011610791576107818183612b37565b90836124d2565b3461038a575f36600319011261038a5760206040515f516020615e3f5f395f51905f528152f35b3461038a575f36600319011261038a57602060ff60c954166040519015158152f35b3461038a57602036600319011261038a57602061257f600435612c8e565b6040519015158152f35b3461038a57602036600319011261038a576004355f5260fe60205261014060405f206125b481612b59565b9060018101549060028101546003820154600483015491600660ff6005860154169401549461261b60405180986001600160601b036060809264ffffffffff815116855262ffffff6020820151166020860152826040820151166040860152015116910152565b608087015260a086015260c085015260e08401521515610100830152610120820152f35b3461038a575f36600319011261038a57612657612fe5565b60c95460ff8116156126965760ff191660c9557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b60405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606490fd5b3461038a57604036600319011261038a576126eb612a31565b50633f84111960e21b5f5260045ffd5b3461038a575f36600319011261038a5760206040515f516020615e5f5f395f51905f528152f35b3461038a57604036600319011261038a5760043561273e612a31565b90612758610c45825f526065602052600160405f20015490565b805f52606560205260405f2060018060a01b0383165f5260205260ff60405f2054161561278157005b5f8181526065602090815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291905f516020615e1f5f395f51905f529080a4005b3461038a576127d636612a89565b90916127e0612f4b565b6127e8612fa1565b6127f0613096565b6001600160a01b03606060206128058461314c565b01510151163003611fca5761281981612c8e565b6103af57805f5260fe60205260405f206128328261314c565b936128416102756111fe612c40565b926001830190612852858354612c62565b60028501541061039d5750926128e7836128a86128ed9460209761288361287c8c6128f89a61353a565b80956138a5565b61288e868254612c62565b9055895160400151309033906001600160a01b031661392b565b61197d6128d66128cb6128c089850196875190612d1d565b60a085015190612d1d565b948351905190612d1d565b916080606082015191015190612d1d565b90612d30565b610307610301612c6f565b925101516001600160a01b0316803b1561038a576040516340c10f1960e01b81526001600160a01b03929092166004830152602482018390525f908290604490829084905af1801561038e57612959575b6020826001609755604051908152f35b806129655f8093612b37565b80031261038a5781612949565b3461038a57602036600319011261038a5760206108946004355f526065602052600160405f20015490565b3461038a575f36600319011261038a5760206040515f516020615e7f5f395f51905f528152f35b3461038a57602036600319011261038a576004359063ffffffff60e01b821680920361038a57602091638844e8d160e01b8114908115612a06575b5015158152f35b637965db0b60e01b811491508115612a20575b50836129ff565b6301ffc9a760e01b14905083612a19565b602435906001600160a01b038216820361038a57565b606435906001600160a01b038216820361038a57565b600435906001600160a01b038216820361038a57565b604435906001600160a01b038216820361038a57565b606090600319011261038a5760043590602435906044356001600160a01b038116810361038a5790565b60e0810190811067ffffffffffffffff821117612acf57604052565b634e487b7160e01b5f52604160045260245ffd5b6080810190811067ffffffffffffffff821117612acf57604052565b60a0810190811067ffffffffffffffff821117612acf57604052565b60c0810190811067ffffffffffffffff821117612acf57604052565b90601f8019910116810190811067ffffffffffffffff821117612acf57604052565b90604051612b6681612ae3565b606081935464ffffffffff8116835262ffffff8160281c1660208401526001600160601b038160401c16604084015260a01c910152565b9060a060031983011261038a57608060043592602319011261038a57604051612bc581612ae3565b602435801515810361038a5781526044356001600160a01b038116810361038a5760208201526064356001600160a01b038116810361038a576040820152608435606082015290565b604090600319011261038a576004359060243590565b67ffffffffffffffff8111612acf57601f01601f191660200190565b60405190612c4f604083612b37565b60048252636261736560e01b6020830152565b91908201809211611a0757565b60405190612c7e604083612b37565b60018252600f60fb1b6020830152565b6001600160a01b0360606020612ca38461314c565b01510151163003611fca57612cce81612cbd60c09361314c565b905f5260fe60205260405f2061353a565b01511590565b5190811515820361038a57565b919082604091031261038a576020612cf883612cd4565b92015190565b60405190612d0d604083612b37565b60018252606160f81b6020830152565b81810292918115918404141715611a0757565b8115612d3a570490565b634e487b7160e01b5f52601260045260245ffd5b805f5260ff60205260405f2054620151808101809111611a07574210612e89576001825115151480612e74575b80612e5f575b61227957612d8e81612e8d565b918215611f1b577f62a88264473dbaca9528a17ab39375790b482893fe5d1eae766e6f43114ed3048291612dc18361314c565b835f5260fe602052612e2060405f2091855f5260ff6020524260405f205560018060a01b0360fd54169360018060a01b0360fc541691612e02868b83614c7e565b50809589612e1a60ff60a086015160101c16846134f7565b93614d49565b604080519182526001600160a01b03929092166020820152a27f1c010aedf7d0edeba419efbe7616b2c889056e31cf4454693eb683d0dc4edecd5f80a3565b5060408201516001600160a01b031615612d81565b5060208201516001600160a01b031615612d7b565b5050565b6001600160a01b0360606020612ea28461314c565b01510151163003611fca57612eb690612ec6565b90565b91908203918211611a0757565b612ecf8161314c565b905f5260fe602052600160405f2001549060648210612f4557805160400151612f1d90612f069030906001600160a01b0316613fda565b612f17612f11612c40565b846133a4565b906134f7565b91808311612f2c575050505f90565b612f3c61030791612eb694612eb9565b9161120d612c40565b50505f90565b600260975414612f5c576002609755565b60405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606490fd5b60ff60c95416612fad57565b60405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606490fd5b335f9081527fffdfc1249c027f9191656349feb0761381bb32c9f557e01f419fd08754bf5a1b602052604090205460ff161561301d57565b610c0a61302933615366565b610bf26011610b705f61544c565b335f9081527fea6b36b9f5cb12f73bb1a2064b058edf7e385c60e5d5069a9ac68ba5930d55bd602052604090205460ff161561306f57565b610c0a61307b33615366565b610bf26011610b705f516020615e3f5f395f51905f5261544c565b335f9081527f3d6d979b4bf289e901af1c0967a6ac71ee985fc0ceabfde37691fc047613e6bf602052604090205460ff16156130ce57565b610c0a6130da33615366565b610bf26011610b705f516020615e7f5f395f51905f5261544c565b5f81815260656020908152604080832033845290915290205460ff16156131195750565b610c0a90610bf26011610b7061312e33615366565b9361544c565b67ffffffffffffffff8111612acf5760051b60200190565b905f60a060405161315c81612b1b565b60405161316881612aff565b838152836020820152836040820152836060820152836080820152815260405161319181612ab3565b83815283602082015283604082015283606082015283608082015283838201528360c082015260208201528260408201526060808201528260808201520152815f5260fb60205260405f209160ff6011840154161561337157506040516131f781612b1b565b60405161320381612aff565b83546001600160a01b03908116825260018501548116602083015260028501548116604080840191909152600386015482166060840152600486015490911660808301529082525161325481612ab3565b60058401546001600160a01b0390811682526006850154811660208084019190915260078601548216604080850191909152600887015483166060850152600987015483166080850152600a870154831660a0850152600b87015490921660c0840152830191909152600c84015490820152600d830180549093906132d881613134565b906132e66040519283612b37565b80825260208201955f5260205f20955f905b828210613327575050506060830152600e8101546001600160a01b03166080830152600f015460a08201529150565b6003602060019260405161333a81612ae3565b60ff8c54868060a01b038116835260a01c1683820152848c0154604082015260028c015460608201528152019801910190966132f8565b6337e1342d60e21b5f5260045260245ffd5b5f5b8381106133945750505f910152565b8181015183820152602001613385565b9060405190602082018151926133d6602082818601966133c581878a613383565b81010301601f198101835282612b37565b5190206040516020810190636261736560e01b8252600481526133fa602482612b37565b5190200361341157505060a0015160101c60ff1690565b604051602081019061342c60208285516133c581878a613383565b5190206040516020810190606160f81b82526001815261344d602182612b37565b5190200361346157505060a0015160ff1690565b61347d602060405180936133c583830196879251928391613383565b5190206040516020810190600f60fb1b82526001815261349e602182612b37565b519020036134b35760a0015160081c60ff1690565b63a1e9dd9d60e01b5f5260045ffd5b60ff6011199116019060ff8211611a0757565b60ff166012039060ff8211611a0757565b60ff16604d8111611a0757600a0a90565b60ff82166012811461353457601211156135255761351f61351a612eb6936134d5565b6134e6565b90612d1d565b6128e761351a612eb6936134c2565b50905090565b9190604051610100810181811067ffffffffffffffff821117612acf576040525f815260208101915f835260408201925f845260608301905f825260808401935f855260a08101935f855260c08201965f885260e08301905f8252839a60a0840151916135bb60ff8460101c16600160ff8087169660081c169401546134f7565b8652602085015151855160409081015181516341976e0960e01b81526001600160a01b039182166004820152939284916024918391165afa91821561038e575f905f93613881575b50158015613879575b61386a5781885252845161363357505050505050505090670de0b6b3a7640000809252525b565b8351516040516318160ddd60e01b81529899979890602090829060049082906001600160a01b03165afa801561038e575f90613837575b85516020908101516040516318160ddd60e01b81529350839060049082906001600160a01b03165afa91821561038e575f92613801575b506136b6936136af916134f7565b89526134f7565b8752815151604051639faa3c9160e01b815290602090829060049082906001600160a01b03165afa90811561038e575f916137c7575b501580159091526137b657515160405163c1590cd760e01b815290602090829060049082906001600160a01b03165afa90811561038e575f91613784575b5083525b8451613746575050505050670de0b6b3a76400009052565b61376292916137589151905190612d1d565b9251905190612d1d565b9081811061377c5761377892916119a191612eb9565b9052565b5050505f9052565b90506020813d6020116137ae575b8161379f60209383612b37565b8101031261038a57515f61372a565b3d9150613792565b50670de0b6b3a7640000835261372e565b90506020813d6020116137f9575b816137e260209383612b37565b8101031261038a576137f390612cd4565b5f6136ec565b3d91506137d5565b9091506020813d60201161382f575b8161381d60209383612b37565b8101031261038a5751906136b66136a1565b3d9150613810565b506020813d602011613862575b8161385160209383612b37565b8101031261038a576004905161366a565b3d9150613844565b630ae7ae7760e21b5f5260045ffd5b50811561360c565b905061389d91925060403d604011610791576107818183612b37565b91905f613603565b6020906138d27f5f7c2fa4633ef1ba390069935f57e39241415a5fac1e69c762c72c789bed489d93614b83565b906138dc8161516e565b815467ffffff00000000001660a09190911b6001600160a01b03191617604083811b73ffffffffffffffffffffffff000000000000000016919091174264ffffffffff161790915551908152a1565b9192916001600160a01b0316908161394c57631954782960e01b5f5260045ffd5b6001600160a01b03169133830361399d5761363193604051936323b872dd60e01b6020860152602485015260018060a01b03166044840152606483015260648252613998608483612b37565b6154ee565b63f8fd233360e01b5f5260045ffd5b60ff82166012811461353457601211156139cf576128e761351a612eb6936134d5565b61351f61351a612eb6936134c2565b6001600160a01b0381165f9081527f55b7d6438a27f557ce2e68ce9e0414fa62195bc72edfca0c05472cd322380f72602052604090205460ff1615613a205750565b6001600160a01b03165f8181527f55b7d6438a27f557ce2e68ce9e0414fa62195bc72edfca0c05472cd322380f7260205260408120805460ff191660011790553391905f516020615e5f5f395f51905f52905f516020615e1f5f395f51905f529080a4565b90915f91602060018060a01b039151015116926040516370a0823160e01b8152306004820152602081602481885afa90811561038e575f91613be8575b50843b1561038a5760405163643cb2b960e11b81525f81600481838a5af19081613bd3575b50613b24575050503d80916040519363643cb2b960e11b8552600485015260406024850152816044850152606484013e601f801991011660640190fd5b60206024929395604051938480926370a0823160e01b82523060048301525afa80156110bd578490613b9f575b613b5b9250612eb9565b918215613b9057507f381ff38e2fec0d64b5d6f95156decdb3e229ef47c184126bbb5511a7bf32cf106020604051848152a290565b631f2a200560e01b8152600490fd5b506020823d602011613bcb575b81613bb960209383612b37565b8101031261038a57613b5b9151613b51565b3d9150613bac565b613be09195505f90612b37565b5f935f613ae7565b90506020813d602011613c12575b81613c0360209383612b37565b8101031261038a57515f613ac2565b3d9150613bf6565b9491929596939096602088510151965f9760018060a01b031698600460208b6040519283809263a111723160e01b82525afa90811561038e575f91613e63575b506006811015613e4f5760018114613e295760028114908115613e1e575b50613c9157637aa460c960e11b89526004889052602489fd5b899796973b1561038a57604051632770a7eb60e21b8152306004820152602481018590525f81604481838f5af19081613e09575b50613d015789893d809160405193632770a7eb60e21b8552600485015260406024850152816044850152606484013e601f801991011660640190fd5b9193959760206024929496989a6040519384809263124ca52960e01b82528a60048301525afa918215610798579089918193613da9575b5097839291612e1a613d7f8a60ff7f51392bf9d32fbeaa79ec8834e63548707bbaa882d9ce800f31db15cb4fd062689d60a0613d879c9b9a0151905060101c169587614c7e565b5093846134f7565b604080519182526001600160a01b03909216602082015290819081015b0390a2565b959493925090506020853d602011613e01575b81613dc960209383612b37565b8101031261038a57935192939192909188907f51392bf9d32fbeaa79ec8834e63548707bbaa882d9ce800f31db15cb4fd06268613d38565b3d9150613dbc565b613e16919a505f90612b37565b5f985f613cc5565b60039150145f613c78565b505160200151959850613631975091955091936001600160a01b03169250614af3915050565b634e487b7160e01b5f52602160045260245ffd5b90506020813d602011613e96575b81613e7e60209383612b37565b8101031261038a5751600681101561038a575f613c5a565b3d9150613e71565b90613ea89161353a565b905f915f918151613ebf6020840191825190612d1d565b670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a0757613efe6080613ef3606087015186612d1d565b950194855190612d1d565b92838211613f10575b50505050509091565b93955091935091670de0b6b3a763ffff198101908111611a0757613f4e613f4882613f41613f55976128e796612eb9565b9551612d1d565b84612d30565b9451612d1d565b5f80808080613f07565b90613f699161353a565b805115613fcd57606081018051158015613fc1575b613fac57613fa6826080613f9b612eb69551602084015190612d1d565b935191015190612d1d565b906151f9565b50506ec097ce7bc90715b34b9f100000000090565b50608082015115613f7e565b50670de0b6b3a764000090565b6001600160a01b031680613fed57503190565b6040516370a0823160e01b81526001600160a01b039092166004830152602090829060249082905afa90811561038e575f91614027575090565b90506020813d60201161404e575b8161404260209383612b37565b8101031261038a575190565b3d9150614035565b919290859695949161406882876134f7565b9361407c836140778389613fda565b6134f7565b8581106140dc575b5050505092847f57019a8e75e12d459999803f3a22046f4ada495918e1b915de1f2fefe62fac2395936140c9936140c2600160209801918254612eb9565b9055614af3565b6040519384526001600160a01b031692a2565b856140ed9293949596979850612eb9565b9182156142195760405163abae70c560e01b81526004810184905290602090829060249082905f906001600160a01b03165af190811561038e575f916141df575b50156141d05760068401918254918183106141c15761415d93614155614077938795612eb9565b905587613fda565b90818411614172575b80808896959493614084565b6001965085935094602094826140c26141b17f57019a8e75e12d459999803f3a22046f4ada495918e1b915de1f2fefe62fac23996140c99796936139ac565b9950509496509450819250614166565b6302100b1160e21b5f5260045ffd5b637286ef7960e11b5f5260045ffd5b90506020813d602011614211575b816141fa60209383612b37565b8101031261038a5761420b90612cd4565b5f61412e565b3d91506141ed565b505050505050505050565b1561422b57565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b9061428e9161353a565b908151916142a26020820193845190612d1d565b670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a07576142d1606083015184612d1d565b90670de0b6b3a7640000820291808304670de0b6b3a76400001490151715611a07578082111561433b5761430491612eb9565b90670de0b6b3a763ffff198301928311611a075761433892614330613f4860806128e794015183612d1d565b945190612d1d565b91565b50505050505f5f9091565b6001600160a01b03168015614aad57815f5260fb60205260245f604081209260405192838092635ab3ea5d60e11b82528760048301525afa90811561038e575f91614877575b508051516001600160a01b0316156146ab5760608101805151801561486457600d84019182545f845580614825575b505f5b82811061477a575050825180519092506001600160a01b03161590508015614765575b8015614750575b801561473b575b61461457805160208201516001600160a01b03918216911681811492918315614724575b831561470d575b5082156146f6575b82156146df575b5081156146be575b506146ab5760208101805180516001600160a01b031615908115614695575b811561467f575b8115614669575b8115614653575b811561463d575b8115614627575b50614614578151805184546001600160a01b03199081166001600160a01b039283161786556020808401516001808901805485169286169290921790915560408086015160028a018054861691871691909117905560608087015160038b018054871691881691909117905560809687015160048b01805487169188169190911790559651805160058b01805487169188169190911790559283015160068a01805486169187169190911790558281015160078a018054861691871691909117905595820151600889018054851691861691909117905581850151600989018054851691861691909117905560a082810151600a8a018054861691871691909117905560c090920151600b89018054851691861691909117905594860151600c880155850151600f8701559190930151600e85018054909216931692909217909155436010830155601191909101805460ff19169091179055807f67795b7df97de6699e0f17226d6111be2ddc0ebe76fb110c2e8ab6df9312579f5f80a26001600160a01b03606060206146068461314c565b01510151163003611fca5750565b83635dbad7a160e01b5f5260045260245ffd5b60c001516001600160a01b03161590505f614473565b60a08101516001600160a01b031615915061446c565b60808101516001600160a01b0316159150614465565b60608101516001600160a01b031615915061445e565b60408101516001600160a01b0316159150614457565b60208101516001600160a01b0316159150614450565b82635dbad7a160e01b5f5260045260245ffd5b60408101516060909101516001600160a01b0390811691161490505f614431565b60608201516001600160a01b03161491505f614429565b60408201516001600160a01b031681149250614422565b60608301516001600160a01b03161492505f61441a565b60408301516001600160a01b031681149350614413565b5060608101516001600160a01b0316156143ef565b5060408101516001600160a01b0316156143e8565b5060208101516001600160a01b0316156143e1565b614785818351615605565b519084549168010000000000000000831015612acf5760018301808755831015614811575f86815260209081902082516003909502018054918301516001600160a81b03199092166001600160a01b03959095169490941760a09190911b60ff60a01b1617835560408101516001848101919091556060919091015160029390930192909255016143be565b634e487b7160e01b5f52603260045260245ffd5b80600302906003820403611a0757835f5260205f20908101905b81811061484c57506143bb565b805f600392555f60018201555f60028201550161483f565b8463f4ac45b160e01b5f5260045260245ffd5b90503d805f833e6148888183612b37565b81019060208183031261038a5780519067ffffffffffffffff821161038a570180820391610200831261038a57604051926148c284612b1b565b60a0811261038a5760e0906040516148d981612aff565b6148e285615bc9565b81526148f060208601615bc9565b602082015261490160408601615bc9565b604082015261491260608601615bc9565b606082015261492360808601615bc9565b60808201528552609f19011261038a5760405161493f81612ab3565b61494b60a08401615bc9565b815261495960c08401615bc9565b602082015261496a60e08401615bc9565b604082015261497c6101008401615bc9565b606082015261498e6101208401615bc9565b60808201526149a06101408401615bc9565b60a08201526149b26101608401615bc9565b60c0820152602084015261018082015160408401526101a082015167ffffffffffffffff811161038a57820181601f8201121561038a578051906149f582613134565b92614a036040519485612b37565b82845260208085019360071b8301019181831161038a57602001925b828410614a52575050505060608301526101e090614a406101c08201615bc9565b6080840152015160a08201525f61438c565b60808483031261038a5760405190614a6982612ae3565b614a7285615bc9565b825260208501519060ff8216820361038a57826020928360809501526040870151604082015260608701516060820152815201930192614a1f565b506324df413360e21b5f5260045260245ffd5b817fb13143af250a090d8b08b199f27b7bb426e38b9f377b101ea3205d5ca83f07559260026020930155604051908152a1565b9091906001600160a01b031680614b1357630c5d6fad60e21b5f5260045ffd5b60405163a9059cbb60e01b60208201526001600160a01b0390931660248401526044830191909152613631919061399882606481015b03601f198101845283612b37565b60409160208252614b778151809281602086015260208686019101613383565b601f01601f1916010190565b60e0810151613fcd578051158015614c72575b8015614c66575b614c6157614bb46060820151608083015190612d1d565b670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a07576128e7826040614be9945191015190612d1d565b670de0b6b3a76400008110614c06575068056bc75e2d6310000090565b80670de0b6b3a76400000390670de0b6b3a76400008211611a0757670de0b6b3a764000014612d3a576ec097ce7bc90715b34b9f1000000000049068056bc75e2d631000008211614c5357565b68056bc75e2d631000009150565b505f90565b50604081015115614b9d565b50602081015115614b96565b60208181015160c0015160405163e16777c160e01b8152959493915f91879060049082906001600160a01b03165afa95861561038e575f96614d15575b508515614d0c5750612710614cd3614cdd9683612d1d565b0494858092612eb9565b9281614ceb575b5050509190565b915160400151614d0492906001600160a01b0316614af3565b5f8381614ce4565b94509150509190565b9095506020813d602011614d41575b81614d3160209383612b37565b8101031261038a5751945f614cbb565b3d9150614d24565b8051805160408089018051602086018051519584015184516341976e0960e01b81526001600160a01b039182166004820152989d939c9281169b5f9b989a9299939897909692959282169493929183916024918391165afa90811561038e575f905f9261514c575b50158015615144575b61386a5760405163c1590cd760e01b815290602082600481875afa90811561038e575f9161510e575b614dee9250866152d5565b604051631a3acfc360e31b8152600481018e90529091602090829060249082906001600160a01b03165afa801561038e5782915f916150c2575b506001600160601b03614e3d91168a86613e9e565b9050105f14614f96575050835115614f825791602091614e636001899501918254612eb9565b9055602460018060a01b0360408851015116916040519485938492636f074d1f60e11b845260048401525af1948515614f765794614f38575b5091614f0e8492614ef587957fe91e44a5e14583bb47bf0c9cd41988f95e0d3fd88b342c44ae58bc38f27e2912999760809960018060a01b0360208401511692606060018060a01b03818a510151169101519330615619565b905160c00151909485916001600160a01b031690614af3565b51604090810151935181516001600160a01b039586168152941660208501528301526060820152a2565b9593509093916020863d602011614f6e575b81614f5760209383612b37565b8101031261038a5794519294919390614f0e614e9c565b3d9150614f4a565b604051903d90823e3d90fd5b637e61a6cb60e11b875260048a9052602487fd5b959850985060ff935060a0925090614fb76001614fc2979301918254612c62565b9055015116906139ac565b9260018060a01b0360c0845101511690803b1561038a576040516340c10f1960e01b81526001600160a01b03929092166004830152602482018590525f908290604490829084905af1801561038e576150af575b50815160c001516001600160a01b0316803b1561083b57818091600460405180948193630712235560e31b83525af180156107be5761509a575b50505160c00151604080519283526001600160a01b0390911660208301527f5fb9b8afcb71da1bf9b20ce82cf328dcf7636eceebe61b8bacd2165a64556a5d919081908101613da4565b6150a5828092612b37565b6103d35780615050565b6150bb91505f90612b37565b5f5f615016565b9150506020813d602011615106575b816150de60209383612b37565b8101031261038a57516001600160601b038116810361038a5781906001600160601b03614e28565b3d91506150d1565b90506020823d60201161513c575b8161512960209383612b37565b8101031261038a57614dee915190614de3565b3d915061511c565b508015614dba565b9050615167915060403d604011610791576107818183612b37565b905f614db1565b5464ffffffffff8116428110156151f25761519e90670de0b6b3a764000062ffffff8460281c1691420302612d30565b90680238fd42c5cf0400008211156151c1576001600160601b03915060401c1690565b6151d5670de0b6b3a7640000925f03615757565b906001600160601b03828260a01c029284039160401c1602010490565b5060a01c90565b90670de0b6b3a76400008202905f19670de0b6b3a7640000840992828085109403938085039485841115615290571461528957670de0b6b3a764000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b60405162461bcd60e51b815260206004820152601f60248201527f46756c6c4d6174683a2064656e6f6d696e61746f7220746f6f20736d616c6c006044820152606490fd5b91818302915f1981850993838086109503948086039586851115615290571461534d579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b908151811015614811570160200190565b615370602a612c24565b9061537e6040519283612b37565b602a825261538c602a612c24565b6020830190601f19013682378251156148115760309053815160011015614811576078602183015360295b6001811161540b57506153c75790565b606460405162461bcd60e51b815260206004820152602060248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152fd5b90600f81166010811015614811576f181899199a1a9b1b9c1cb0b131b232b360811b901a6154398385615355565b5360041c908015611a07575f19016153b7565b6154566042612c24565b906154646040519283612b37565b604282526154726042612c24565b6020830190601f19013682378251156148115760309053815160011015614811576078602183015360415b600181116154ad57506153c75790565b90600f81166010811015614811576f181899199a1a9b1b9c1cb0b131b232b360811b901a6154db8385615355565b5360041c908015611a07575f190161549d565b9061556d9160018060a01b03165f806040519361550c604086612b37565b602085527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564602086015260208151910182855af13d156155fd573d9161555183612c24565b9261555f6040519485612b37565b83523d5f602085013e615d8d565b80519081159182156155db575b50501561558357565b60405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b819250906020918101031261038a5760206155f69101612cd4565b5f8061557a565b606091615d8d565b80518210156148115760209160051b010190565b93919293601e420190814211611a0757604051615637606082612b37565b6002815260208101956040368837815115614811576001600160a01b03169586905280516001101561481157878561569b95604084019960018060a01b0316809a5261568481868b615bdd565b8281106156e4575b506001600160a01b0316615c35565b9384106156d55760407fdd36740e2a012d93061a0d99eaa9107860955de4e90027d3cf465a055026c407918151908152856020820152a390565b6374f79b2960e01b5f5260045ffd5b6156f16156f89184612eb9565b828b615afb565b5f61568c565b1561570557565b60405162461bcd60e51b815260206004820152601060248201526f1253959053125117d1561413d391539560821b6044820152606490fd5b8015612d3a576ec097ce7bc90715b34b9f10000000000590565b680238fd42c5cf03ffff1981121580615ae8575b615774906156fe565b5f8112615ad457612eb6906806f05b59d3b20000008112615a93576806f05b59d3b1ffffff19016159366064770195e54c5dd42177f53a27172fa9ec630262827000000000925b0268056bc75e2d631000009068ad78ebc5ac62000000811215615a70575b6856bc75e2d631000000811215615a42575b682b5e3af16b18800000811215615a16575b6815af1d78b58c4000008112156159ea575b680ad78ebc5ac62000008112156159bf575b68056bc75e2d63100000811215615994575b6802b5e3af16b1880000811215615969575b68015af1d78b58c4000081121561593e575b600268056bc75e2d631000008280020505600368056bc75e2d631000008383020505600468056bc75e2d631000008483020505600568056bc75e2d631000008583020505600668056bc75e2d631000008683020505600768056bc75e2d63100000878302050590600868056bc75e2d63100000888402050592600968056bc75e2d6310000089860205059468056bc75e2d63100000600a8a88028290050597600b68056bc75e2d631000008c8b02050599600c68056bc75e2d631000008d8d0205059b0101010101010101010101010268056bc75e2d63100000900590565b026064900590565b68015af1d78b58c3ffff19019068056bc75e2d631000006806f5f17757889379379091020590615857565b6802b5e3af16b187ffff19019068056bc75e2d631000006808f00f760a4b2db55d9091020590615845565b68056bc75e2d630fffff19019068056bc75e2d63100000680ebc5fb417461211109091020590615833565b680ad78ebc5ac61fffff19019068056bc75e2d6310000068280e60114edb805d039091020590615821565b6815af1d78b58c3fffff19019068056bc75e2d63100000690127fa27722cc06cc5e2909102059061580f565b682b5e3af16b187fffff19019068056bc75e2d63100000693f1fce3da636ea5cf85090910205906157fd565b6856bc75e2d630ffffff19019068056bc75e2d631000006b02df0ab5a80a22c61ab5a70090910205906157eb565b6e01855144814a7ff805980ff0084000915068ad78ebc5ac61ffffff19016157d9565b6803782dace9d90000008112615ac7576803782dace9d8ffffff190161593660646b1425982cf597cd205cef7380926157bb565b61593660646001926157bb565b615adf905f03615757565b612eb69061573d565b5068070c1cc73b00c8000081131561576b565b6001600160a01b03168015615bba57604051636eb1769f60e11b81523060048201526001600160a01b038316602482015292602084604481855afa93841561038e575f94615b84575b50615b556139989161363195612c62565b60405163095ea7b360e01b60208201526001600160a01b03909416602485015260448401528260648101614b49565b93506020843d602011615bb2575b81615b9f60209383612b37565b8101031261038a57925192615b55615b44565b3d9150615b92565b63220abce160e01b5f5260045ffd5b51906001600160a01b038216820361038a57565b6001600160a01b03169182615bf3575050505f90565b604051636eb1769f60e11b81526001600160a01b0392831660048201529116602482015290602090829060449082905afa90811561038e575f91614027575090565b939490949291926040519586946338ed173960e01b865260a48601916004870152602486015260a060448601528351809152602060c486019401905f5b818110615d6b575050506001600160a01b03908116606485015260848401919091525f93918390039183918591165af15f9181615cd8575b50615cbe576374f79b2960e01b5f5260045ffd5b80515f198101908111611a0757615cd491615605565b5190565b9091503d805f833e615cea8183612b37565b81019060208183031261038a5780519067ffffffffffffffff821161038a57019080601f8301121561038a578151615d2181613134565b92615d2f6040519485612b37565b81845260208085019260051b82010192831161038a57602001905b828210615d5b57505050905f615caa565b8151815260209182019101615d4a565b82516001600160a01b0316865288965060209586019590920191600101615c72565b91929015615def5750815115615da1575090565b3b15615daa5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b825190915015615e025750805190602001fd5b60405162461bcd60e51b8152908190610c0a9060048301614b5756fe2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d3fc733b4d20d27a28452ddf0e9351aced28242fe03389a653cdb783955316b9b767b56a6f9d29ab1315e16c17b56dfe5edc8988075500f6ef388c6dc4b0e045dba279271fb7bbf76a6f3df3cc57bf80647fcafdea60ec3383d90f459de74e7c065d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa2646970667358221220d8543d70c908e965a6bf0382ef55d6d8d8ac7f10c6f9f7854f90d6897ac8a76364736f6c634300081c0033
Deployed Bytecode
0x6080806040526004361015610034575b503615610025576339218f3b60e01b5f5260045ffd5b6339218f3b60e01b5f5260045ffd5b5f905f3560e01c90816301ffc9a7146129c45750806302768de41461299d578063248a9ca3146129725780632569e86c146127c85780632f2ff15d1461272257806335046416146126fb57806336568abe146126d25780633f4ba83a1461263f5780634943d301146125895780634d9d6024146125615780635c975abb1461253f57806363a560ec1461251857806373602fb41461245057806373f6cefc146122b557806379850ce7146121b35780637ac6f8ab146121485780638456cb591461209a578063861980521461204d5780638ce744261461202557806391d1485414611fdc578063973ed91f14611f5e578063a05a600b14611a4b578063a217fddf14611a2f578063a86ba52a146116d1578063aa95d40114611672578063b37b486214611648578063c0c53b8b14611245578063c1b8f40f14611186578063c415b95c1461115d578063d246c5bc14610d53578063d2c35ce814610ccf578063d547741f14610c0e578063e3dab55014610ae4578063e526fed214610ac5578063e63ab1e914610a9d578063e6b6312814610989578063e88fb871146108ae578063f3c479971461083f578063f665b214146103d65763fde0b0820361000f57346103d35761020236612a89565b90929161020d612f4b565b610215612fa1565b61021d613096565b6001600160a01b03606060206102328461314c565b015101511630036103c15761024681612c8e565b6103af57805f5260fe60205260405f20906102608161314c565b9461027b61027561026f612c40565b886133a4565b826134f7565b91600184019061028c848354612c62565b60028601541061039d57506102ed6102f6936102e286946080946102bd6102b68d61030d9b61353a565b80986138a5565b6102c8848254612c62565b90558a5160400151309033906001600160a01b031661392b565b602084015190612d1d565b91015190612d30565b610307610301612cfe565b866133a4565b906139ac565b9251516001600160a01b031690813b15610399576040516340c10f1960e01b81526001600160a01b0391909116600482015260248101849052919081908390604490829084905af1801561038e57610370575b6020836001609755604051908152f35b9061037c5f9282612b37565b80031261038a575f80610360565b5f80fd5b6040513d5f823e3d90fd5b8280fd5b639d1bab0960e01b5f5260045260245ffd5b63658242c560e01b5f5260045260245ffd5b635dbad7a160e01b8352600452602482fd5b80fd5b50346103d35760a03660031901126103d357600435608036602319011261083b5760405161040381612ae3565b6024358152610410612a73565b6020820190815261041f612a47565b60408301908152606083016084358152610437612f4b565b6001600160a01b036060602061044c8861314c565b015101511630036108275761045f612fe5565b6104688561314c565b9160a083019283519287895260fe6020526001600160601b0360408a2094603b1c166104948386613f5f565b87516001600160a01b0316158015610815575b6108065788519182159283156107fb575b5082156107f0575b5081156107dd575b506107c9576104d987518386614284565b83515160208501805160c001518951919694506001600160a01b0392831693928e9291169061050b9060ff16846139ac565b90843b1561039957604051632770a7eb60e21b81526001600160a01b039190911660048201526024810191909152818160448183885af180156107be576107a5575b5050845151835160409081015181516341976e0960e01b81526001600160a01b03918216600482015294928f929186916024918391165afa938415610798578194610764575b5015801561075c575b61074d578c9493929160206004926040519384809263c1590cd760e01b82525afa918215610742578692610708575b50906105d792916152d5565b97518551925197516001600160a01b03938416939190911691906020906106049060101c60ff168b6139ac565b602460018060a01b0360408551015116916040519788938492636f074d1f60e11b845260048401525af19384156106fd578c946106b7575b5096600196959361067e9593610664936106879a60608b8060a01b0391510151169030615619565b9151905160c0015160a086901b8690039081169116614af3565b01918254612eb9565b905551907f0f471384eb459a67f4e6a9130f154a67b2fccb91ca6f319e9aa6dd472a0ec26d8380a3600160975580f35b91949296959350966020823d6020116106f5575b816106d860209383612b37565b8101031261038a579051909694959294919390929161068761063c565b3d91506106cb565b6040513d8e823e3d90fd5b92915094506020823d60201161073a575b8161072660209383612b37565b8101031261038a5790518c946105d76105cb565b3d9150610719565b6040513d88823e3d90fd5b630ae7ae7760e21b8d5260048dfd5b50821561059c565b905061078991935060403d604011610791575b6107818183612b37565b810190612ce1565b92905f610593565b503d610777565b50604051903d90823e3d90fd5b816107af91612b37565b6107ba578b5f61054d565b8b80fd5b6040513d84823e3d90fd5b630303022d60e21b89526004889052602489fd5b670de0b6b3a7640000915011155f6104c8565b81101591505f6104c0565b82101592505f6104b8565b63d92e233d60e01b8b5260048bfd5b5084516001600160a01b0316156104a7565b635dbad7a160e01b86526004859052602486fd5b5080fd5b50346103d35760203660031901126103d357600435906001600160a01b036060602061086a8561314c565b0151015116300361089c578160406108949261088760209561314c565b92815260fe855220613f5f565b604051908152f35b602491635dbad7a160e01b8252600452fd5b50346103d3576108bd36612c0e565b906108c6612fe5565b6001600160a01b03606060206108db8461314c565b015101511630036103c15781158015610971575b8015610959575b6109475780835260fe60205260026040842001549080845260fe6020526109208360408620614ac0565b7f2077bbe429859a2793babc143041af43b6197d85275f53cac01450607f2fedfe8480a480f35b63118341d960e01b8352600452602482fd5b5080835260fe602052600160408420015482106108f6565b5080835260fe602052600260408420015482146108ef565b50346103d35761099836612c0e565b906109a1612f4b565b6001600160a01b03606060206109b68461314c565b015101511630036103c1576109ca8161314c565b602081015160a001516001600160a01b03163303610a8e5781845260fe602052604084206001610a0a610a046109fe612c40565b856133a4565b866134f7565b9160068101610a1a848254612c62565b905501908154818110610a7a5791610a37610a4e94928794612eb9565b9055516040015133906001600160a01b0316614af3565b7f7baa823fe1737fb055aa4f86aecc858a61acddcb591ea0b95311bfaaff59a2248380a3600160975580f35b63040b0a2d60e01b87526004859052602487fd5b63ade5da5f60e01b8452600484fd5b50346103d357806003193601126103d35760206040515f516020615e9f5f395f51905f528152f35b50346103d35760203660031901126103d3576020610894600435612e8d565b50346103d35760403660031901126103d357610afe612a5d565b610b06612f4b565b5f516020615e5f5f395f51905f528252606560209081526040808420335f908152925290205460ff1615610b4957610b419060243590614346565b600160975580f35b610c0a610b5533615366565b610bf26011610b705f516020615e5f5f395f51905f5261544c565b9260376040519485927f416363657373436f6e74726f6c3a206163636f756e74200000000000000000006020850152610bb28151809260208688019101613383565b83017001034b99036b4b9b9b4b733903937b6329607d1b83820152610be1825180936020604885019101613383565b01010301601f198101835282612b37565b60405162461bcd60e51b815291829160048301614b57565b0390fd5b50346103d35760403660031901126103d357600435610c2b612a31565b90610c4a610c45825f526065602052600160405f20015490565b6130f5565b80835260656020526040832060018060a01b0383165f5260205260ff60405f205416610c74578280f35b8083526065602090815260408085206001600160a01b03949094165f81815294909252909220805460ff191690553391907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b8480a45f808280f35b50346103d35760203660031901126103d357610ce9612a5d565b610cf1612fe5565b6001600160a01b03168015610d445760fd80546001600160a01b0319811683179091556001600160a01b03167fcc882185e6edeeb762130016ea1faf3d7aa9c01b199bfd646f965b58ab7410638380a380f35b63d92e233d60e01b8252600482fd5b50346103d35760a03660031901126103d357610d6d612a5d565b602435606036604319011261039957610d84612f4b565b610d8c612fe5565b6001600160a01b0382161561114e57604435801561113a5781845260fe6020526040842090600582019360ff85541661112657836001600160a01b0360606020610dd58461314c565b01510151163003611116575b610df69150610def9061314c565b9183614ac0565b602081015151815160409081015181516341976e0960e01b81526001600160a01b039182166004820152969287916024918391165afa94851561074257869087966110f2575b501580156110ea575b6110db57908291856004889501557f4b02072719fa9787c31ae0719421e5b921c10e6da6eaf9a4f7ddda13dc2b3ddd6020604051888152a160643590610e95610e8f6109fe612c40565b836134f7565b6001850181905584547b1bc16d674ec80000000000000000000000000000015180000000000073ffffffffffffffffffffffff000000ffffffffff73ffffffffffffffffffffffff000000ffffffffff199092164264ffffffffff16176503782dace9d960531b179190911617909455604051671bc16d674ec8000081527fd2148a73b824404e6bde3e68b87ff1d3c2b24c734dc65de8efaa37a0be423e1a90602090a1805460ff19166001179055671bc16d674ec80000610f578785612d1d565b049260843580151581036110d7576110cc575b50610fac610f91610f85610f7f610301612cfe565b866139ac565b94610307610301612c6f565b835160400151909290309033906001600160a01b031661392b565b8151602001516001600160a01b0316803b156110c8576040516340c10f1960e01b8152306004820152602481019290925284908290604490829084905af19081156110bd5784916110a8575b505051516001600160a01b0316803b15610399576040516340c10f1960e01b8152306004820152602481019290925282908290604490829084905af180156107be57611093575b5080827f0cd738c9c0bbe501d6da72544aaef2b26bfdcbffa10507ff2755918321897c56828694a47fc737d26127da3bd7f66d0d10fe580666127260220a2ff721985d1b2f5ed3da968380a3600160975580f35b8161109d91612b37565b61039957825f61103f565b816110b291612b37565b61039957825f610ff8565b6040513d86823e3d90fd5b8480fd5b60011c92505f610f6a565b8580fd5b630ae7ae7760e21b8652600486fd5b508415610e45565b905061110e91955060403d604011610791576107818183612b37565b94905f610e3c565b61111f91614346565b5f83610de1565b630cee99df60e01b86526004849052602486fd5b63118341d960e01b84526004829052602484fd5b63d92e233d60e01b8352600483fd5b50346103d357806003193601126103d35760fd546040516001600160a01b039091168152602090f35b50346103d35761119536612c0e565b91906001600160a01b03606060206111ac8461314c565b0151015116300361123257670de0b6b3a764000083111561121f576112046103076111f160409584876111e16112139761314c565b978892815260fe60205220614284565b92906103076111fe612c40565b876133a4565b9361120d612cfe565b906133a4565b82519182526020820152f35b6315063bef60e21b825260045260249150fd5b635dbad7a160e01b825260045260249150fd5b50346103d35760603660031901126103d35761125f612a5d565b611267612a31565b61126f612a73565b9183549260ff8460081c16159384809561163b575b8015611624575b156115c85760ff1981166001178655846115b7575b506001600160a01b03821691821580156115a6575b8015611595575b61158657611395906112fd60ff885460081c166112d881614224565b6112e181614224565b6112ea81614224565b60016097556112f881614224565b614224565b60ff1960c9541660c95586805260656020526040872060018060a01b0384165f5260205260ff60405f20541615611540575b5f516020615e9f5f395f51905f52875260656020526040872060018060a01b0384165f5260205260ff60405f205416156114ed575b5f516020615e7f5f395f51905f528752606560205260408720845f5260205260ff60405f20541615611499576139de565b61139e816139de565b5f516020615e3f5f395f51905f52855260656020526040852060018060a01b0382165f5260205260ff60405f20541615611440575b506001600160601b0360a01b60fc54161760fc5560018060a01b03166001600160601b0360a01b60fd54161760fd556114095780f35b61ff001981541681557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a180f35b5f516020615e3f5f395f51905f528086526065602090815260408088206001600160a01b03949094165f81815294909252909220805460ff191660011790553391905f516020615e1f5f395f51905f528780a45f6113d3565b5f516020615e7f5f395f51905f528752606560205260408720845f5260205260405f20600160ff1982541617905533845f516020615e7f5f395f51905f525f516020615e1f5f395f51905f528a80a46139de565b5f516020615e9f5f395f51905f52808852606560209081526040808a206001600160a01b0387165f8181529190935220805460ff1916600117905533915f516020615e1f5f395f51905f528a80a4611364565b8680526065602090815260408089206001600160a01b0386165f8181529190935220805460ff191660011790553390885f516020615e1f5f395f51905f528180a461132f565b63d92e233d60e01b8652600486fd5b506001600160a01b038416156112bc565b506001600160a01b038216156112b5565b61ffff19166101011785555f6112a0565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b15801561128b5750600160ff82161461128b565b50600160ff821610611284565b50346103d35760203660031901126103d3576040602091600435815260ff83522054604051908152f35b50346103d35761168136612b9d565b61168c929192612f4b565b611694613037565b6001600160a01b03606060206116a98661314c565b015101511630036116be57610b419192612d4e565b50602491635dbad7a160e01b8252600452fd5b50346103d35760803660031901126103d3576024356004356044356116f4612a47565b936116fd612f4b565b611705612fa1565b61170d613096565b6001600160a01b03606060206117228661314c565b01510151163003611a1b576117368361314c565b91835f5260fe60205260405f2093611758611752610301612cfe565b876134f7565b61176c6117666111fe612c6f565b846134f7565b906117848960208851015160018060a01b0316613fda565b6064019283606411611a07578415159384908690826119fd575b50506119d457836117af888a61353a565b936117ba858b6138a5565b60c085015161194757506103af57506117ec9160606102ed6117e19360018b015490612d1d565b6103076111fe612c40565b95806118cb575b50611843575b6020856118368882888861181461180e612c40565b826133a4565b8151604001519188015160a001516001600160a01b0390811692169030614056565b6001609755604051908152f35b825160200151611861908290309089906001600160a01b031661392b565b8251602001516001600160a01b031690813b1561039957604051632770a7eb60e21b81523060048201526024810191909152919081908390604490829084905af1801561038e57156117f957906118bc5f9282979497612b37565b80031261038a57925f806117f9565b8451516118e690829030908b906001600160a01b031661392b565b8451516001600160a01b031690813b156110c857604051632770a7eb60e21b815230600482015260248101919091529084908290604490829084905af1801561038e57156117f3578061193a855f93612b37565b80031261038a575f6117f3565b9150506117ec928051916119616020830193845190612d1d565b9160a061198360608301519461197d6080850196875190612d1d565b90612eb9565b9101908151155f146119ae575050506119a9926119a1915190612d1d565b905190612d30565b6117e1565b906119a16119ce926119c86119a9986119a1975190612d1d565b94612d1d565b90612c62565b86516020015163cd7af51b60e01b5f9081526004929092526001600160a01b0316602452604490fd5b109050855f61179e565b634e487b7160e01b5f52601160045260245ffd5b635dbad7a160e01b81526004839052602490fd5b50346103d357806003193601126103d357602090604051908152f35b503461038a5760c036600319011261038a5760043560a036602319011261038a57604051611a7881612aff565b6024358152602081016044358152611a8e612a47565b60408301908152608435906001600160a01b038216820361038a5760608401918252608084019160a4358352611ac2612f4b565b6001600160a01b0360606020611ad78961314c565b01510151163003611f4b57611aea612fe5565b611af38661314c565b9060a0820192835194885f5260fe60205260405f209560018060a01b03845116158015611f39575b611f2a57875115611f1b57603b1c6001600160601b0316611b3c8588613f5f565b89518015928315611f10575b508215611f05575b5050611ef6578151965160208501805160c0015190989193916001600160a01b039081169116611b808183613fda565b858110611eee575b50803b1561038a57604051636f59f5a760e11b81526001600160a01b03929092166004830152602482018590525f908290604490829084905af1801561038e57611ecb575b5051925190518a93602093611c0c9390916001600160a01b039182169116611bf6838383615afb565b8751606001516001600160a01b03169130615619565b83516060810151604090910151611c319183916001600160a01b039081169116615afb565b602460018060a01b0360408651015116916040519485938492630ea598cb60e41b845260048401525af18015611ec0578890611e8c575b611c7b915060ff845160101c16906134f7565b81518051845187515160409384015184516341976e0960e01b81526001600160a01b039182166004820152959995979381169693949293929188916024918391165afa958615611e81578b908c97611e5d575b50158015611e55575b611e465760405163c1590cd760e01b815295602087600481895afa9687156106fd578c97611e0e575b5090611d186001600160601b0397611d26938b6152d5565b968793603b1c169088613e9e565b905010611dff5790611d3e60ff8a94935116856139ac565b905160c001516001600160a01b031690823b15611dfb576040516340c10f1960e01b81526001600160a01b0392909216600483015260248201529082908290604490829084905af180156107be57611de6575b505015611dd7576001611da79101918254612c62565b905551907f42286d04e4c524c8cc0ee3f3e851a993a5cb29c5b4d2d6b408bbecdc01ec99e48380a3600160975580f35b631f2a200560e01b8552600485fd5b81611df091612b37565b6110d757855f611d91565b8380fd5b63648564d360e01b8952600489fd5b9650906020873d602011611e3e575b81611e2a60209383612b37565b8101031261038a5795519590611d18611d00565b3d9150611e1d565b630ae7ae7760e21b8b5260048bfd5b508515611cd7565b9050611e7991965060403d604011610791576107818183612b37565b95905f611cce565b6040513d8d823e3d90fd5b506020813d602011611eb8575b81611ea660209383612b37565b8101031261038a57611c7b9051611c68565b3d9150611e99565b6040513d8a823e3d90fd5b611c0c929b5092611ee15f602095969396612b37565b5f9b925092939093611bcd565b94505f611b88565b630303022d60e21b5f5260045ffd5b101590505f80611b50565b81111592505f611b48565b631f2a200560e01b5f5260045ffd5b63d92e233d60e01b5f5260045ffd5b5082516001600160a01b031615611b1b565b85635dbad7a160e01b5f5260045260245ffd5b3461038a57602036600319011261038a5760043560606020611f7f8361314c565b015101516001600160a01b03163003611fca57805f5260fe602052611fa660405f2061516e565b8015611fb757604051908152602090f35b50630303022d60e21b5f5260045260245ffd5b635dbad7a160e01b5f5260045260245ffd5b3461038a57604036600319011261038a57611ff5612a31565b6004355f52606560205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b3461038a575f36600319011261038a5760fc546040516001600160a01b039091168152602090f35b3461038a57602036600319011261038a576004356001600160a01b03606060206120768461314c565b01510151163003611fca575f5260fe6020526020600160405f200154604051908152f35b3461038a575f36600319011261038a57335f9081527fbfe93621c6aa2dbf737e9056c9b79e4d30ee4f6b28b18be2cb71aac8a7bf258e602052604090205460ff1615612121576120e8612fa1565b600160ff1960c954161760c9557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b610c0a61212d33615366565b610bf26011610b705f516020615e9f5f395f51905f5261544c565b3461038a5761215636612c0e565b6001600160a01b036060602061216b8561314c565b015101511630036121a057906112136112046103076111f160409561218f8661314c565b955f5260fe60205285875f20613e9e565b50635dbad7a160e01b5f5260045260245ffd5b3461038a576121c136612b9d565b906121ca612f4b565b6001600160a01b03606060206121df8461314c565b01510151163003611fca576121f2613037565b60018251151514806122a0575b8061228b575b612279578061224e6122175f9361314c565b82845260fe6020526040842061222d8483613a85565b60fd5460fc5491976001600160a01b03928316949290911692889287613c1a565b7fffad48306557376fc515a68c2431cd2699d06bfa2151ac89cdedf0a55d41aba88280a46001609755005b63d92e233d60e01b5f5260045260245ffd5b5060408201516001600160a01b031615612205565b5060208201516001600160a01b0316156121ff565b3461038a57602036600319011261038a576004355f60c06040516122d881612ab3565b6040516122e481612ae3565b83815283602082015283604082015283606082015281528260208201528260408201528260608201528260808201528260a0820152015260018060a01b036060602061232f8461314c565b01510151163003611fca575f5260fe60205261014060405f2060c06040519161235783612ab3565b61236081612b59565b9283815260018201548060208301526002830154806040840152600384015491826060850152600485015493846080820152600660ff6005880154161515968760a08401520154968791015260c06040516123ba81612ab3565b8881526020810192835260408101938452606081019485526080810195865260a081019687520195865261242660405180986001600160601b036060809264ffffffffff815116855262ffffff6020820151166020860152826040820151166040860152015116910152565b5160808701525160a08601525160c08501525160e084015251151561010083015251610120820152f35b3461038a57602036600319011261038a576004356001600160a01b03606060206124798461314c565b01510151163003611fca5761248d8161314c565b602081015151905160409081015181516341976e0960e01b81526001600160a01b0391821660048201529283916024918391165afa90811561038e575f905f926124f6575b50156124e357602090604051908152f35b5063cd97203f60e01b5f5260045260245ffd5b9050612511915060403d604011610791576107818183612b37565b90836124d2565b3461038a575f36600319011261038a5760206040515f516020615e3f5f395f51905f528152f35b3461038a575f36600319011261038a57602060ff60c954166040519015158152f35b3461038a57602036600319011261038a57602061257f600435612c8e565b6040519015158152f35b3461038a57602036600319011261038a576004355f5260fe60205261014060405f206125b481612b59565b9060018101549060028101546003820154600483015491600660ff6005860154169401549461261b60405180986001600160601b036060809264ffffffffff815116855262ffffff6020820151166020860152826040820151166040860152015116910152565b608087015260a086015260c085015260e08401521515610100830152610120820152f35b3461038a575f36600319011261038a57612657612fe5565b60c95460ff8116156126965760ff191660c9557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b60405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606490fd5b3461038a57604036600319011261038a576126eb612a31565b50633f84111960e21b5f5260045ffd5b3461038a575f36600319011261038a5760206040515f516020615e5f5f395f51905f528152f35b3461038a57604036600319011261038a5760043561273e612a31565b90612758610c45825f526065602052600160405f20015490565b805f52606560205260405f2060018060a01b0383165f5260205260ff60405f2054161561278157005b5f8181526065602090815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291905f516020615e1f5f395f51905f529080a4005b3461038a576127d636612a89565b90916127e0612f4b565b6127e8612fa1565b6127f0613096565b6001600160a01b03606060206128058461314c565b01510151163003611fca5761281981612c8e565b6103af57805f5260fe60205260405f206128328261314c565b936128416102756111fe612c40565b926001830190612852858354612c62565b60028501541061039d5750926128e7836128a86128ed9460209761288361287c8c6128f89a61353a565b80956138a5565b61288e868254612c62565b9055895160400151309033906001600160a01b031661392b565b61197d6128d66128cb6128c089850196875190612d1d565b60a085015190612d1d565b948351905190612d1d565b916080606082015191015190612d1d565b90612d30565b610307610301612c6f565b925101516001600160a01b0316803b1561038a576040516340c10f1960e01b81526001600160a01b03929092166004830152602482018390525f908290604490829084905af1801561038e57612959575b6020826001609755604051908152f35b806129655f8093612b37565b80031261038a5781612949565b3461038a57602036600319011261038a5760206108946004355f526065602052600160405f20015490565b3461038a575f36600319011261038a5760206040515f516020615e7f5f395f51905f528152f35b3461038a57602036600319011261038a576004359063ffffffff60e01b821680920361038a57602091638844e8d160e01b8114908115612a06575b5015158152f35b637965db0b60e01b811491508115612a20575b50836129ff565b6301ffc9a760e01b14905083612a19565b602435906001600160a01b038216820361038a57565b606435906001600160a01b038216820361038a57565b600435906001600160a01b038216820361038a57565b604435906001600160a01b038216820361038a57565b606090600319011261038a5760043590602435906044356001600160a01b038116810361038a5790565b60e0810190811067ffffffffffffffff821117612acf57604052565b634e487b7160e01b5f52604160045260245ffd5b6080810190811067ffffffffffffffff821117612acf57604052565b60a0810190811067ffffffffffffffff821117612acf57604052565b60c0810190811067ffffffffffffffff821117612acf57604052565b90601f8019910116810190811067ffffffffffffffff821117612acf57604052565b90604051612b6681612ae3565b606081935464ffffffffff8116835262ffffff8160281c1660208401526001600160601b038160401c16604084015260a01c910152565b9060a060031983011261038a57608060043592602319011261038a57604051612bc581612ae3565b602435801515810361038a5781526044356001600160a01b038116810361038a5760208201526064356001600160a01b038116810361038a576040820152608435606082015290565b604090600319011261038a576004359060243590565b67ffffffffffffffff8111612acf57601f01601f191660200190565b60405190612c4f604083612b37565b60048252636261736560e01b6020830152565b91908201809211611a0757565b60405190612c7e604083612b37565b60018252600f60fb1b6020830152565b6001600160a01b0360606020612ca38461314c565b01510151163003611fca57612cce81612cbd60c09361314c565b905f5260fe60205260405f2061353a565b01511590565b5190811515820361038a57565b919082604091031261038a576020612cf883612cd4565b92015190565b60405190612d0d604083612b37565b60018252606160f81b6020830152565b81810292918115918404141715611a0757565b8115612d3a570490565b634e487b7160e01b5f52601260045260245ffd5b805f5260ff60205260405f2054620151808101809111611a07574210612e89576001825115151480612e74575b80612e5f575b61227957612d8e81612e8d565b918215611f1b577f62a88264473dbaca9528a17ab39375790b482893fe5d1eae766e6f43114ed3048291612dc18361314c565b835f5260fe602052612e2060405f2091855f5260ff6020524260405f205560018060a01b0360fd54169360018060a01b0360fc541691612e02868b83614c7e565b50809589612e1a60ff60a086015160101c16846134f7565b93614d49565b604080519182526001600160a01b03929092166020820152a27f1c010aedf7d0edeba419efbe7616b2c889056e31cf4454693eb683d0dc4edecd5f80a3565b5060408201516001600160a01b031615612d81565b5060208201516001600160a01b031615612d7b565b5050565b6001600160a01b0360606020612ea28461314c565b01510151163003611fca57612eb690612ec6565b90565b91908203918211611a0757565b612ecf8161314c565b905f5260fe602052600160405f2001549060648210612f4557805160400151612f1d90612f069030906001600160a01b0316613fda565b612f17612f11612c40565b846133a4565b906134f7565b91808311612f2c575050505f90565b612f3c61030791612eb694612eb9565b9161120d612c40565b50505f90565b600260975414612f5c576002609755565b60405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606490fd5b60ff60c95416612fad57565b60405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606490fd5b335f9081527fffdfc1249c027f9191656349feb0761381bb32c9f557e01f419fd08754bf5a1b602052604090205460ff161561301d57565b610c0a61302933615366565b610bf26011610b705f61544c565b335f9081527fea6b36b9f5cb12f73bb1a2064b058edf7e385c60e5d5069a9ac68ba5930d55bd602052604090205460ff161561306f57565b610c0a61307b33615366565b610bf26011610b705f516020615e3f5f395f51905f5261544c565b335f9081527f3d6d979b4bf289e901af1c0967a6ac71ee985fc0ceabfde37691fc047613e6bf602052604090205460ff16156130ce57565b610c0a6130da33615366565b610bf26011610b705f516020615e7f5f395f51905f5261544c565b5f81815260656020908152604080832033845290915290205460ff16156131195750565b610c0a90610bf26011610b7061312e33615366565b9361544c565b67ffffffffffffffff8111612acf5760051b60200190565b905f60a060405161315c81612b1b565b60405161316881612aff565b838152836020820152836040820152836060820152836080820152815260405161319181612ab3565b83815283602082015283604082015283606082015283608082015283838201528360c082015260208201528260408201526060808201528260808201520152815f5260fb60205260405f209160ff6011840154161561337157506040516131f781612b1b565b60405161320381612aff565b83546001600160a01b03908116825260018501548116602083015260028501548116604080840191909152600386015482166060840152600486015490911660808301529082525161325481612ab3565b60058401546001600160a01b0390811682526006850154811660208084019190915260078601548216604080850191909152600887015483166060850152600987015483166080850152600a870154831660a0850152600b87015490921660c0840152830191909152600c84015490820152600d830180549093906132d881613134565b906132e66040519283612b37565b80825260208201955f5260205f20955f905b828210613327575050506060830152600e8101546001600160a01b03166080830152600f015460a08201529150565b6003602060019260405161333a81612ae3565b60ff8c54868060a01b038116835260a01c1683820152848c0154604082015260028c015460608201528152019801910190966132f8565b6337e1342d60e21b5f5260045260245ffd5b5f5b8381106133945750505f910152565b8181015183820152602001613385565b9060405190602082018151926133d6602082818601966133c581878a613383565b81010301601f198101835282612b37565b5190206040516020810190636261736560e01b8252600481526133fa602482612b37565b5190200361341157505060a0015160101c60ff1690565b604051602081019061342c60208285516133c581878a613383565b5190206040516020810190606160f81b82526001815261344d602182612b37565b5190200361346157505060a0015160ff1690565b61347d602060405180936133c583830196879251928391613383565b5190206040516020810190600f60fb1b82526001815261349e602182612b37565b519020036134b35760a0015160081c60ff1690565b63a1e9dd9d60e01b5f5260045ffd5b60ff6011199116019060ff8211611a0757565b60ff166012039060ff8211611a0757565b60ff16604d8111611a0757600a0a90565b60ff82166012811461353457601211156135255761351f61351a612eb6936134d5565b6134e6565b90612d1d565b6128e761351a612eb6936134c2565b50905090565b9190604051610100810181811067ffffffffffffffff821117612acf576040525f815260208101915f835260408201925f845260608301905f825260808401935f855260a08101935f855260c08201965f885260e08301905f8252839a60a0840151916135bb60ff8460101c16600160ff8087169660081c169401546134f7565b8652602085015151855160409081015181516341976e0960e01b81526001600160a01b039182166004820152939284916024918391165afa91821561038e575f905f93613881575b50158015613879575b61386a5781885252845161363357505050505050505090670de0b6b3a7640000809252525b565b8351516040516318160ddd60e01b81529899979890602090829060049082906001600160a01b03165afa801561038e575f90613837575b85516020908101516040516318160ddd60e01b81529350839060049082906001600160a01b03165afa91821561038e575f92613801575b506136b6936136af916134f7565b89526134f7565b8752815151604051639faa3c9160e01b815290602090829060049082906001600160a01b03165afa90811561038e575f916137c7575b501580159091526137b657515160405163c1590cd760e01b815290602090829060049082906001600160a01b03165afa90811561038e575f91613784575b5083525b8451613746575050505050670de0b6b3a76400009052565b61376292916137589151905190612d1d565b9251905190612d1d565b9081811061377c5761377892916119a191612eb9565b9052565b5050505f9052565b90506020813d6020116137ae575b8161379f60209383612b37565b8101031261038a57515f61372a565b3d9150613792565b50670de0b6b3a7640000835261372e565b90506020813d6020116137f9575b816137e260209383612b37565b8101031261038a576137f390612cd4565b5f6136ec565b3d91506137d5565b9091506020813d60201161382f575b8161381d60209383612b37565b8101031261038a5751906136b66136a1565b3d9150613810565b506020813d602011613862575b8161385160209383612b37565b8101031261038a576004905161366a565b3d9150613844565b630ae7ae7760e21b5f5260045ffd5b50811561360c565b905061389d91925060403d604011610791576107818183612b37565b91905f613603565b6020906138d27f5f7c2fa4633ef1ba390069935f57e39241415a5fac1e69c762c72c789bed489d93614b83565b906138dc8161516e565b815467ffffff00000000001660a09190911b6001600160a01b03191617604083811b73ffffffffffffffffffffffff000000000000000016919091174264ffffffffff161790915551908152a1565b9192916001600160a01b0316908161394c57631954782960e01b5f5260045ffd5b6001600160a01b03169133830361399d5761363193604051936323b872dd60e01b6020860152602485015260018060a01b03166044840152606483015260648252613998608483612b37565b6154ee565b63f8fd233360e01b5f5260045ffd5b60ff82166012811461353457601211156139cf576128e761351a612eb6936134d5565b61351f61351a612eb6936134c2565b6001600160a01b0381165f9081527f55b7d6438a27f557ce2e68ce9e0414fa62195bc72edfca0c05472cd322380f72602052604090205460ff1615613a205750565b6001600160a01b03165f8181527f55b7d6438a27f557ce2e68ce9e0414fa62195bc72edfca0c05472cd322380f7260205260408120805460ff191660011790553391905f516020615e5f5f395f51905f52905f516020615e1f5f395f51905f529080a4565b90915f91602060018060a01b039151015116926040516370a0823160e01b8152306004820152602081602481885afa90811561038e575f91613be8575b50843b1561038a5760405163643cb2b960e11b81525f81600481838a5af19081613bd3575b50613b24575050503d80916040519363643cb2b960e11b8552600485015260406024850152816044850152606484013e601f801991011660640190fd5b60206024929395604051938480926370a0823160e01b82523060048301525afa80156110bd578490613b9f575b613b5b9250612eb9565b918215613b9057507f381ff38e2fec0d64b5d6f95156decdb3e229ef47c184126bbb5511a7bf32cf106020604051848152a290565b631f2a200560e01b8152600490fd5b506020823d602011613bcb575b81613bb960209383612b37565b8101031261038a57613b5b9151613b51565b3d9150613bac565b613be09195505f90612b37565b5f935f613ae7565b90506020813d602011613c12575b81613c0360209383612b37565b8101031261038a57515f613ac2565b3d9150613bf6565b9491929596939096602088510151965f9760018060a01b031698600460208b6040519283809263a111723160e01b82525afa90811561038e575f91613e63575b506006811015613e4f5760018114613e295760028114908115613e1e575b50613c9157637aa460c960e11b89526004889052602489fd5b899796973b1561038a57604051632770a7eb60e21b8152306004820152602481018590525f81604481838f5af19081613e09575b50613d015789893d809160405193632770a7eb60e21b8552600485015260406024850152816044850152606484013e601f801991011660640190fd5b9193959760206024929496989a6040519384809263124ca52960e01b82528a60048301525afa918215610798579089918193613da9575b5097839291612e1a613d7f8a60ff7f51392bf9d32fbeaa79ec8834e63548707bbaa882d9ce800f31db15cb4fd062689d60a0613d879c9b9a0151905060101c169587614c7e565b5093846134f7565b604080519182526001600160a01b03909216602082015290819081015b0390a2565b959493925090506020853d602011613e01575b81613dc960209383612b37565b8101031261038a57935192939192909188907f51392bf9d32fbeaa79ec8834e63548707bbaa882d9ce800f31db15cb4fd06268613d38565b3d9150613dbc565b613e16919a505f90612b37565b5f985f613cc5565b60039150145f613c78565b505160200151959850613631975091955091936001600160a01b03169250614af3915050565b634e487b7160e01b5f52602160045260245ffd5b90506020813d602011613e96575b81613e7e60209383612b37565b8101031261038a5751600681101561038a575f613c5a565b3d9150613e71565b90613ea89161353a565b905f915f918151613ebf6020840191825190612d1d565b670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a0757613efe6080613ef3606087015186612d1d565b950194855190612d1d565b92838211613f10575b50505050509091565b93955091935091670de0b6b3a763ffff198101908111611a0757613f4e613f4882613f41613f55976128e796612eb9565b9551612d1d565b84612d30565b9451612d1d565b5f80808080613f07565b90613f699161353a565b805115613fcd57606081018051158015613fc1575b613fac57613fa6826080613f9b612eb69551602084015190612d1d565b935191015190612d1d565b906151f9565b50506ec097ce7bc90715b34b9f100000000090565b50608082015115613f7e565b50670de0b6b3a764000090565b6001600160a01b031680613fed57503190565b6040516370a0823160e01b81526001600160a01b039092166004830152602090829060249082905afa90811561038e575f91614027575090565b90506020813d60201161404e575b8161404260209383612b37565b8101031261038a575190565b3d9150614035565b919290859695949161406882876134f7565b9361407c836140778389613fda565b6134f7565b8581106140dc575b5050505092847f57019a8e75e12d459999803f3a22046f4ada495918e1b915de1f2fefe62fac2395936140c9936140c2600160209801918254612eb9565b9055614af3565b6040519384526001600160a01b031692a2565b856140ed9293949596979850612eb9565b9182156142195760405163abae70c560e01b81526004810184905290602090829060249082905f906001600160a01b03165af190811561038e575f916141df575b50156141d05760068401918254918183106141c15761415d93614155614077938795612eb9565b905587613fda565b90818411614172575b80808896959493614084565b6001965085935094602094826140c26141b17f57019a8e75e12d459999803f3a22046f4ada495918e1b915de1f2fefe62fac23996140c99796936139ac565b9950509496509450819250614166565b6302100b1160e21b5f5260045ffd5b637286ef7960e11b5f5260045ffd5b90506020813d602011614211575b816141fa60209383612b37565b8101031261038a5761420b90612cd4565b5f61412e565b3d91506141ed565b505050505050505050565b1561422b57565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b9061428e9161353a565b908151916142a26020820193845190612d1d565b670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a07576142d1606083015184612d1d565b90670de0b6b3a7640000820291808304670de0b6b3a76400001490151715611a07578082111561433b5761430491612eb9565b90670de0b6b3a763ffff198301928311611a075761433892614330613f4860806128e794015183612d1d565b945190612d1d565b91565b50505050505f5f9091565b6001600160a01b03168015614aad57815f5260fb60205260245f604081209260405192838092635ab3ea5d60e11b82528760048301525afa90811561038e575f91614877575b508051516001600160a01b0316156146ab5760608101805151801561486457600d84019182545f845580614825575b505f5b82811061477a575050825180519092506001600160a01b03161590508015614765575b8015614750575b801561473b575b61461457805160208201516001600160a01b03918216911681811492918315614724575b831561470d575b5082156146f6575b82156146df575b5081156146be575b506146ab5760208101805180516001600160a01b031615908115614695575b811561467f575b8115614669575b8115614653575b811561463d575b8115614627575b50614614578151805184546001600160a01b03199081166001600160a01b039283161786556020808401516001808901805485169286169290921790915560408086015160028a018054861691871691909117905560608087015160038b018054871691881691909117905560809687015160048b01805487169188169190911790559651805160058b01805487169188169190911790559283015160068a01805486169187169190911790558281015160078a018054861691871691909117905595820151600889018054851691861691909117905581850151600989018054851691861691909117905560a082810151600a8a018054861691871691909117905560c090920151600b89018054851691861691909117905594860151600c880155850151600f8701559190930151600e85018054909216931692909217909155436010830155601191909101805460ff19169091179055807f67795b7df97de6699e0f17226d6111be2ddc0ebe76fb110c2e8ab6df9312579f5f80a26001600160a01b03606060206146068461314c565b01510151163003611fca5750565b83635dbad7a160e01b5f5260045260245ffd5b60c001516001600160a01b03161590505f614473565b60a08101516001600160a01b031615915061446c565b60808101516001600160a01b0316159150614465565b60608101516001600160a01b031615915061445e565b60408101516001600160a01b0316159150614457565b60208101516001600160a01b0316159150614450565b82635dbad7a160e01b5f5260045260245ffd5b60408101516060909101516001600160a01b0390811691161490505f614431565b60608201516001600160a01b03161491505f614429565b60408201516001600160a01b031681149250614422565b60608301516001600160a01b03161492505f61441a565b60408301516001600160a01b031681149350614413565b5060608101516001600160a01b0316156143ef565b5060408101516001600160a01b0316156143e8565b5060208101516001600160a01b0316156143e1565b614785818351615605565b519084549168010000000000000000831015612acf5760018301808755831015614811575f86815260209081902082516003909502018054918301516001600160a81b03199092166001600160a01b03959095169490941760a09190911b60ff60a01b1617835560408101516001848101919091556060919091015160029390930192909255016143be565b634e487b7160e01b5f52603260045260245ffd5b80600302906003820403611a0757835f5260205f20908101905b81811061484c57506143bb565b805f600392555f60018201555f60028201550161483f565b8463f4ac45b160e01b5f5260045260245ffd5b90503d805f833e6148888183612b37565b81019060208183031261038a5780519067ffffffffffffffff821161038a570180820391610200831261038a57604051926148c284612b1b565b60a0811261038a5760e0906040516148d981612aff565b6148e285615bc9565b81526148f060208601615bc9565b602082015261490160408601615bc9565b604082015261491260608601615bc9565b606082015261492360808601615bc9565b60808201528552609f19011261038a5760405161493f81612ab3565b61494b60a08401615bc9565b815261495960c08401615bc9565b602082015261496a60e08401615bc9565b604082015261497c6101008401615bc9565b606082015261498e6101208401615bc9565b60808201526149a06101408401615bc9565b60a08201526149b26101608401615bc9565b60c0820152602084015261018082015160408401526101a082015167ffffffffffffffff811161038a57820181601f8201121561038a578051906149f582613134565b92614a036040519485612b37565b82845260208085019360071b8301019181831161038a57602001925b828410614a52575050505060608301526101e090614a406101c08201615bc9565b6080840152015160a08201525f61438c565b60808483031261038a5760405190614a6982612ae3565b614a7285615bc9565b825260208501519060ff8216820361038a57826020928360809501526040870151604082015260608701516060820152815201930192614a1f565b506324df413360e21b5f5260045260245ffd5b817fb13143af250a090d8b08b199f27b7bb426e38b9f377b101ea3205d5ca83f07559260026020930155604051908152a1565b9091906001600160a01b031680614b1357630c5d6fad60e21b5f5260045ffd5b60405163a9059cbb60e01b60208201526001600160a01b0390931660248401526044830191909152613631919061399882606481015b03601f198101845283612b37565b60409160208252614b778151809281602086015260208686019101613383565b601f01601f1916010190565b60e0810151613fcd578051158015614c72575b8015614c66575b614c6157614bb46060820151608083015190612d1d565b670de0b6b3a7640000810290808204670de0b6b3a76400001490151715611a07576128e7826040614be9945191015190612d1d565b670de0b6b3a76400008110614c06575068056bc75e2d6310000090565b80670de0b6b3a76400000390670de0b6b3a76400008211611a0757670de0b6b3a764000014612d3a576ec097ce7bc90715b34b9f1000000000049068056bc75e2d631000008211614c5357565b68056bc75e2d631000009150565b505f90565b50604081015115614b9d565b50602081015115614b96565b60208181015160c0015160405163e16777c160e01b8152959493915f91879060049082906001600160a01b03165afa95861561038e575f96614d15575b508515614d0c5750612710614cd3614cdd9683612d1d565b0494858092612eb9565b9281614ceb575b5050509190565b915160400151614d0492906001600160a01b0316614af3565b5f8381614ce4565b94509150509190565b9095506020813d602011614d41575b81614d3160209383612b37565b8101031261038a5751945f614cbb565b3d9150614d24565b8051805160408089018051602086018051519584015184516341976e0960e01b81526001600160a01b039182166004820152989d939c9281169b5f9b989a9299939897909692959282169493929183916024918391165afa90811561038e575f905f9261514c575b50158015615144575b61386a5760405163c1590cd760e01b815290602082600481875afa90811561038e575f9161510e575b614dee9250866152d5565b604051631a3acfc360e31b8152600481018e90529091602090829060249082906001600160a01b03165afa801561038e5782915f916150c2575b506001600160601b03614e3d91168a86613e9e565b9050105f14614f96575050835115614f825791602091614e636001899501918254612eb9565b9055602460018060a01b0360408851015116916040519485938492636f074d1f60e11b845260048401525af1948515614f765794614f38575b5091614f0e8492614ef587957fe91e44a5e14583bb47bf0c9cd41988f95e0d3fd88b342c44ae58bc38f27e2912999760809960018060a01b0360208401511692606060018060a01b03818a510151169101519330615619565b905160c00151909485916001600160a01b031690614af3565b51604090810151935181516001600160a01b039586168152941660208501528301526060820152a2565b9593509093916020863d602011614f6e575b81614f5760209383612b37565b8101031261038a5794519294919390614f0e614e9c565b3d9150614f4a565b604051903d90823e3d90fd5b637e61a6cb60e11b875260048a9052602487fd5b959850985060ff935060a0925090614fb76001614fc2979301918254612c62565b9055015116906139ac565b9260018060a01b0360c0845101511690803b1561038a576040516340c10f1960e01b81526001600160a01b03929092166004830152602482018590525f908290604490829084905af1801561038e576150af575b50815160c001516001600160a01b0316803b1561083b57818091600460405180948193630712235560e31b83525af180156107be5761509a575b50505160c00151604080519283526001600160a01b0390911660208301527f5fb9b8afcb71da1bf9b20ce82cf328dcf7636eceebe61b8bacd2165a64556a5d919081908101613da4565b6150a5828092612b37565b6103d35780615050565b6150bb91505f90612b37565b5f5f615016565b9150506020813d602011615106575b816150de60209383612b37565b8101031261038a57516001600160601b038116810361038a5781906001600160601b03614e28565b3d91506150d1565b90506020823d60201161513c575b8161512960209383612b37565b8101031261038a57614dee915190614de3565b3d915061511c565b508015614dba565b9050615167915060403d604011610791576107818183612b37565b905f614db1565b5464ffffffffff8116428110156151f25761519e90670de0b6b3a764000062ffffff8460281c1691420302612d30565b90680238fd42c5cf0400008211156151c1576001600160601b03915060401c1690565b6151d5670de0b6b3a7640000925f03615757565b906001600160601b03828260a01c029284039160401c1602010490565b5060a01c90565b90670de0b6b3a76400008202905f19670de0b6b3a7640000840992828085109403938085039485841115615290571461528957670de0b6b3a764000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b60405162461bcd60e51b815260206004820152601f60248201527f46756c6c4d6174683a2064656e6f6d696e61746f7220746f6f20736d616c6c006044820152606490fd5b91818302915f1981850993838086109503948086039586851115615290571461534d579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b908151811015614811570160200190565b615370602a612c24565b9061537e6040519283612b37565b602a825261538c602a612c24565b6020830190601f19013682378251156148115760309053815160011015614811576078602183015360295b6001811161540b57506153c75790565b606460405162461bcd60e51b815260206004820152602060248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152fd5b90600f81166010811015614811576f181899199a1a9b1b9c1cb0b131b232b360811b901a6154398385615355565b5360041c908015611a07575f19016153b7565b6154566042612c24565b906154646040519283612b37565b604282526154726042612c24565b6020830190601f19013682378251156148115760309053815160011015614811576078602183015360415b600181116154ad57506153c75790565b90600f81166010811015614811576f181899199a1a9b1b9c1cb0b131b232b360811b901a6154db8385615355565b5360041c908015611a07575f190161549d565b9061556d9160018060a01b03165f806040519361550c604086612b37565b602085527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564602086015260208151910182855af13d156155fd573d9161555183612c24565b9261555f6040519485612b37565b83523d5f602085013e615d8d565b80519081159182156155db575b50501561558357565b60405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608490fd5b819250906020918101031261038a5760206155f69101612cd4565b5f8061557a565b606091615d8d565b80518210156148115760209160051b010190565b93919293601e420190814211611a0757604051615637606082612b37565b6002815260208101956040368837815115614811576001600160a01b03169586905280516001101561481157878561569b95604084019960018060a01b0316809a5261568481868b615bdd565b8281106156e4575b506001600160a01b0316615c35565b9384106156d55760407fdd36740e2a012d93061a0d99eaa9107860955de4e90027d3cf465a055026c407918151908152856020820152a390565b6374f79b2960e01b5f5260045ffd5b6156f16156f89184612eb9565b828b615afb565b5f61568c565b1561570557565b60405162461bcd60e51b815260206004820152601060248201526f1253959053125117d1561413d391539560821b6044820152606490fd5b8015612d3a576ec097ce7bc90715b34b9f10000000000590565b680238fd42c5cf03ffff1981121580615ae8575b615774906156fe565b5f8112615ad457612eb6906806f05b59d3b20000008112615a93576806f05b59d3b1ffffff19016159366064770195e54c5dd42177f53a27172fa9ec630262827000000000925b0268056bc75e2d631000009068ad78ebc5ac62000000811215615a70575b6856bc75e2d631000000811215615a42575b682b5e3af16b18800000811215615a16575b6815af1d78b58c4000008112156159ea575b680ad78ebc5ac62000008112156159bf575b68056bc75e2d63100000811215615994575b6802b5e3af16b1880000811215615969575b68015af1d78b58c4000081121561593e575b600268056bc75e2d631000008280020505600368056bc75e2d631000008383020505600468056bc75e2d631000008483020505600568056bc75e2d631000008583020505600668056bc75e2d631000008683020505600768056bc75e2d63100000878302050590600868056bc75e2d63100000888402050592600968056bc75e2d6310000089860205059468056bc75e2d63100000600a8a88028290050597600b68056bc75e2d631000008c8b02050599600c68056bc75e2d631000008d8d0205059b0101010101010101010101010268056bc75e2d63100000900590565b026064900590565b68015af1d78b58c3ffff19019068056bc75e2d631000006806f5f17757889379379091020590615857565b6802b5e3af16b187ffff19019068056bc75e2d631000006808f00f760a4b2db55d9091020590615845565b68056bc75e2d630fffff19019068056bc75e2d63100000680ebc5fb417461211109091020590615833565b680ad78ebc5ac61fffff19019068056bc75e2d6310000068280e60114edb805d039091020590615821565b6815af1d78b58c3fffff19019068056bc75e2d63100000690127fa27722cc06cc5e2909102059061580f565b682b5e3af16b187fffff19019068056bc75e2d63100000693f1fce3da636ea5cf85090910205906157fd565b6856bc75e2d630ffffff19019068056bc75e2d631000006b02df0ab5a80a22c61ab5a70090910205906157eb565b6e01855144814a7ff805980ff0084000915068ad78ebc5ac61ffffff19016157d9565b6803782dace9d90000008112615ac7576803782dace9d8ffffff190161593660646b1425982cf597cd205cef7380926157bb565b61593660646001926157bb565b615adf905f03615757565b612eb69061573d565b5068070c1cc73b00c8000081131561576b565b6001600160a01b03168015615bba57604051636eb1769f60e11b81523060048201526001600160a01b038316602482015292602084604481855afa93841561038e575f94615b84575b50615b556139989161363195612c62565b60405163095ea7b360e01b60208201526001600160a01b03909416602485015260448401528260648101614b49565b93506020843d602011615bb2575b81615b9f60209383612b37565b8101031261038a57925192615b55615b44565b3d9150615b92565b63220abce160e01b5f5260045ffd5b51906001600160a01b038216820361038a57565b6001600160a01b03169182615bf3575050505f90565b604051636eb1769f60e11b81526001600160a01b0392831660048201529116602482015290602090829060449082905afa90811561038e575f91614027575090565b939490949291926040519586946338ed173960e01b865260a48601916004870152602486015260a060448601528351809152602060c486019401905f5b818110615d6b575050506001600160a01b03908116606485015260848401919091525f93918390039183918591165af15f9181615cd8575b50615cbe576374f79b2960e01b5f5260045ffd5b80515f198101908111611a0757615cd491615605565b5190565b9091503d805f833e615cea8183612b37565b81019060208183031261038a5780519067ffffffffffffffff821161038a57019080601f8301121561038a578151615d2181613134565b92615d2f6040519485612b37565b81845260208085019260051b82010192831161038a57602001905b828210615d5b57505050905f615caa565b8151815260209182019101615d4a565b82516001600160a01b0316865288965060209586019590920191600101615c72565b91929015615def5750815115615da1575090565b3b15615daa5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b825190915015615e025750805190602001fd5b60405162461bcd60e51b8152908190610c0a9060048301614b5756fe2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d3fc733b4d20d27a28452ddf0e9351aced28242fe03389a653cdb783955316b9b767b56a6f9d29ab1315e16c17b56dfe5edc8988075500f6ef388c6dc4b0e045dba279271fb7bbf76a6f3df3cc57bf80647fcafdea60ec3383d90f459de74e7c065d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862aa2646970667358221220d8543d70c908e965a6bf0382ef55d6d8d8ac7f10c6f9f7854f90d6897ac8a76364736f6c634300081c0033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 31 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
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.