Verified contractExactBUSL-1.1
Rebalancing
Address0xbb44fe36a4f3de483ce237726478899eda7da239
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.17
- Same code
Only this contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 20,768,723
- Creation transaction
- 0xee51fb495e…5d02bfb7aa
32 files
- contracts/rebalance/Rebalancing.solmain15.61 KB
- @chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol599 B
- @chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol215 B
- @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol668 B
- @openzeppelin/contracts-upgradeable-4.9.6/access/OwnableUpgradeable.sol3.17 KB
- @openzeppelin/contracts-upgradeable-4.9.6/interfaces/IERC1967Upgradeable.sol678 B
- @openzeppelin/contracts-upgradeable-4.9.6/interfaces/IERC20Upgradeable.sol162 B
- @openzeppelin/contracts-upgradeable-4.9.6/interfaces/draft-IERC1822Upgradeable.sol890 B
- @openzeppelin/contracts-upgradeable-4.9.6/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol6.8 KB
- @openzeppelin/contracts-upgradeable-4.9.6/proxy/beacon/IBeaconUpgradeable.sol461 B
- @openzeppelin/contracts-upgradeable-4.9.6/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable-4.9.6/proxy/utils/UUPSUpgradeable.sol4.92 KB
- @openzeppelin/contracts-upgradeable-4.9.6/security/ReentrancyGuardUpgradeable.sol3.68 KB
- @openzeppelin/contracts-upgradeable-4.9.6/token/ERC20/IERC20Upgradeable.sol2.75 KB
- @openzeppelin/contracts-upgradeable-4.9.6/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable-4.9.6/utils/ContextUpgradeable.sol1.48 KB
- @openzeppelin/contracts-upgradeable-4.9.6/utils/StorageSlotUpgradeable.sol4.12 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.75 KB
- contracts/FunctionParameters.sol9.48 KB
- contracts/access/AccessRoles.sol1.91 KB
- contracts/access/IAccessController.sol673 B
- contracts/config/assetManagement/IAssetManagementConfig.sol3.57 KB
- contracts/config/protocol/IProtocolConfig.sol7.5 KB
- contracts/core/calculations/TokenBalanceLibrary.sol2.38 KB
- contracts/core/interfaces/IAllowanceTransfer.sol7.25 KB
- contracts/core/interfaces/IEIP712.sol153 B
- contracts/core/interfaces/IPortfolio.sol7.24 KB
- contracts/core/interfaces/ITokenExclusionManager.sol1.24 KB
- contracts/handler/IIntentHandler.sol1.24 KB
- contracts/library/ErrorLibrary.sol8.92 KB
- contracts/oracle/IPriceOracle.sol500 B
- contracts/rebalance/RebalancingConfig.sol5.45 KB
contracts/rebalance/Rebalancing.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable-4.9.6/security/ReentrancyGuardUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable-4.9.6/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable-4.9.6/access/OwnableUpgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable-4.9.6/interfaces/IERC20Upgradeable.sol";
import {ErrorLibrary} from "../library/ErrorLibrary.sol";
import {IIntentHandler} from "../handler/IIntentHandler.sol";
import {RebalancingConfig} from "./RebalancingConfig.sol";
import {FunctionParameters} from "../FunctionParameters.sol";
/**
* @title RebalancingCore
* @dev Manages the rebalancing operations for Portfolio contracts, ensuring asset managers can update token weights and swap tokens as needed.
* Inherits RebalancingConfig for auxiliary functions like checking token balances.
*/
contract Rebalancing is
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable,
RebalancingConfig
{
/// @notice Emitted when weights are successfully updated after a swap operation.
event UpdatedWeights();
event UpdatedTokens(address[] newTokens);
event PortfolioTokenRemoved(
address indexed token,
address indexed vault,
uint256 indexed balance,
uint256 atSnapshotId
);
uint256 public constant TOTAL_WEIGHT = 10_000; // Represents 100% in basis points.
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @notice Initializes the Rebalancing contract.
* @param _portfolio Address of the Portfolio contract.
* @param _accessController Address of the AccessController.
*/
function init(
address _portfolio,
address _accessController
) external initializer {
__Ownable_init();
__ReentrancyGuard_init();
__UUPSUpgradeable_init();
__RebalancingHelper_init(_portfolio, _accessController);
}
/**
* @notice Allows an asset manager to propose new weights for tokens in the portfolio.
* @param _sellTokens Array of tokens to sell.
* @param _sellAmounts Corresponding amounts of each token to sell.
* @param _handler Address of the swap handler.
* @param _callData Encoded swap call data.
*/
function updateWeights(
address[] calldata _sellTokens,
uint256[] calldata _sellAmounts,
address _handler,
bytes memory _callData
) external virtual nonReentrant onlyAssetManager {
// Extra Parameter to define assetManager intent(which token to sell and which to buy) + Check for it
//Check for not selling the whole amount
_updateWeights(
_sellTokens,
_getCurrentTokens(),
_sellAmounts,
_handler,
_callData
);
emit UpdatedWeights();
}
/**
* @dev Internal function to handle the logic of updating weights.
* @param _sellTokens Tokens to be sold.
* @param _newTokens New set of tokens after rebalancing.
* @param _sellAmounts Amounts of each sell token.
* @param _handler The handler to execute swaps.
* @param _callData Swap details.
*/
function _updateWeights(
address[] calldata _sellTokens,
address[] memory _newTokens,
uint256[] calldata _sellAmounts,
address _handler,
bytes memory _callData
) private protocolNotPaused {
if (!protocolConfig.isSolver(_handler)) revert ErrorLibrary.InvalidSolver();
// Pull tokens to be completely removed from portfolio to handler for swapping.
uint256 sellTokenLength = _sellTokens.length;
uint256 sellAmountLength = _sellAmounts.length;
if (sellAmountLength != sellTokenLength) {
revert ErrorLibrary.InvalidLength();
}
for (uint256 i; i < sellTokenLength; i++) {
address sellToken = _sellTokens[i];
if (sellToken == address(0)) revert ErrorLibrary.InvalidAddress();
portfolio.pullFromVault(sellToken, _sellAmounts[i], _handler);
}
// Execute the swap using the handler.
address[] memory ensoBuyTokens = IIntentHandler(_handler)
.multiTokenSwapAndTransfer(_vault, _callData);
// Verify that all specified sell tokens have been completely sold by the handler.
for (uint256 i; i < sellTokenLength; i++) {
uint256 dustValue = (_sellAmounts[i] *
protocolConfig.allowedDustTolerance()) / TOTAL_WEIGHT;
if (_getTokenBalanceOf(_sellTokens[i], _handler) > dustValue)
revert ErrorLibrary.BalanceOfHandlerShouldNotExceedDust();
}
// Ensure that each token bought by the solver is in the portfolio list.
uint256 tokenLength = _newTokens.length;
for (uint256 i; i < tokenLength; i++) {
address token = _newTokens[i];
if (_getTokenBalanceOf(token, _vault) == 0)
revert ErrorLibrary.BalanceOfVaultCannotNotBeZero(token);
tokensMapping[token] = true;
}
// Validate that all tokens bought by the solver are in the list of new tokens.
uint256 ensoBuyTokensLength = ensoBuyTokens.length;
for (uint256 i; i < ensoBuyTokensLength; i++) {
if (!tokensMapping[ensoBuyTokens[i]]) {
revert ErrorLibrary.InvalidBuyTokenList();
}
}
// Reset the tokens mapping for the new tokens.
for (uint256 i; i < tokenLength; i++) {
delete tokensMapping[_newTokens[i]];
}
}
/**
* @notice Updates the token list and adjusts weights based on provided rebalance data.
* @dev This function is called by the asset manager to rebalance the portfolio.
* @param rebalanceData The data required for rebalancing, including tokens to sell, new tokens, sell amounts, handler, and call data.
*/
function updateTokens(
FunctionParameters.RebalanceIntent calldata rebalanceData
) external virtual nonReentrant onlyAssetManager {
address[] calldata _sellTokens = rebalanceData._sellTokens;
address[] calldata _newTokens = rebalanceData._newTokens;
address[] memory _tokens = _getCurrentTokens();
//Need a check here to confirm _newTokens has buyTokens in it
portfolio.updateTokenList(_newTokens);
// Perform token update and weights adjustment based on provided rebalance data.
_updateWeights(
_sellTokens,
_newTokens,
rebalanceData._sellAmounts,
rebalanceData._handler,
rebalanceData._callData
);
// Update the internal mapping to reflect changes in the token list post-rebalance.
uint256 tokenLength = _tokens.length;
for (uint256 i; i < tokenLength; i++) {
tokensMapping[_tokens[i]] = true;
}
uint256 newTokensLength = _newTokens.length;
for (uint256 i; i < newTokensLength; i++) {
tokensMapping[_newTokens[i]] = false;
}
for (uint256 i; i < tokenLength; i++) {
address _portfolioToken = _tokens[i];
if (tokensMapping[_portfolioToken]) {
if (_getTokenBalanceOf(_portfolioToken, _vault) != 0)
revert ErrorLibrary.NonPortfolioTokenBalanceIsNotZero();
}
delete tokensMapping[_portfolioToken];
}
emit UpdatedTokens(_newTokens);
}
/**
* @notice Removes an portfolio token from the portfolio. Can only be called by the asset manager.
* @param _token The address of the token to be removed from the portfolio.
*/
function removePortfolioToken(
address _token
) external onlyAssetManager nonReentrant protocolNotPaused {
if (!_isPortfolioToken(_token)) revert ErrorLibrary.NotPortfolioToken();
// Generate a new token list excluding the token to be removed
address[] memory currentTokens = _getCurrentTokens();
uint256 tokensLength = currentTokens.length;
address[] memory newTokens = new address[](tokensLength - 1);
uint256 j = 0;
for (uint256 i; i < tokensLength; i++) {
address token = currentTokens[i];
if (token != _token) {
newTokens[j++] = token;
}
}
portfolio.updateTokenList(newTokens);
uint256 tokenBalance = IERC20Upgradeable(_token).balanceOf(_vault);
_tokenRemoval(_token, tokenBalance);
}
/**
* @notice Removes a non-portfolio token from the portfolio. Can only be called by the asset manager.
* @param _token The address of the token to be removed.
*/
function removeNonPortfolioToken(
address _token
) external onlyAssetManager protocolNotPaused nonReentrant {
if (_isPortfolioToken(_token)) revert ErrorLibrary.IsPortfolioToken();
uint256 tokenBalance = IERC20Upgradeable(_token).balanceOf(_vault);
_tokenRemoval(_token, tokenBalance);
}
/**
* @notice Removes a portion of a portfolio token from the portfolio. Can only be called by the asset manager.
* @param _token The address of the token to be partially removed from the portfolio.
* @param _percentage The percentage of the token balance to be removed from the portfolio.
* @dev This function allows the asset manager to remove a specified percentage of a token from the portfolio.
* It reverts if the token is not part of the portfolio.
*/
function removePortfolioTokenPartially(
address _token,
uint256 _percentage
) external onlyAssetManager protocolNotPaused nonReentrant {
if (!_isPortfolioToken(_token)) revert ErrorLibrary.NotPortfolioToken();
uint256 tokenBalanceToRemove = _getTokenBalanceForPartialRemoval(
_token,
_percentage
);
_tokenRemoval(_token, tokenBalanceToRemove);
}
/**
* @notice Removes a non-portfolio token partially from the portfolio. Can only be called by the asset manager.
* @param _token The address of the token to be removed.
*/
function removeNonPortfolioTokenPartially(
address _token,
uint256 _percentage
) external onlyAssetManager protocolNotPaused nonReentrant {
if (_isPortfolioToken(_token)) revert ErrorLibrary.IsPortfolioToken();
uint256 tokenBalanceToRemove = _getTokenBalanceForPartialRemoval(
_token,
_percentage
);
_tokenRemoval(_token, tokenBalanceToRemove);
}
function _getTokenBalanceForPartialRemoval(
address _token,
uint256 _percentage
) internal view returns (uint256 tokenBalanceToRemove) {
if (_percentage >= TOTAL_WEIGHT)
revert ErrorLibrary.InvalidTokenRemovalPercentage();
uint256 tokenBalance = IERC20Upgradeable(_token).balanceOf(_vault);
tokenBalanceToRemove = (tokenBalance * _percentage) / TOTAL_WEIGHT;
}
/**
* @dev Handles the removal of a token and transfers its balance out of the vault.
* @param _token The address of the token to be removed.
*/
function _tokenRemoval(address _token, uint256 _tokenBalance) internal {
if (_tokenBalance == 0) revert ErrorLibrary.BalanceOfVaultIsZero();
// Snapshot for record-keeping before removing the token
uint256 currentId = tokenExclusionManager.snapshot();
// Deploy a new token removal vault for the token to remove
address tokenRemovalVault = tokenExclusionManager.deployTokenRemovalVault();
// Transfer the token balance from the vault to the token exclusion manager
portfolio.pullFromVault(_token, _tokenBalance, tokenRemovalVault);
// Record the removal details in the token exclusion manager
tokenExclusionManager.setTokenAndSupplyRecord(
currentId - 1,
_token,
tokenRemovalVault,
portfolio.totalSupply()
);
// Log the token removal event
emit PortfolioTokenRemoved(
_token,
tokenRemovalVault,
_tokenBalance,
currentId - 1
);
}
/**
* @dev This function allows the asset manager to claim reward tokens, which might be accumulated
* from various activities like staking, liquidity provision, or participation in DeFi protocols.
* The function ensures the safety and correctness of the operation by verifying that the
* reward token's balance in the vault increases as a result of the claim. It also checks
* that no other token balances in the vault have been unexpectedly reduced, which could
* indicate an issue such as a bug in the target contract or malicious interference.
*
* Before executing the claim, the function stores the current balances of all tokens in the vault.
* After executing the claim via a call to an external contract, it checks the new balances.
* If the reward token's balance does not increase or if any other token's balance decreases,
* the transaction is reverted to prevent potential losses.
*
* @param _tokenToBeClaimed The address of the reward token that the asset manager aims to claim.
* @param _target The contract address that will process the claim. This contract is expected to
* hold the reward logic and tokens.
* @param _claimCalldata The calldata necessary to execute the claim function on the target contract.
* This includes the method signature and parameters for the claim operation.
*/
function claimRewardTokens(
address _tokenToBeClaimed,
address _target,
bytes memory _claimCalldata
) external onlyAssetManager protocolNotPaused nonReentrant {
if (!protocolConfig.isRewardTargetEnabled(_target))
revert ErrorLibrary.RewardTargetNotEnabled();
// Retrieve the list of all tokens in the portfolio and their balances before the claim operation
address[] memory tokens = portfolio.getTokens();
uint256[] memory tokenBalancesInVaultBefore = getTokenBalancesOf(
tokens,
_vault
);
uint256 rewardTokenBalanceBefore = _getTokenBalanceOf(
_tokenToBeClaimed,
_vault
);
// Execute the claim operation using the provided calldata on the target contract
portfolio.claimRewardTokens(_target, _claimCalldata);
uint256[] memory tokenBalancesInVaultAfter = getTokenBalancesOf(
tokens,
_vault
);
// Fetch the new balance of the reward token in the vault after the claim operation
uint256 rewardTokenBalanceAfter = _getTokenBalanceOf(
_tokenToBeClaimed,
_vault
);
// Ensure the reward token balance has increased, otherwise revert the transaction
if (rewardTokenBalanceAfter <= rewardTokenBalanceBefore)
revert ErrorLibrary.ClaimFailed();
// Check that no other token balances have decreased, ensuring the integrity of the vault's assets
uint256 tokensLength = tokens.length;
for (uint256 i; i < tokensLength; i++) {
if (tokenBalancesInVaultAfter[i] < tokenBalancesInVaultBefore[i])
revert ErrorLibrary.ClaimFailed();
}
}
/**
* @notice Authorizes contract upgrade by the contract owner.
* @param _newImplementation Address of the new contract implementation.
*/
function _authorizeUpgrade(
address _newImplementation
) internal override onlyOwner {
// Intentionally left empty as required by an abstract contract
}
/**
* @notice Modifier to restrict function if protocol is paused.
* Uses the `isProtocolPaused` function to determine the protocol pause status.
* @dev Reverts with a ProtocolIsPaused error if the protocol is paused.
*/
modifier protocolNotPaused() {
if (protocolConfig.isProtocolPaused())
revert ErrorLibrary.ProtocolIsPaused();
_; // Continues function execution if the protocol is not paused
}
}
@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}
@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
@openzeppelin/contracts-upgradeable-4.9.6/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @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;
}
@openzeppelin/contracts-upgradeable-4.9.6/interfaces/IERC1967Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967Upgradeable {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
@openzeppelin/contracts-upgradeable-4.9.6/interfaces/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20Upgradeable.sol";
@openzeppelin/contracts-upgradeable-4.9.6/interfaces/draft-IERC1822Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable-4.9.6/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import {Initializable} from "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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;
}
@openzeppelin/contracts-upgradeable-4.9.6/proxy/beacon/IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts-upgradeable-4.9.6/proxy/utils/Initializable.sol
// 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;
}
}
@openzeppelin/contracts-upgradeable-4.9.6/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeTo(address newImplementation) public virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) 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[50] private __gap;
}
@openzeppelin/contracts-upgradeable-4.9.6/security/ReentrancyGuardUpgradeable.sol
// 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;
}
@openzeppelin/contracts-upgradeable-4.9.6/token/ERC20/IERC20Upgradeable.sol
// 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);
}
@openzeppelin/contracts-upgradeable-4.9.6/utils/AddressUpgradeable.sol
// 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);
}
}
}
@openzeppelin/contracts-upgradeable-4.9.6/utils/ContextUpgradeable.sol
// 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;
}
@openzeppelin/contracts-upgradeable-4.9.6/utils/StorageSlotUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// 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);
}
contracts/FunctionParameters.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
/**
* @title FunctionParameters
* @notice A library for defining structured data passed across functions in DeFi protocols.
* @dev This library encapsulates various structures used for initializing, configuring, and managing on-chain financial products.
*/
library FunctionParameters {
/**
* @notice Struct for initializing a new PortfolioFactory
* @dev Encapsulates data necessary for deploying an PortfolioFactory and associated components.
* @param _basePortfolioAddress Base Portfolio contract address for cloning
* @param _baseTokenExclusionManagerAddress Base Token Exclusion address for cloning
* @param _baseRebalancingAddress Base Rebalancing module address for cloning
* @param _baseAssetManagementConfigAddress Base AssetManagement Config address for cloning
* @param _feeModuleImplementationAddress Fee Module implementation contract address
* @param _baseTokenRemovalVaultImplementation Token Removal Vault implementation contract address
* @param _baseVelvetGnosisSafeModuleAddress Base Gnosis-Safe module address for cloning
* @param _gnosisSingleton Gnosis Singleton contract address
* @param _gnosisFallbackLibrary Gnosis Fallback Library address
* @param _gnosisMultisendLibrary Gnosis Multisend Library address
* @param _gnosisSafeProxyFactory Gnosis Safe Proxy Factory address
* @param _protocolConfig Protocol configuration contract address
* @param _velvetProtocolFee Protocol fee percentage (in basis points)
*/
struct PortfolioFactoryInitData {
address _basePortfolioAddress;
address _baseTokenExclusionManagerAddress;
address _baseRebalancingAddres;
address _baseAssetManagementConfigAddress;
address _feeModuleImplementationAddress;
address _baseTokenRemovalVaultImplementation;
address _baseVelvetGnosisSafeModuleAddress;
address _gnosisSingleton;
address _gnosisFallbackLibrary;
address _gnosisMultisendLibrary;
address _gnosisSafeProxyFactory;
address _protocolConfig;
}
/**
* @notice Data for initializing the Portfolio module
* @dev Used when setting up a new Portfolio instance.
* @param _name Name of the Portfolio Fund
* @param _symbol Symbol of the Portfolio Fund
* @param _vault Vault address associated with the Portfolio Fund
* @param _module Safe module address associated with the Portfolio Fund
* @param _accessController Access Controller address for managing roles
* @param _protocolConfig Protocol configuration contract address
* @param _assetManagementConfig Asset Management configuration contract address
* @param _feeModule Fee Module contract address
*/
struct PortfolioInitData {
string _name;
string _symbol;
address _vault;
address _module;
address _tokenExclusionManager;
address _accessController;
address _protocolConfig;
address _assetManagementConfig;
address _feeModule;
}
/**
* @notice Data for initializing a new Portfolio Fund via the Factory
* @dev Encapsulates settings and configurations for a newly created Portfolio Fund.
* @param _assetManagerTreasury Treasury address for asset manager fee accumulation
* @param _whitelistedTokens Array of token addresses permitted in the Portfolio Fund
* @param _managementFee Management fee (annual, in basis points)
* @param _performanceFee Performance fee (upon profit, in basis points)
* @param _entryFee Fee for entering the fund (in basis points)
* @param _exitFee Fee for exiting the fund (in basis points)
* @param _initialPortfolioAmount Initial amount of the portfolio token
* @param _minPortfolioTokenHoldingAmount Minimum amount of portfolio tokens that can be held and can be minted
* @param _public Indicates if the fund is open to the public
* @param _transferable Indicates if the fund's tokens are transferable
* @param _transferableToPublic Indicates if the fund's tokens are transferable to the public
* @param _whitelistTokens Indicates if only whitelisted tokens can be included in the fund
* @param _name Name of the Portfolio Fund
* @param _symbol Symbol of the Portfolio Fund
*/
struct PortfolioCreationInitData {
address _assetManagerTreasury;
address[] _whitelistedTokens;
uint256 _managementFee;
uint256 _performanceFee;
uint256 _entryFee;
uint256 _exitFee;
uint256 _initialPortfolioAmount;
uint256 _minPortfolioTokenHoldingAmount;
bool _public;
bool _transferable;
bool _transferableToPublic;
bool _whitelistTokens;
string _name;
string _symbol;
}
/**
* @notice Data for initializing the Asset Manager Config
* @dev Used for setting up asset management configurations for an Portfolio Fund.
* @param _managementFee Annual management fee (in basis points)
* @param _performanceFee Performance fee (upon profit, in basis points)
* @param _entryFee Entry fee (in basis points)
* @param _exitFee Exit fee (in basis points)
* @param _initialPortfolioAmount Initial amount of the portfolio token
* @param _minPortfolioTokenHoldingAmount Minimum amount of portfolio tokens that can be held and can be minted
* @param _protocolConfig Protocol configuration contract address
* @param _accessController Access Controller contract address
* @param _assetManagerTreasury Treasury address for asset manager fee accumulation
* @param _whitelistedTokens Array of token addresses permitted in the Portfolio Fund
* @param _publicPortfolio Indicates if the portfolio is open to public deposits
* @param _transferable Indicates if the portfolio's tokens are transferable
* @param _transferableToPublic Indicates if the portfolio's tokens are transferable to the public
* @param _whitelistTokens Indicates if only whitelisted tokens can be included in the portfolio
*/
struct AssetManagementConfigInitData {
uint256 _managementFee;
uint256 _performanceFee;
uint256 _entryFee;
uint256 _exitFee;
uint256 _initialPortfolioAmount;
uint256 _minPortfolioTokenHoldingAmount;
address _protocolConfig;
address _accessController;
address _feeModule;
address _assetManagerTreasury;
address[] _whitelistedTokens;
bool _publicPortfolio;
bool _transferable;
bool _transferableToPublic;
bool _whitelistTokens;
}
/**
* @notice Data structure for setting up roles during Portfolio Fund creation
* @dev Used for assigning roles to various components of the Portfolio Fund ecosystem.
* @param _portfolio Portfolio contract address
* @param _protocolConfig Protocol configuration contract address
* @param _portfolioCreator Address of the portfolio creator
* @param _rebalancing Rebalancing module contract address
* @param _feeModule Fee Module contract address
*/
struct AccessSetup {
address _portfolio;
address _portfolioCreator;
address _rebalancing;
address _feeModule;
}
/**
* @notice Struct for defining a rebalance intent
* @dev Encapsulates the intent data for performing a rebalance operation.
* @param _newTokens Array of new token addresses to be included in the Portfolio Fund
* @param _sellTokens Array of token addresses to be sold during the rebalance
* @param _sellAmounts Corresponding amounts of each token to sell
* @param _handler Address of the intent handler for executing rebalance
* @param _callData Encoded call data for the rebalance operation
*/
struct RebalanceIntent {
address[] _newTokens;
address[] _sellTokens;
uint256[] _sellAmounts;
address _handler;
bytes _callData;
}
/**
* @notice Struct of batchHandler data
* @dev Encapsulates the data needed to batch transaction.
* @param _minMintAmount The minimum amount of portfolio tokens the user expects to receive for their deposit, protecting against slippage
* @param _depositAmount Amount to token to swap to vailt tokens
* @param _target Adress of portfolio contract to deposit
* @param _depositToken Address of token that needed to be swapped
* @param _callData Encoded call data for swap operation
*/
struct BatchHandler {
uint256 _minMintAmount;
uint256 _depositAmount;
address _target;
address _depositToken;
bytes[] _callData;
}
/**
* @dev Struct to encapsulate the parameters required for deploying a Safe and its associated modules.
* @param _gnosisSingleton Address of the Safe singleton contract.
* @param _gnosisSafeProxyFactory Address of the Safe Proxy Factory contract.
* @param _gnosisMultisendLibrary Address of the Multisend library contract.
* @param _gnosisFallbackLibrary Address of the Fallback library contract.
* @param _baseGnosisModule Address of the base module to be used.
* @param _owners Array of addresses to be designated as owners of the Safe.
* @param _threshold Number of owner signatures required to execute a transaction in the Safe.
*/
struct SafeAndModuleDeploymentParams {
address _gnosisSingleton;
address _gnosisSafeProxyFactory;
address _gnosisMultisendLibrary;
address _gnosisFallbackLibrary;
address _baseGnosisModule;
address[] _owners;
uint256 _threshold;
}
}
contracts/access/AccessRoles.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
/**
* @title AccessRoles
* @dev Defines roles for access control in the system.
* This contract stores constants for role identifiers used across the system to manage permissions and access.
* Roles are used in conjunction with an AccessControl mechanism to secure functions and actions.
*/
contract AccessRoles {
// Role for managing indices, including creating, updating, and deleting them.
bytes32 internal constant PORTFOLIO_MANAGER_ROLE =
keccak256("PORTFOLIO_MANAGER_ROLE");
// Role for the highest level of administrative access, capable of managing roles and critical system settings.
bytes32 internal constant SUPER_ADMIN = keccak256("SUPER_ADMIN");
// Admin role for managing the whitelist, specifically capable of adding or removing addresses from the whitelist.
bytes32 internal constant WHITELIST_MANAGER_ADMIN =
keccak256("WHITELIST_MANAGER_ADMIN");
// Role for managing assets, including tasks such as adjusting asset allocations and managing asset listings.
bytes32 internal constant ASSET_MANAGER = keccak256("ASSET_MANAGER");
// Role for managing the whitelist, typically including adding or removing addresses to/from a whitelist for access control.
bytes32 internal constant WHITELIST_MANAGER = keccak256("WHITELIST_MANAGER");
// Admin role for asset managers, capable of assigning or revoking the ASSET_MANAGER to other addresses.
bytes32 internal constant ASSET_MANAGER_ADMIN =
keccak256("ASSET_MANAGER_ADMIN");
// Specialized role for the rebalancing contract.
bytes32 internal constant REBALANCER_CONTRACT =
keccak256("REBALANCER_CONTRACT");
// Role for addresses authorized to mint tokens, typically used in token generation events or for reward distributions.
bytes32 internal constant MINTER_ROLE = keccak256("MINTER_ROLE");
}
contracts/access/IAccessController.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {FunctionParameters} from "../FunctionParameters.sol";
/**
* @title IAccessController
* @dev Interface for the AccessController contract to manage roles and permissions within the Portfolio platform.
*/
interface IAccessController {
function setupRole(bytes32 _role, address _account) external;
function setUpRoles(
FunctionParameters.AccessSetup memory _setupData
) external;
function transferSuperAdminOwnership(
address _oldAccount,
address _newAccount
) external;
function hasRole(bytes32 role, address account) external view returns (bool);
}
contracts/config/assetManagement/IAssetManagementConfig.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {FunctionParameters} from "../../FunctionParameters.sol";
/**
* @title IAssetManagementConfig
* @notice Interface for the asset management configuration contract.
*/
interface IAssetManagementConfig {
/**
* @notice Initializes the asset management configuration with the provided initial data.
* @param initData The initialization data for the asset management configuration.
*/
function init(
FunctionParameters.AssetManagementConfigInitData calldata initData
) external;
/**
* @notice Returns the management fee.
* @return The management fee.
*/
function managementFee() external view returns (uint256);
/**
* @notice Returns the performance fee.
* @return The performance fee.
*/
function performanceFee() external view returns (uint256);
/**
* @notice Returns the entry fee.
* @return The entry fee.
*/
function entryFee() external view returns (uint256);
/**
* @notice Returns the exit fee.
* @return The exit fee.
*/
function exitFee() external view returns (uint256);
/**
* @notice Returns the initial portfolio amount.
* @return The initial portfolio amount.
*/
function initialPortfolioAmount() external view returns (uint256);
/**
* @notice Returns the minimum portfolio token holding amount.
* @return The minimum portfolio token holding amount.
*/
function minPortfolioTokenHoldingAmount() external view returns (uint256);
/**
* @notice Returns the address of the asset manager treasury.
* @return The address of the asset manager treasury.
*/
function assetManagerTreasury() external returns (address);
/**
* @notice Checks if a token is whitelisted.
* @param token The address of the token.
* @return True if the token is whitelisted, false otherwise.
*/
function whitelistedTokens(address token) external returns (bool);
/**
* @notice Checks if a user is whitelisted.
* @param user The address of the user.
* @return True if the user is whitelisted, false otherwise.
*/
function whitelistedUsers(address user) external returns (bool);
/**
* @notice Checks if the portfolio is public.
* @return True if the portfolio is public, false otherwise.
*/
function publicPortfolio() external returns (bool);
/**
* @notice Checks if the portfolio token is transferable.
* @return True if the portfolio token is transferable, false otherwise.
*/
function transferable() external returns (bool);
/**
* @notice Checks if the portfolio token is transferable to the public.
* @return True if the portfolio token is transferable to the public, false otherwise.
*/
function transferableToPublic() external returns (bool);
/**
* @notice Checks if token whitelisting is enabled.
* @return True if token whitelisting is enabled, false otherwise.
*/
function tokenWhitelistingEnabled() external returns (bool);
/**
* @notice Updates the initial portfolio amount.
* @param _newPrice The new initial portfolio amount.
*/
function updateInitialPortfolioAmount(uint256 _newPrice) external;
/**
* @notice Updates the minimum portfolio token holding amount.
* @param _minPortfolioTokenHoldingAmount The new minimum portfolio token holding amount.
*/
function updateMinPortfolioTokenHoldingAmount(
uint256 _minPortfolioTokenHoldingAmount
) external;
}
contracts/config/protocol/IProtocolConfig.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
/**
* @title IProtocolConfig
* @notice Interface for the protocol configuration contract, managing various system settings and functionalities.
*/
interface IProtocolConfig {
// ----- OracleManagement Functions -----
/**
* @notice Updates the address of the price oracle.
* @param _newOracle The address of the new price oracle.
*/
function updatePriceOracle(address _newOracle) external;
/**
* @notice Returns the address of the current price oracle.
* @return The address of the current price oracle.
*/
function oracle() external view returns (address);
// ----- TreasuryManagement Functions -----
/**
* @notice Updates the address of the Velvet treasury.
* @param _newVelvetTreasury The address of the new Velvet treasury.
*/
function updateVelvetTreasury(address _newVelvetTreasury) external;
/**
* @notice Returns the address of the Velvet treasury.
* @return The address of the Velvet treasury.
*/
function velvetTreasury() external view returns (address);
// ----- SystemSettings Functions -----
/**
* @notice Returns the cooldown period for certain protocol operations.
* @return The cooldown period.
*/
function cooldownPeriod() external view returns (uint256);
/**
* @notice Returns the asset limit for the protocol.
* @return The asset limit.
*/
function assetLimit() external view returns (uint256);
/**
* @notice Returns the minimum initial portfolio amount.
* @return The minimum initial portfolio amount.
*/
function minInitialPortfolioAmount() external view returns (uint256);
/**
* @notice Returns the minimum portfolio token holding amount.
* @return The minimum portfolio token holding amount.
*/
function minPortfolioTokenHoldingAmount() external view returns (uint256);
/**
* @notice Returns whether the protocol is currently paused.
* @return True if the protocol is paused, false otherwise.
*/
function isProtocolPaused() external view returns (bool);
/**
* @notice Returns whether the protocol is currently in an emergency paused state.
* @return True if the protocol is in an emergency paused state, false otherwise.
*/
function isProtocolEmergencyPaused() external view returns (bool);
/**
* @notice Sets a new cooldown period for certain protocol operations.
* @param _newCooldownPeriod The new cooldown period.
*/
function setCoolDownPeriod(uint256 _newCooldownPeriod) external;
/**
* @notice Sets a new asset limit for the protocol.
* @param _newLimit The new asset limit.
*/
function setAssetLimit(uint256 _newLimit) external;
/**
* @notice Sets the pause state of the protocol.
* @param _paused The new pause state.
*/
function setProtocolPause(bool _paused) external;
/**
* @notice Sets the emergency pause state of the protocol.
* @param _paused The new emergency pause state.
*/
function setEmergencyPause(bool _paused) external;
// ----- TokenManagement Functions -----
/**
* @notice Enables a list of tokens for the protocol.
* @param _tokens The list of token addresses to enable.
*/
function enableTokens(address[] calldata _tokens) external;
/**
* @notice Disables a specific token for the protocol.
* @param _token The address of the token to disable.
*/
function disableToken(address _token) external;
/**
* @notice Checks if a specific token is enabled.
* @param _token The address of the token to check.
* @return True if the token is enabled, false otherwise.
*/
function isTokenEnabled(address _token) external view returns (bool);
// ----- FeeManagement Functions -----
/**
* @notice Updates the protocol fee.
* @param _newProtocolFee The new protocol fee.
*/
function updateProtocolFee(uint256 _newProtocolFee) external;
/**
* @notice Updates the protocol streaming fee.
* @param _newProtocolStreamingFee The new protocol streaming fee.
*/
function updateProtocolStreamingFee(
uint256 _newProtocolStreamingFee
) external;
/**
* @notice Returns the maximum management fee.
* @return The maximum management fee.
*/
function maxManagementFee() external view returns (uint256);
/**
* @notice Returns the maximum performance fee.
* @return The maximum performance fee.
*/
function maxPerformanceFee() external view returns (uint256);
/**
* @notice Returns the maximum entry fee.
* @return The maximum entry fee.
*/
function maxEntryFee() external view returns (uint256);
/**
* @notice Returns the maximum exit fee.
* @return The maximum exit fee.
*/
function maxExitFee() external view returns (uint256);
/**
* @notice Returns the protocol fee.
* @return The protocol fee.
*/
function protocolFee() external view returns (uint256);
/**
* @notice Returns the protocol streaming fee.
* @return The protocol streaming fee.
*/
function protocolStreamingFee() external view returns (uint256);
// ----- SolverManagement Functions -----
/**
* @notice Checks if a specific address is a solver.
* @param _handler The address to check.
* @return True if the address is a solver, false otherwise.
*/
function isSolver(address _handler) external view returns (bool);
/**
* @notice Enables a solver handler.
* @param _handler The address of the solver handler to enable.
*/
function enableSolverHandler(address _handler) external;
/**
* @notice Disables a solver handler.
* @param _handler The address of the solver handler to disable.
*/
function disableSolverHandler(address _handler) external;
/**
* @notice Checks if a specific solver handler is enabled.
* @param _handler The address to check.
* @return True if the solver handler is enabled, false otherwise.
*/
function isSolverHandlerEnabled(
address _handler
) external view returns (bool);
function whitelistLimit() external view returns (uint256);
function allowedDustTolerance() external view returns (uint256);
// ----- RewardTargetManagement Functions -----
/**
* @notice Checks if a reward target address is enabled.
* @param _rewardTargetAddress The address of the reward target to check.
* @return Boolean indicating if the reward target address is enabled.
*/
function isRewardTargetEnabled(
address _rewardTargetAddress
) external view returns (bool);
/**
* @notice Enables a reward target address by setting its status to true in the mapping.
* @dev This function can only be called by the protocol owner.
* @param _rewardTargetAddress The address of the reward target to enable.
* @dev Reverts if the provided address is invalid (address(0)).
*/
function enableRewardTarget(address _rewardTargetAddress) external;
/**
* @notice Disables a reward target address by setting its status to false in the mapping.
* @dev This function can only be called by the protocol owner.
* @param _rewardTargetAddress The address of the reward target to disable.
* @dev Reverts if the provided address is invalid (address(0)).
*/
function disableRewardTarget(address _rewardTargetAddress) external;
}
contracts/core/calculations/TokenBalanceLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {ErrorLibrary} from "../../library/ErrorLibrary.sol";
/**
* @title Token Balance Library
* @dev Library for managing token balances within a vault. Provides utility functions to fetch individual
* and collective token balances from a specified vault address.
*/
contract TokenBalanceLibrary {
/**
* @notice Fetches the balances of multiple tokens from a single vault.
* @dev Iterates through an array of token addresses to retrieve each token's balance in the vault.
* Utilizes `_getTokenBalanceOf` to fetch each individual token balance securely and efficiently.
*
* @param portfolioTokens Array of ERC20 token addresses whose balances are to be fetched.
* @param _vault The vault address from which to retrieve the balances.
* @return vaultBalances Array of balances corresponding to the list of input tokens.
*/
function getTokenBalancesOf(
address[] memory portfolioTokens,
address _vault
) public view returns (uint256[] memory vaultBalances) {
uint256 portfolioLength = portfolioTokens.length;
vaultBalances = new uint256[](portfolioLength); // Initializes the array to hold fetched balances.
for (uint256 i; i < portfolioLength; i++) {
vaultBalances[i] = _getTokenBalanceOf(portfolioTokens[i], _vault); // Fetches balance for each token.
}
}
/**
* @notice Fetches the balance of a specific token held in a given vault.
* @dev Retrieves the token balance using the ERC20 `balanceOf` function.
* Throws if the token or vault address is zero to prevent erroneous queries.
*
* @param _token The address of the token whose balance is to be retrieved.
* @param _vault The address of the vault where the token is held.
* @return tokenBalance The current token balance within the vault.
*/
function _getTokenBalanceOf(
address _token,
address _vault
) internal view returns (uint256 tokenBalance) {
if (_token == address(0) || _vault == address(0))
revert ErrorLibrary.InvalidAddress(); // Ensures neither the token nor the vault address is zero.
tokenBalance = IERC20Upgradeable(_token).balanceOf(_vault); // Actual balance fetch.
}
}
contracts/core/interfaces/IAllowanceTransfer.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {IEIP712} from "./IEIP712.sol";
/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
/// @notice Emits an event when the owner successfully invalidates an ordered nonce.
event NonceInvalidation(
address indexed owner,
address indexed token,
address indexed spender,
uint48 newNonce,
uint48 oldNonce
);
/// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
event Approval(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration
);
/// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
event Permit(
address indexed owner,
address indexed token,
address indexed spender,
uint160 amount,
uint48 expiration,
uint48 nonce
);
/// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
event Lockdown(
address indexed owner,
address indexed token,
address indexed spender
);
/// @notice The permit data for a token
struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice The permit message signed for a single token allowance
struct PermitSingle {
// the permit data for a single token alownce
PermitDetails details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The permit message signed for multiple token allowances
struct PermitBatch {
// the permit data for multiple token allowances
PermitDetails[] details;
// address permissioned on the allowed tokens
address spender;
// deadline on the permit signature
uint256 sigDeadline;
}
/// @notice The saved permissions
/// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
/// @dev Setting amount to type(uint160).max sets an unlimited approval
struct PackedAllowance {
// amount allowed
uint160 amount;
// permission expiry
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
/// @notice A token spender pair.
struct TokenSpenderPair {
// the token the spender is approved
address token;
// the spender address
address spender;
}
/// @notice Details for a token transfer.
struct AllowanceTransferDetails {
// the owner of the token
address from;
// the recipient of the token
address to;
// the amount of the token
uint160 amount;
// the token to be transferred
address token;
}
/// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
/// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
/// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
function allowance(
address user,
address token,
address spender
) external view returns (uint160 amount, uint48 expiration, uint48 nonce);
/// @notice Approves the spender to use up to amount of the specified token up until the expiration
/// @param token The token to approve
/// @param spender The spender address to approve
/// @param amount The approved amount of the token
/// @param expiration The timestamp at which the approval is no longer valid
/// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
/// @dev Setting amount to type(uint160).max sets an unlimited approval
function approve(
address token,
address spender,
uint160 amount,
uint48 expiration
) external;
/// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitSingle Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(
address owner,
PermitSingle memory permitSingle,
bytes calldata signature
) external;
/// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
/// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
/// @param owner The owner of the tokens being approved
/// @param permitBatch Data signed over by the owner specifying the terms of approval
/// @param signature The owner's signature over the permit data
function permit(
address owner,
PermitBatch memory permitBatch,
bytes calldata signature
) external;
/// @notice Transfer approved tokens from one address to another
/// @param from The address to transfer from
/// @param to The address of the recipient
/// @param amount The amount of the token to transfer
/// @param token The token address to transfer
/// @dev Requires the from address to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(
address from,
address to,
uint160 amount,
address token
) external;
/// @notice Transfer approved tokens in a batch
/// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
/// @dev Requires the from addresses to have approved at least the desired amount
/// of tokens to msg.sender.
function transferFrom(
AllowanceTransferDetails[] calldata transferDetails
) external;
/// @notice Enables performing a "lockdown" of the sender's Permit2 identity
/// by batch revoking approvals
/// @param approvals Array of approvals to revoke.
function lockdown(TokenSpenderPair[] calldata approvals) external;
/// @notice Invalidate nonces for a given (token, spender) pair
/// @param token The token to invalidate nonces for
/// @param spender The spender to invalidate nonces for
/// @param newNonce The new nonce to set. Invalidates all nonces less than it.
/// @dev Can't invalidate more than 2**16 nonces per transaction.
function invalidateNonces(
address token,
address spender,
uint48 newNonce
) external;
}
contracts/core/interfaces/IEIP712.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
interface IEIP712 {
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
contracts/core/interfaces/IPortfolio.sol
// SPDX-License-Identifier: BUSL-1.1
/**
* @title Portfolio for the Portfolio
* @author Velvet.Capital
* @notice This contract is used by the user to deposit and withdraw from the portfolio
* @dev This contract includes functionalities:
* 1. Deposit in the particular fund
* 2. Withdraw from the fund
*/
pragma solidity 0.8.17;
import {FunctionParameters} from "../../FunctionParameters.sol";
import {IPriceOracle} from "../../oracle/IPriceOracle.sol";
import {IAllowanceTransfer} from "./IAllowanceTransfer.sol";
interface IPortfolio {
function vault() external view returns (address);
function feeModule() external view returns (address);
function protocolConfig() external view returns (address);
function tokenExclusionManager() external view returns (address);
function accessController() external view returns (address);
function paused() external view returns (bool);
function assetManagementConfig() external view returns (address);
/**
* @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);
function init(
FunctionParameters.PortfolioInitData calldata initData
) external;
/**
* @dev Sets up the initial assets for the pool.
* @param tokens Underlying tokens to initialize the pool with
*/
function initToken(address[] calldata tokens) external;
// For Minting Shares
function mintShares(address _to, uint256 _amount) external;
function pullFromVault(address _token, uint256 _amount, address _to) external;
/**
* @notice The function swaps BNB into the portfolio tokens after a user makes an deposit
* @dev The output of the swap is converted into USD to get the actual amount after slippage to calculate
the portfolio token amount to mint
* @dev (tokenBalance, vaultBalance) has to be calculated before swapping for the _mintShareAmount function
because during the swap the amount will change but the portfolio token balance is still the same
(before minting)
*/
function multiTokenDeposit(
uint256[] calldata depositAmounts,
uint256 _minMintAmount,
IAllowanceTransfer.PermitBatch calldata _permit,
bytes calldata _signature
) external;
/**
* @notice Allows a specified depositor to deposit tokens into the fund through a multi-token deposit.
* The deposited tokens are added to the vault, and the user is minted portfolio tokens representing their share.
* @param _depositFor The address of the user the deposit is being made for.
* @param depositAmounts An array of amounts corresponding to each token the user wishes to deposit.
* @param _minMintAmount The minimum amount of portfolio tokens the user expects to receive for their deposit, protecting against slippage.
*/
function multiTokenDepositFor(
address _depositFor,
uint256[] calldata depositAmounts,
uint256 _minMintAmount
) external;
/**
* @notice The function swaps the amount of portfolio tokens represented by the amount of portfolio token back to
BNB and returns it to the user and burns the amount of portfolio token being withdrawn
* @param _portfolioTokenAmount The portfolio token amount the user wants to withdraw from the fund
*/
function multiTokenWithdrawal(uint256 _portfolioTokenAmount) external;
/**
* @notice Allows an approved user to withdraw portfolio tokens on behalf of another user.
* @param _withdrawFor The address of the user for whom the withdrawal is being made.
* @param _portfolioTokenAmount The amount of portfolio tokens to withdraw.
*/
function multiTokenWithdrawalFor(
address _withdrawFor,
address _tokenReceiver,
uint256 _portfolioTokenAmount
) external;
/**
@notice The function returns lastRebalanced time
*/
function getLastRebalance() external view returns (uint256);
/**
@notice The function returns lastPaused time
*/
function getLastPaused() external view returns (uint256);
function getTokens() external view returns (address[] memory);
function updateTokenList(address[] memory tokens) external;
function userLastDepositTime(address owner) external view returns (uint256);
function _checkCoolDownPeriod(address _user) external view;
function getTokenBalancesOf(
address[] memory,
address
) external view returns (uint256[] memory);
function getVaultValueInUSD(
IPriceOracle,
address[] memory,
uint256,
address
) external view returns (uint256);
function _calculateMintAmount(uint256, uint256) external returns (uint256);
function claimRewardTokens(
address _target,
bytes memory _claimCalldata
) external;
}
contracts/core/interfaces/ITokenExclusionManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
interface ITokenExclusionManager {
function init(
address _accessController,
address _protocolConfig,
address _baseTokenRemovalVaultImplementation
) external;
function snapshot() external returns (uint256);
function _currentSnapshotId() external view returns (uint256);
function claimRemovedTokens(
address user,
uint256 startId,
uint256 endId
) external;
function setUserRecord(address _user, uint256 _userBalance) external;
function setTokenAndSupplyRecord(
uint256 _snapShotId,
address _tokenRemoved,
address _vault,
uint256 _totalSupply
) external;
function claimTokenAtId(address user, uint256 id) external;
function getDataAtId(
address user,
uint256 id
) external view returns (bool, uint256);
function userRecord(
address user,
uint256 snapshotId
) external view returns (uint256 portfolioBalance, bool hasInteractedWithId);
function deployTokenRemovalVault() external returns (address);
function removedToken(
uint256 id
)
external
view
returns (address token, address vault, uint256 totalSupply);
}
contracts/handler/IIntentHandler.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
/**
* @title IIntentHandler
* @dev Interface for IntentHandler contract to facilitate token swaps and transfers.
*/
interface IIntentHandler {
/**
* @notice Conducts a token swap operation via the Solver platform and transfers the output tokens
* to a specified recipient address.
* @param _to The address designated to receive the output tokens from the swap.
* @param _callData Encoded bundle containing the swap operation data, structured as follows:
* - callDataXXX: Array of bytes representing the encoded data for each swap operation,
* allowing for direct interaction with the solver swap logic.
* - tokens: Array of token addresses involved in the swap operations.
* - minExpectedOutputAmounts: Array of minimum acceptable output amounts for the tokens
* received from each swap operation, ensuring the swap meets the user's expectations.
* @return _swapReturns Array containing the actual amounts of tokens received from each swap operation.
*/
function multiTokenSwapAndTransfer(
address _to,
bytes memory _callData
) external returns (address[] memory);
}
contracts/library/ErrorLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
/**
* @title ErrorLibrary
* @author Velvet.Capital
* @notice This is a library contract including custom defined errors
*/
library ErrorLibrary {
/// @notice Thrown when caller is not rebalancer contract
error CallerNotRebalancerContract();
/// @notice Thrown when caller is not asset manager
error CallerNotAssetManager();
/// @notice Thrown when caller is not asset manager
error CallerNotSuperAdmin();
/// @notice Thrown when caller is not whitelist manager
error CallerNotWhitelistManager();
/// @notice Thrown when length of tokens array is zero
error InvalidLength();
/// @notice Thrown when user is not allowed to deposit
error UserNotAllowedToDeposit();
/// @notice Thrown when portfolio token in not initialized
error PortfolioTokenNotInitialized();
/// @notice Thrown when caller is not holding enough portfolio token amount to withdraw
error CallerNotHavingGivenPortfolioTokenAmount();
/// @notice Thrown when the tokens are already initialized
error AlreadyInitialized();
/// @notice Thrown when the token is not whitelisted
error TokenNotWhitelisted();
/// @notice Thrown when token address being passed is zero
error InvalidTokenAddress();
/// @notice Thrown when transfer is prohibited
error Transferprohibited();
/// @notice Thrown when caller is not portfolio manager
error CallerNotPortfolioManager();
/// @notice Thrown when offchain handler is not valid
error InvalidSolver();
/// @notice Thrown when set time period is not over
error TimePeriodNotOver();
/// @notice Thrown when trying to set any fee greater than max allowed fee
error InvalidFee();
/// @notice Thrown when zero address is passed for treasury
error ZeroAddressTreasury();
/// @notice Thrown when previous address is passed for treasury
error PreviousTreasuryAddress();
/// @notice Thrown when zero address is being passed
error InvalidAddress();
/// @notice Thrown when caller is not the owner
error CallerNotOwner();
/// @notice Thrown when protocol is not paused
error ProtocolNotPaused();
/// @notice Thrown when protocol is paused
error ProtocolIsPaused();
/// @notice Thrown when token is not enabled
error TokenNotEnabled();
/// @notice Thrown when portfolio creation is paused
error PortfolioCreationIsPause();
/// @notice Thrown when asset manager is trying to input token which already exist
error TokenAlreadyExist();
/// @notice Thrown when cool down period is not passed
error CoolDownPeriodNotPassed();
/// @notice Throws when the setup is failed in gnosis
error ModuleNotInitialised();
/// @notice Throws when threshold is more than owner length
error InvalidThresholdLength();
/// @notice Throws when no owner address is passed while fund creation
error NoOwnerPassed();
/// @notice Thorws when the caller does not have a default admin role
error CallerNotAdmin();
/// @notice Throws when a public fund is tried to made transferable only to whitelisted addresses
error PublicFundToWhitelistedNotAllowed();
/// @notice Generic call failed error
error CallFailed();
/// @notice Generic transfer failed error
error TransferFailed();
/// @notice Throws when the initToken or updateTokenList function of Portfolio is having more tokens than set by the Registry
error TokenCountOutOfLimit(uint256 limit);
/// @notice Throws when the array lenghts don't match for adding price feed or enabling tokens
error IncorrectArrayLength();
/// @notice Throws when user calls updateFees function before proposing a new fee
error NoNewFeeSet();
/// @notice Throws when sequencer is down
error SequencerIsDown();
/// @notice Throws when sequencer threshold is not crossed
error SequencerThresholdNotCrossed();
/// @notice Throws when depositAmount and depositToken length does not match
error InvalidDepositInputLength();
/// @notice Mint amount smaller than users indended buy amount
error InvalidMintAmount();
/// @notice Thorws when zero price is set for min portfolio price
error InvalidMinPortfolioAmount();
/// @notice Thorws when min portfolio price is set less then min portfolio price set by protocol
error InvalidMinPortfolioAmountByAssetManager();
/// @notice Throws when assetManager set zero or less initial portfolio price then set by protocol
error InvalidInitialPortfolioAmount();
/// @notice Throws when zero amount or amount less then protocol minPortfolioAmount is set while updating min Portfolio amount by assetManager
error InvalidMinPortfolioTokenHoldingAmount();
/// @notice Throws when assetmanager set min portfolio amount less then acceptable amount set by protocol
error InvalidMinAmountByAssetManager();
/// @notice Throws when user is not maintaining min portfolio token amount while withdrawing
error CallerNeedToMaintainMinTokenAmount();
/// @notice Throws when user minted amount during deposit is less then set by assetManager
error MintedAmountIsNotAccepted();
/// @notice Throws when balance of buyToken after rebalance is zero
error BalanceOfVaultCannotNotBeZero(address);
/// @notice Throws when balance of selltoken in handler after swap is not zero
error BalanceOfHandlerShouldBeZero();
/// @notice Throws when balance of selltoken in handler after swap is exceeding dust
error BalanceOfHandlerShouldNotExceedDust();
/// @notice Throws when swap return value in handler is less then min buy amounts
error ReturnValueLessThenExpected();
/// @notice Throws when non portfolio token balance in not zero after rebalance
error NonPortfolioTokenBalanceIsNotZero();
/// @notice Throws when the oracle price is not updated under set timeout
error PriceOracleExpired();
/// @notice Throws when the oracle price is returned 0
error PriceOracleInvalid();
/// @notice Thrown when oracle address is zero address
error InvalidOracleAddress();
/// @notice Thrown when token is not in price oracle
error TokenNotInPriceOracle();
/// @notice Throws when token is not removed and user is trying to claim
error NoTokensRemoved();
/// @notice Throws when assetManager tries to remove portfolioToken
error IsPortfolioToken();
/// @notice Throws when disabled tokens are used in protocol
error NotPortfolioToken();
/// @notice Thrown when balance of vault is zero
error BalanceOfVaultIsZero();
/// @notice Thrown when max asset limit is set zero
error InvalidAssetLimit();
/// @notice Thrown when max whitelist limit is set zero
error InvalidWhitelistLimit();
/// @notice Thrown when withdrawal amount is too small and tokenBalance in return is zero
error WithdrawalAmountIsSmall();
/// @notice Thrown when deposit amount is zero
error AmountCannotBeZero();
// @notice Thrown when percentage of token to remove is invalid
error InvalidTokenRemovalPercentage();
// @notice Thrown when user passes the wrong buy token list (not equal to buy tokens in calldata)
error InvalidBuyTokenList();
/// @notice Thrown when permitted to wrong spender
error InvalidSpender();
/// @notice Thrown when claiming reward tokens failed
error ClaimFailed();
/// @notice Thrown when protocol owner passed invalid protocol streaming fee
error InvalidProtocolStreamingFee();
/// @notice Thrown when protocol owner passed invalid protocol fee
error InvalidProtocolFee();
/// @notice Thrown when protocol is emergency paused
error ProtocolEmergencyPaused();
/// @notice Thrown when batchHandler balance diff is zero
error InvalidBalanceDiff();
// @notice Thrown when an unpause action is attempted too soon after the last unpause.
error TimeSinceLastUnpauseNotElapsed();
// @notice Thrown when an invalid cooldown period is set.
error InvalidCooldownPeriod();
// @notice Thrown when the division by zero occurs
error DivisionByZero();
// @notice Thrown when the token whitelist length is zero
error InvalidTokenWhitelistLength();
// @notice Thrown when the reward target is not enabled
error RewardTargetNotEnabled();
// @notice Thrown when the allowance is insufficient
error InsufficientAllowance();
// @notice Thrown when user tries to claim for invalid Id
error InvalidId();
// @notice Thrown when exemption does match token to withdraw
error InvalidExemptionTokens();
// @notice Thrown when exemption tokens length is greater then portfolio tokens length
error InvalidExemptionTokensLength();
// @notice Thrown when the dust tolerance input is invalid
error InvalidDustTolerance();
// @notice Thrown when the target address is not whitelisted
error InvalidTargetAddress();
// @notice Thrown when the ETH balance sent is zero
error InvalidBalance();
}
contracts/oracle/IPriceOracle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {AggregatorV2V3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol";
interface IPriceOracle {
function WETH() external returns (address);
function _addFeed(
address base,
address quote,
AggregatorV2V3Interface aggregator
) external;
function convertToUSD18Decimals(
address _base,
uint256 amountIn
) external view returns (uint256 amountOut);
}
contracts/rebalance/RebalancingConfig.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;
import {ErrorLibrary} from "../library/ErrorLibrary.sol";
import {IPortfolio} from "../core/interfaces/IPortfolio.sol";
import {IAccessController} from "../access/IAccessController.sol";
import {IProtocolConfig} from "../config/protocol/IProtocolConfig.sol";
import {IAssetManagementConfig} from "../config/assetManagement/IAssetManagementConfig.sol";
import {ITokenExclusionManager} from "../core/interfaces/ITokenExclusionManager.sol";
import {AccessRoles} from "../access/AccessRoles.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable-4.9.6/proxy/utils/Initializable.sol";
import {TokenBalanceLibrary} from "../core/calculations/TokenBalanceLibrary.sol";
/**
* @title RebalancingConfig
* @notice Provides auxiliary functions to support the RebalancingCore contract operations, including balance checks and validator checks.
* @dev This contract includes helper functions for rebalancing operations such as validating handler, checking token balances, and initial setup.
*/
contract RebalancingConfig is AccessRoles, Initializable, TokenBalanceLibrary {
IPortfolio public portfolio;
IAccessController public accessController;
IProtocolConfig public protocolConfig;
IAssetManagementConfig public assetManagementConfig;
ITokenExclusionManager internal tokenExclusionManager;
mapping(address => bool) public tokensMapping;
address internal _vault;
/**
* @notice Initializes the contract with portfolio, access controller, protocol and asset management configuration.
* @param _portfolio Address of the Portfolio contract.
* @param _accessController Address of the AccessController.
*/
function __RebalancingHelper_init(
address _portfolio,
address _accessController
) internal onlyInitializing {
if (_portfolio == address(0) || _accessController == address(0))
revert ErrorLibrary.InvalidAddress();
portfolio = IPortfolio(_portfolio);
accessController = IAccessController(_accessController);
protocolConfig = IProtocolConfig(portfolio.protocolConfig());
assetManagementConfig = IAssetManagementConfig(
portfolio.assetManagementConfig()
);
tokenExclusionManager = ITokenExclusionManager(
portfolio.tokenExclusionManager()
);
_vault = portfolio.vault();
}
/**
* @dev Ensures that the function is only called by an asset manager.
*/
modifier onlyAssetManager() {
if (!accessController.hasRole(ASSET_MANAGER, msg.sender)) {
revert ErrorLibrary.CallerNotAssetManager();
}
_;
}
/**
* @notice Checks that each token bought by the Solver is in the portfolio list.
* @param _ensoBuyTokens Array of token addresses bought by the Solver.
* @param _newTokens Array of new portfolio tokens.
*/
function _verifyNewTokenList(
address[] memory _ensoBuyTokens,
address[] memory _newTokens
) internal {
uint256 tokenLength = _newTokens.length;
for (uint256 i; i < tokenLength; i++) {
address token = _newTokens[i];
if (_getTokenBalanceOf(token, _vault) == 0)
revert ErrorLibrary.BalanceOfVaultCannotNotBeZero(token);
tokensMapping[token] = true;
}
uint256 ensoBuyTokensLength = _ensoBuyTokens.length;
for (uint256 i; i < ensoBuyTokensLength; i++) {
if (!tokensMapping[_ensoBuyTokens[i]]) {
revert ErrorLibrary.InvalidBuyTokenList();
}
}
for (uint256 i; i < tokenLength; i++) {
delete tokensMapping[_newTokens[i]];
}
}
/**
* @notice Updates the token balance mapping based on the new token list.
* @param _portfolioTokens Array of current portfolio tokens.
* @param _newTokens Array of new tokens after rebalancing.
*/
function _verifyZeroBalanceForRemovedTokens(
address[] memory _portfolioTokens,
address[] memory _newTokens
) internal {
uint256 tokenLength = _portfolioTokens.length;
for (uint256 i; i < tokenLength; i++) {
tokensMapping[_portfolioTokens[i]] = true;
}
uint256 newTokensLength = _newTokens.length;
for (uint256 i; i < newTokensLength; i++) {
tokensMapping[_newTokens[i]] = false;
}
for (uint256 i; i < tokenLength; i++) {
address _portfolioToken = _portfolioTokens[i];
if (tokensMapping[_portfolioToken]) {
if (_getTokenBalanceOf(_portfolioToken, _vault) != 0)
revert ErrorLibrary.NonPortfolioTokenBalanceIsNotZero();
}
delete tokensMapping[_portfolioToken];
}
}
/**
* @notice The function is used to get tokens from portfolio
* @return Array of token returned
*/
function _getCurrentTokens() internal view returns (address[] memory) {
return portfolio.getTokens();
}
/**
* @notice Checks if a token is part of the current portfolio token list.
* @param _token The address of the token to check.
* @return bool Returns true if the token is part of the portfolio, false otherwise.
*/
function _isPortfolioToken(address _token) internal view returns (bool) {
address[] memory currentTokens = _getCurrentTokens();
uint256 tokensLength = currentTokens.length;
for (uint256 i; i < tokensLength; i++) {
if (currentTokens[i] == _token) {
return true;
}
}
return false;
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.