Verified contractPartialAGPL-3.0-only
BittyVault
Address0x74dfda5faaedbcfbc9626035b6a11e5843644984
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- prague
- Via IR
- yes
- License
- AGPL-3.0-only
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,372,557
- Creation transaction
- 0xbec196a025…b9e85cf6d7
- Libraries
- src/BittyVault.sol:VaultLogic0xfb20…db8291src/BittyVault.sol:AssetManagerLogic0xd76c…0f4ff5
29 files
- src/BittyVault.solmain12.5 KB
- lib/guard-contracts/src/interfaces/IGuard.sol8.88 KB
- lib/openzeppelin-contracts/contracts/access/AccessControl.sol8.23 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol2.92 KB
- lib/openzeppelin-contracts/contracts/proxy/Clones.sol4.03 KB
- lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol6.62 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.74 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol9.36 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol962 B
- lib/openzeppelin-contracts/contracts/utils/Strings.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol987 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol853 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol12.79 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol12.96 KB
- lib/protocol-contracts/src/interfaces/IAMMProtocol.sol1.66 KB
- lib/protocol-contracts/src/interfaces/ILendingProtocol.sol1.03 KB
- lib/protocol-contracts/src/interfaces/IProtocol.sol417 B
- lib/protocol-contracts/src/interfaces/IStakingProtocol.sol2.07 KB
- lib/solmate/src/tokens/ERC20.sol6.81 KB
- lib/solmate/src/tokens/WETH.sol1.03 KB
- lib/solmate/src/utils/SafeTransferLib.sol5.77 KB
- src/interfaces/IAssetManager.sol10.82 KB
- src/interfaces/IVault.sol6.89 KB
- src/logic/AssetManagerLogic.sol22.48 KB
- src/logic/Storages.sol1.21 KB
- src/logic/VaultLogic.sol10.81 KB
src/BittyVault.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {Initializable} from "openzeppelin-contracts/contracts/proxy/utils/Initializable.sol";
import {AccessControl} from "openzeppelin-contracts/contracts/access/AccessControl.sol";
import {IAssetManager} from "./interfaces/IAssetManager.sol";
import {IGuard} from "guard-contracts/src/interfaces/IGuard.sol";
import {IVault, ReceiverNotFound, OnlyReceiver, OwnerAndAssetManagerMustDiffer} from "./interfaces/IVault.sol";
import {AssetManagerLogic} from "./logic/AssetManagerLogic.sol";
import {VaultLogic} from "./logic/VaultLogic.sol";
import {AssetManagerStorage, VaultStorage} from "./logic/Storages.sol";
/**
* @title BittyVault
* @notice
* @dev
*
* Role hierarchy:
* - DEFAULT_ADMIN_ROLE: hardware wallet / multi-sig. Owns all config and irreversible ops.
* - ASSET_MANAGER_ROLE: hot wallet / AI agent. Executes yield and trading operations only.
*/
contract BittyVault is IVault, IAssetManager, Initializable, AccessControl {
using AssetManagerLogic for AssetManagerStorage;
using VaultLogic for VaultStorage;
bytes32 public constant ASSET_MANAGER_ROLE = keccak256("ASSET_MANAGER_ROLE");
string public vaultName;
AssetManagerStorage internal _assetManager;
VaultStorage internal _vault;
receive() external payable {}
function initialize(
address owner,
string memory initialName,
address[] memory assetManagers,
address guardAddress,
address weth,
address[] memory assetAddresses,
address[] memory lendingProtocols,
address[] memory stakingProtocols,
address[] memory ammProtocols
) public initializer {
vaultName = initialName;
_grantRole(DEFAULT_ADMIN_ROLE, owner);
for (uint256 i = 0; i < assetManagers.length; i++) {
if (assetManagers[i] == owner) revert OwnerAndAssetManagerMustDiffer();
if (assetManagers[i] != address(0)) {
_grantRole(ASSET_MANAGER_ROLE, assetManagers[i]);
}
}
_vault.initialize(guardAddress);
if (assetAddresses.length > 0) {
_vault.addAssets(assetAddresses);
}
_assetManager.initialize(guardAddress, weth);
if (lendingProtocols.length > 0) {
_assetManager.addLendingProtocols(lendingProtocols);
}
if (stakingProtocols.length > 0) {
_assetManager.addStakingProtocols(stakingProtocols);
}
if (ammProtocols.length > 0) {
_assetManager.addAMMProtocols(ammProtocols);
}
}
function _grantRole(bytes32 role, address account) internal override {
if (role == ASSET_MANAGER_ROLE && hasRole(DEFAULT_ADMIN_ROLE, account)) {
revert OwnerAndAssetManagerMustDiffer();
}
if (role == DEFAULT_ADMIN_ROLE && hasRole(ASSET_MANAGER_ROLE, account)) {
revert OwnerAndAssetManagerMustDiffer();
}
super._grantRole(role, account);
}
function setName(string memory newName) external override onlyRole(DEFAULT_ADMIN_ROLE) {
vaultName = newName;
}
// ============ AMM ============
function rebalance(
address ammProtocol,
address from,
address to,
uint256 sellAmount,
uint256 buyAmountMin,
bytes memory data
) external override onlyRole(ASSET_MANAGER_ROLE) {
_vault.checkAsset(from);
_vault.checkAsset(to);
_assetManager.rebalance(_vault, ammProtocol, from, to, sellAmount, buyAmountMin, data);
}
function addLiquidity(
address ammProtocol,
address token0,
uint256 amount0,
address token1,
uint256 amount1,
bytes memory data
) external override onlyRole(ASSET_MANAGER_ROLE) {
_assetManager.addLiquidity(ammProtocol, token0, amount0, token1, amount1, data);
}
function removeLiquidity(address ammProtocol, bytes memory data) external override onlyRole(ASSET_MANAGER_ROLE) {
_assetManager.removeLiquidity(ammProtocol, data);
}
function claimAMMFees(address ammProtocol, bytes memory data) external override onlyRole(ASSET_MANAGER_ROLE) {
_assetManager.claimAMMFees(ammProtocol, data);
}
function getLiquidity(address ammProtocol, bytes memory data) external view override returns (uint256) {
return _assetManager.getLiquidity(ammProtocol, data);
}
// ============ Lending ============
function supply(address lendingProtocol, address assetAddress, uint256 amount)
external
override
onlyRole(ASSET_MANAGER_ROLE)
{
_assetManager.supply(lendingProtocol, assetAddress, amount);
}
function withdraw(address lendingProtocol, address assetAddress, uint256 amount)
external
override
onlyRole(ASSET_MANAGER_ROLE)
{
_assetManager.withdraw(lendingProtocol, assetAddress, amount);
}
function getSuppliedBalance(address lendingProtocol, address assetAddress)
external
view
override
returns (uint256)
{
return _assetManager.getSuppliedBalance(lendingProtocol, assetAddress);
}
// ============ Staking ============
function stake(address stakingProtocol, address asset, uint256 amount)
external
override
onlyRole(ASSET_MANAGER_ROLE)
{
_assetManager.stake(stakingProtocol, asset, amount);
}
function unstake(address stakingProtocol, address asset, uint256 amount)
external
override
onlyRole(ASSET_MANAGER_ROLE)
{
_assetManager.unstake(stakingProtocol, asset, amount);
}
function getStakedBalance(address stakingProtocol, address asset) external view override returns (uint256) {
return _assetManager.getStakedBalance(stakingProtocol, asset);
}
function getUnstakeRequestIds(address stakingProtocol) external view override returns (uint256[] memory) {
return _assetManager.getUnstakeRequestIds(stakingProtocol);
}
function claimUnstaked(address stakingProtocol, uint256[] memory requestIds)
external
override
onlyRole(ASSET_MANAGER_ROLE)
{
_assetManager.claimUnstaked(stakingProtocol, requestIds);
}
// ============ Rebalance config ============
function setRebalanceConfig(address assetAddress, IAssetManager.RebalanceConfig memory _assetConfig)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_assetManager.setRebalanceConfig(assetAddress, _assetConfig);
}
function disableRebalanceUntilTimestamp(uint256 timestamp) external override onlyRole(ASSET_MANAGER_ROLE) {
_assetManager.disableRebalanceUntilTimestamp(timestamp);
}
// ============ Protocol config ============
function disableAddingProtocols() external override onlyRole(DEFAULT_ADMIN_ROLE) {
_assetManager.disableAddingProtocols();
emit ProtocolsLocked();
}
function isAddingProtocolsDisabled() external view override returns (bool) {
return _assetManager.addingProtocolsDisabled;
}
function addLendingProtocols(address[] memory lendingProtocolAddresses)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_assetManager.addLendingProtocols(lendingProtocolAddresses);
}
function removeLendingProtocols(address[] memory lendingProtocolAddresses)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_assetManager.removeLendingProtocols(lendingProtocolAddresses);
}
function addStakingProtocols(address[] memory stakingProtocolAddresses)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_assetManager.addStakingProtocols(stakingProtocolAddresses);
}
function removeStakingProtocols(address[] memory stakingProtocolAddresses)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_assetManager.removeStakingProtocols(stakingProtocolAddresses);
}
function addAMMProtocols(address[] memory ammProtocolAddresses) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_assetManager.addAMMProtocols(ammProtocolAddresses);
}
function removeAMMProtocols(address[] memory ammProtocolAddresses) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_assetManager.removeAMMProtocols(ammProtocolAddresses);
}
// ============ ETH/WETH ============
function ETHToWETH(uint256 amount) external override onlyRole(ASSET_MANAGER_ROLE) {
_assetManager.ETHToWETH(amount);
}
function WETHToETH(uint256 amount) external override onlyRole(ASSET_MANAGER_ROLE) {
_assetManager.WETHToETH(amount);
}
// ============ Asset config ============
function addAssets(address[] memory assetAddresses) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_vault.addAssets(assetAddresses);
}
function removeAssets(address[] memory assetAddresses) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_vault.removeAssets(assetAddresses);
}
// irreversible — DEFAULT_ADMIN_ROLE only
function disableAddingAssets() external override onlyRole(DEFAULT_ADMIN_ROLE) {
_vault.disableAddingAssets();
emit AssetsLocked();
}
function isAddingAssetsDisabled() external view override returns (bool) {
return _vault.addingAssetsDisabled;
}
// ============ Receivers (RECEIVER_MANAGER_ROLE) ============
function addReceiver(string memory receiverName, IVault.Receiver calldata receiver_)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_vault.addReceiver(receiverName, receiver_);
}
function updateReceiver(string memory receiverName, IVault.Receiver calldata receiver_)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_vault.updateReceiver(receiverName, receiver_);
}
function removeReceiver(string memory receiverName) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_vault.removeReceiver(receiverName);
}
// DEFAULT_ADMIN_ROLE — controls the time-lock window for new receivers
function setNewReceiverProtection(uint256 newReceiverProtection) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_vault.setNewReceiverProtection(newReceiverProtection);
}
function changeReceiverAddress(string memory receiverName, address newReceiverAddress) external override {
address oldReceiverAddress = _vault.getReceiverAddress(receiverName);
if (oldReceiverAddress == address(0)) revert ReceiverNotFound();
if (oldReceiverAddress != msg.sender) revert OnlyReceiver();
_vault.changeReceiverAddress(receiverName, newReceiverAddress);
}
function payReceiver(string memory receiverName) external override {
_vault.payReceiver(receiverName);
}
function payReceiverAmount(string memory receiverName, uint256 amount) external override {
_vault.payReceiverAmount(receiverName, amount);
}
// ============ View ============
function name() external view override returns (string memory) {
return vaultName;
}
function getAssets() external view override returns (address[] memory) {
return _vault.getAssets();
}
function getStableCoins() external view override returns (address[] memory) {
return _vault.getStableCoins();
}
function wethAddress() external view returns (address) {
return _assetManager.weth;
}
function guard() external view returns (IGuard) {
return _assetManager.guard;
}
function getLendingProtocols() external view override returns (address[] memory) {
return _assetManager.getLendingProtocols();
}
function getStakingProtocols() external view override returns (address[] memory) {
return _assetManager.getStakingProtocols();
}
function getAMMProtocols() external view override returns (address[] memory) {
return _assetManager.getAMMProtocols();
}
function lastRebalanceTimestamps(address assetAddress) external view returns (uint256) {
return _assetManager.lastRebalanceTimestamps[assetAddress];
}
function rebalanceConfigs(address assetAddress) external view returns (IAssetManager.RebalanceConfig memory) {
return _assetManager.rebalanceConfigs[assetAddress];
}
}
lib/guard-contracts/src/interfaces/IGuard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error AMMProtocolShouldNotBeAllRemoved();
error NotRegistered();
error Deprecated();
/**
* @title Manage the registered assets and protocols.
* @dev Manage the registered assets and protocols by Bitty.
*/
interface IGuard {
/**
* @notice Add a registered asset to Bitty.
* @dev Add a registered asset to Bitty.
* @param assetAddresses The addresses of the assets.
*/
function addAssets(address[] memory assetAddresses) external;
/**
* @notice Remove a registered asset from Bitty.
* @dev Remove a registered asset from Bitty.
* A removed asset can only be sold instead of being bought.
* @param assetAddresses The addresses of the assets.
*/
function removeAssets(address[] memory assetAddresses) external;
/**
* @notice Check if an asset is registered.
* @dev Check if an asset is registered.
* @param assetAddress The address of the asset.
* @return bool True if the asset is registered, false otherwise.
*/
function isAssetRegistered(address assetAddress) external view returns (bool);
/**
* @notice Add a stable coin to Bitty.
* @dev Add a stable coin to Bitty.
* @param stableCoinAddresses The addresses of the stable coins.
*/
function addStableCoins(address[] memory stableCoinAddresses) external;
/**
* @notice Remove a stable coin from Bitty.
* @dev Remove a stable coin from Bitty.
* A removed stable coin can only be sold, can not be bought anymore.
* @param stableCoinAddresses The addresses of the stable coins.
*/
function removeStableCoins(address[] memory stableCoinAddresses) external;
/**
* @notice Check if a stable coin is registered.
* @dev Check if a stable coin is registered.
* @param stableCoinAddress The address of the stable coin.
* @return bool True if the stable coin is registered, false otherwise.
*/
function isStableCoinRegistered(address stableCoinAddress) external view returns (bool);
/**
* @notice Add a yield protocol to Bitty.
* @dev Add a yield protocol to Bitty.
* @param lendingProtocolAddresses The addresses of the yield protocols.
*/
function addLendingProtocols(address[] memory lendingProtocolAddresses) external;
/**
* @notice Deprecate a yield protocol from Bitty.
* @dev Deprecate a yield protocol from Bitty.
* A deprecated yield protocol is only used for withdrawals, can not supply to it anymore.
* @param lendingProtocolAddresses The addresses of the yield protocols.
*/
function deprecateLendingProtocols(address[] memory lendingProtocolAddresses) external;
/**
* @notice Check if a yield protocol is registered.
* @dev Check if a yield protocol is registered.
* @param lendingProtocolAddress The address of the yield protocol.
* @return bool True if the yield protocol is registered, false otherwise.
*/
function isLendingProtocolRegistered(address lendingProtocolAddress) external view returns (bool);
/**
* @notice Check if a yield protocol is deprecated.
* @dev Check if a yield protocol is deprecated.
* @param lendingProtocolAddress The address of the yield protocol.
* @return bool True if the yield protocol is deprecated, false otherwise.
*/
function isLendingProtocolDeprecated(address lendingProtocolAddress) external view returns (bool);
/**
* @notice Add a staking protocol to Bitty.
* @dev Add a staking protocol to Bitty.
* @param stakingProtocols the addresses of the staking protocols.
*/
function addStakingProtocols(address[] memory stakingProtocols) external;
/**
* @notice Check if a staking protocol is registered.
* @dev Check if a staking protocol is registered.
* @param stakingProtocol The address of the staking protocol.
* @return bool True if the staking protocol is registered, false otherwise.
*/
function isStakingProtocolRegistered(address stakingProtocol) external view returns (bool);
/**
* @notice Deprecate a staking protocol from Bitty.
* @dev Deprecate a staking protocol from Bitty.
* A deprecated staking protocol is only used for withdrawals, can not supply to it anymore.
* @param stakingProtocols The addresses of the staking protocols.
*/
function deprecateStakingProtocols(address[] memory stakingProtocols) external;
/**
* @notice Check if a staking protocol is deprecated.
* @dev Check if a staking protocol is deprecated.
* @param stakingProtocolAddress The address of the staking protocol.
* @return bool True if the staking protocol is deprecated, false otherwise.
*/
function isStakingProtocolDeprecated(address stakingProtocolAddress) external view returns (bool);
/**
* @notice Add an intent protocol to Bitty.
* @dev Add an intent protocol to Bitty.
* @param intentProtocolAddresses The addresses of the intent protocols.
*/
function addIntentProtocols(address[] memory intentProtocolAddresses) external;
/**
* @notice Check if an intent protocol is registered.
* @dev Check if an intent protocol is registered.
* @param intentProtocolAddress The address of the intent protocol.
* @return bool True if the intent protocol is registered, false otherwise.
*/
function isIntentProtocolRegistered(address intentProtocolAddress) external view returns (bool);
/**
* @notice Deprecate an intent protocol from Bitty.
* @dev Deprecate an intent protocol from Bitty.
* A deprecated intent protocol is only used for canceling trades, can not be used for executing trades anymore.
* @param intentProtocolAddresses The addresses of the intent protocols.
*/
function deprecateIntentProtocols(address[] memory intentProtocolAddresses) external;
/**
* @notice Check if an intent protocol is deprecated.
* @dev Check if an intent protocol is deprecated.
* @param intentProtocolAddress The address of the intent protocol.
* @return bool True if the intent protocol is deprecated, false otherwise.
*/
function isIntentProtocolDeprecated(address intentProtocolAddress) external view returns (bool);
/**
* @notice Add a swap protocol to Bitty.
* @dev Add a swap protocol to Bitty.
* @param ammProtocolAddresses The addresses of the swap protocols.
*/
function addAMMProtocols(address[] memory ammProtocolAddresses) external;
/**
* @notice Remove a swap protocol from Bitty.
* @dev Remove a swap protocol from Bitty.
* @param ammProtocolAddresses The addresses of the swap protocols.
*/
function removeAMMProtocols(address[] memory ammProtocolAddresses) external;
/**
* @notice Check if a swap protocol is registered.
* @dev Check if a swap protocol is registered.
* @param ammProtocolAddress The address of the swap protocol.
* @return bool True if the swap protocol is registered, false otherwise.
*/
function isAMMProtocolRegistered(address ammProtocolAddress) external view returns (bool);
/**
* @notice Get the registered assets.
* @dev Get the registered assets.
* @return addresses The addresses of the registered assets.
*/
function getAssets() external view returns (address[] memory addresses);
/**
* @notice Get the registered stable coins.
* @dev Get the registered stable coins.
* @return addresses The addresses of the registered stable coins.
*/
function getStableCoins() external view returns (address[] memory addresses);
/**
* @notice Get the registered AMM protocols.
* @dev Get the registered AMM protocols.
* @return addresses The addresses of the registered AMM protocols.
*/
function getAMMProtocols() external view returns (address[] memory addresses);
/**
* @notice Get the registered lending protocols.
* @dev Get the registered lending protocols.
* @return addresses The addresses of the registered lending protocols.
*/
function getLendingProtocols() external view returns (address[] memory addresses);
/**
* @notice Get the registered staking protocols.
* @dev Get the registered staking protocols.
* @return addresses The addresses of the registered staking protocols.
*/
function getStakingProtocols() external view returns (address[] memory addresses);
/**
* @notice Get the registered intent protocols.
* @dev Get the registered intent protocols.
* @return addresses The addresses of the registered intent protocols.
*/
function getIntentProtocols() external view returns (address[] memory addresses);
}
lib/openzeppelin-contracts/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
lib/openzeppelin-contracts/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(0, 0x09, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
lib/openzeppelin-contracts/contracts/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/Address.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) || (!Address.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;
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.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 IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the 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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
lib/openzeppelin-contracts/contracts/utils/Address.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 Address {
/**
* @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);
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
lib/protocol-contracts/src/interfaces/IAMMProtocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {IProtocol} from "./IProtocol.sol";
/**
* @title IAMMProtocol
* @notice Interface for AMM (swap and liquidity) protocols.
*/
interface IAMMProtocol is IProtocol {
/**
* @notice Swap tokens on the AMM protocol.
* @dev Swap tokens on the AMM protocol.
* @param data The data for the swap.
* @dev Only the asset manager can execute it.
*/
function swap(bytes memory data) external payable;
/**
* @notice Add liquidity to the AMM protocol.
* @dev Add liquidity to the AMM protocol.
* @param data The data for the add liquidity.
* @dev Only the asset manager can execute it.
*/
function addLiquidity(bytes memory data) external;
/**
* @notice Remove liquidity from the AMM protocol, this will also collect the fees.
* @dev Remove liquidity from the AMM protocol.
* @param data The data for the remove liquidity.
* @dev Only the asset manager can execute it.
*/
function removeLiquidity(bytes memory data) external;
/**
* @notice Claim fees from the AMM protocol.
* @dev Claim fees from the AMM protocol.
* @param data The data for the claim fees.
* @dev Only the asset manager can execute it.
*/
function claimAMMFees(bytes memory data) external;
/**
* @notice Get the liquidity of the AMM protocol.
* @dev Get the liquidity of the AMM protocol.
* @param data The data for the get liquidity.
* @dev Only the asset manager can execute it.
*/
function getLiquidity(bytes memory data) external view returns (uint256);
}
lib/protocol-contracts/src/interfaces/ILendingProtocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {IProtocol} from "./IProtocol.sol";
interface ILendingProtocol is IProtocol {
/**
* @notice Supply the asset to the lending protocol.
* @dev Supply the asset to the lending protocol.
* @param asset The address of the asset.
* @param amount The amount of the asset.
*/
function supply(address asset, uint256 amount) external payable;
/**
* @notice Withdraw the asset from the lending protocol.
* @dev Withdraw the asset from the lending protocol.
* @param asset The address of the asset.
* @param amount The amount of the asset.
*/
function withdraw(address asset, uint256 amount) external;
/**
* @notice Get the lending balance of the asset.
* @dev Get the lending balance of the asset.
* @param asset The address of the asset.
* @return The lending balance of the asset.
*/
function getSuppliedBalance(address asset) external view returns (uint256);
}
lib/protocol-contracts/src/interfaces/IProtocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
/**
* @title IProtocol
* @notice Interface for all protocols.
* @dev This interface is used to initialize the protocol.
*/
interface IProtocol {
/**
* @notice Initialize the protocol.
* @param newOwner The address of the new owner.
* @dev Initialize the protocol.
*/
function initialize(address newOwner) external;
}
lib/protocol-contracts/src/interfaces/IStakingProtocol.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {IProtocol} from "./IProtocol.sol";
error UnstakeMoreThanStaked();
error InvalidAsset();
error ClaimUnstakedNotSupported();
/**
* @title IStakingProtocol
* @notice Interface for staking protocols.
* @dev This interface is used to stake and unstake the asset.
*/
interface IStakingProtocol is IProtocol {
/**
* @notice Stake the asset to the staking protocol.
* @dev Stake the asset to the staking protocol.
* @param asset The address of the asset.
* @param amount The amount of the asset.
*/
function stake(address asset, uint256 amount) external payable;
/**
* @notice Get the staking balance.
* @dev Get the staking balance.
* @param asset The address of the asset.
* @return The staking balance.
*/
function getStakedBalance(address asset) external view returns (uint256);
/**
* @notice Unstake the asset from the staking protocol.
* @dev Unstake the asset from the staking protocol.
* @param asset The address of the asset.
* @param amount The amount of the asset.
*/
function unstake(address asset, uint256 amount) external;
/**
* @notice Get the unstake request ids.
* @dev Get the unstake request ids, some staking protocols.
* Some protocols for ETH staking need to wait a period of time before the unstake request is finalized.
* Some protocols for StableCoin staking do not need this.
* @return The unstake request ids.
*/
function getUnstakeRequestIds() external view returns (uint256[] memory);
/**
* @notice Claim the unstaked asset from the staking protocol.
* @dev Claim the unstaked asset from the staking protocol.
* Some protocols for ETH staking need to wait a period of time before the unstake request is finalized.
* Some protocols for StableCoin staking do not need this.
* @param requestIds The request ids to claim.
*/
function claimUnstaked(uint256[] memory requestIds) external;
}
lib/solmate/src/tokens/ERC20.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*//////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*//////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*//////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*//////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*//////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
address recoveredAddress = ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
lib/solmate/src/tokens/WETH.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "./ERC20.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
/// @notice Minimalist and modern Wrapped Ether implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
using SafeTransferLib for address;
event Deposit(address indexed from, uint256 amount);
event Withdrawal(address indexed to, uint256 amount);
function deposit() public payable virtual {
_mint(msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) public virtual {
_burn(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
msg.sender.safeTransferETH(amount);
}
receive() external payable virtual {
deposit();
}
}
lib/solmate/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*//////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and store if it succeeded or not.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
/*//////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
success := call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data and token has code.
if and(iszero(and(eq(mload(0), 1), gt(returndatasize(), 31))), success) {
success := iszero(or(iszero(extcodesize(token)), returndatasize()))
}
}
require(success, "APPROVE_FAILED");
}
}
src/interfaces/IAssetManager.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
error RebalanceInMinimalTime();
error RebalanceMaxAmount();
error SellAmountMismatch();
error BuyAmountNotEnough();
error MinimalBalanceNotMet();
error InvalidLendingProtocol();
error InvalidStakingProtocol();
error InvalidAMMProtocol();
error InvalidSwapData();
error DisableRebalanceUntilTimestampTooEarly();
error RebalanceDisabled();
error ETHBalanceNotEnough();
error WETHBalanceNotEnough();
interface IAssetManager {
/**
* @notice Per-asset limits for rebalancing. All amount fields use the token's native decimals
* (raw on-chain units), not human-readable whole-token amounts.
*
* Examples (minimalDuration = 13 seconds in each case):
* - USDC (6 decimals): keep 1,000,000 USDC → minimalBalance = 1_000_000e6; no per-swap cap → maxAmount = 0
* - WBTC (8 decimals): keep 1 WBTC → minimalBalance = 1e8; cap each swap at 0.1 WBTC → maxAmount = 1e7
* - WETH (18 decimals): keep 10 WETH → minimalBalance = 10 ether; cap each swap at 1 WETH → maxAmount = 1 ether
*
* @param minimalBalance Minimum token balance that must remain in the vault after a rebalance sell.
* Set to 0 to allow selling the full balance. Use 1e8 for 1 WBTC, 1 ether for 1 WETH, etc.
* @param minimalDuration Minimum time between rebalances for this asset. Set to 0 to disable the cooldown.
* @param maxAmount Maximum sell amount per rebalance for this asset. Set to 0 for no limit.
*/
struct RebalanceConfig {
/**
* @dev Minimum balance left after selling `from` during rebalance. Expressed in token decimals
* (e.g. 1e8 = 1 WBTC, 10 ether = 10 WETH). Zero allows selling the entire balance.
*/
uint256 minimalBalance;
/**
* @dev Seconds that must pass since the last rebalance involving this asset before another is allowed.
*/
uint256 minimalDuration;
/**
* @dev Upper bound on sell amount per rebalance, in token decimals. Zero means unlimited.
*/
uint256 maxAmount;
}
/**
* @notice Turn the ETH to WETH.
* @dev Turn the ETH to WETH.
* @param amount The amount of ETH to turn.
*/
function ETHToWETH(uint256 amount) external;
/**
* @notice Turn the WETH to ETH.
* @dev Turn the WETH to ETH.
* @param amount The amount of WETH to turn.
*/
function WETHToETH(uint256 amount) external;
/**
* @notice Get the yield providers.
* @dev Get the yield providers.
* @return lendingProtocolAddresses The addresses of the yield providers.
*/
function getLendingProtocols() external view returns (address[] memory);
/**
* @notice Get the staking providers.
* @dev Get the staking providers.
* @return stakingProtocolAddresses The addresses of the staking providers.
*/
function getStakingProtocols() external view returns (address[] memory);
/**
* @notice Get the swap providers.
* @dev Get the swap providers.
* @return ammProtocolAddresses The addresses of the swap providers.
*/
function getAMMProtocols() external view returns (address[] memory);
/**
* @notice Set rebalance limits for an asset. Amount fields in `assetConfig` use the asset's token decimals.
* @param assetAddress The address of the asset.
* @param assetConfig The rebalance config (see `RebalanceConfig` for decimal examples).
*/
function setRebalanceConfig(address assetAddress, RebalanceConfig memory assetConfig) external;
/**
* @notice Supply the asset to the lending provider.
* @dev Supply the asset to the lending provider.
* @param lendingProtocol The address of the lending provider.
* @param assetAddress The address of the asset.
* @param amount The amount of the asset.
*/
function supply(address lendingProtocol, address assetAddress, uint256 amount) external;
/**
* @notice Withdraw the asset from the lending provider.
* @dev Withdraw the asset from the lending provider.
* @param lendingProtocol The address of the lending provider.
* @param assetAddress The address of the asset.
* @param amount The amount of the asset.
*/
function withdraw(address lendingProtocol, address assetAddress, uint256 amount) external;
/**
*
* @param lendingProtocol The address of the lending provider.
* @param assetAddress The address of the asset.
* @return The balance of the asset.
*/
function getSuppliedBalance(address lendingProtocol, address assetAddress) external view returns (uint256);
/**
* @notice Stake the asset to the staking provider.
* @dev Stake the asset to the staking provider, this only works for ETH mainnet.
* @param stakingProtocol The address of the staking provider.
* @param asset The address of the asset.
* @param amount The amount of the weth.
*/
function stake(address stakingProtocol, address asset, uint256 amount) external;
/**
* @notice Get the staking balance.
* @dev Get the staking balance.
* @param stakingProtocol The address of the staking provider.
* @param asset The address of the asset.
* @return The staking balance.
*/
function getStakedBalance(address stakingProtocol, address asset) external view returns (uint256);
/**
* @notice Unstake the asset from the staking provider.
* @dev Unstake the asset from the staking provider, this only works for ETH mainnet.
* @param stakingProtocol The address of the staking provider.
* @param asset The address of the asset.
* @param amount The amount of the asset.
*/
function unstake(address stakingProtocol, address asset, uint256 amount) external;
/**
* @notice Get the unstake request ids.
* @dev Get the unstake request ids.
* @param stakingProtocol The address of the staking provider.
* @return unstakeRequestIds The unstake request ids.
*/
function getUnstakeRequestIds(address stakingProtocol) external view returns (uint256[] memory);
/**
* @notice Claim withdrawn assets from the staking provider.
* @dev Claim withdrawn assets from the staking provider after unstake requests are finalized.
* @param stakingProtocol The address of the staking provider.
* @param requestIds The request ids to claim.
*/
function claimUnstaked(address stakingProtocol, uint256[] memory requestIds) external;
/**
*
* @param ammProtocol The address of the swap provider.
* @param from The address of the from asset.
* @param to The address of the to asset, asset should be in the added guard.
* @param sellAmount The amount of the from asset to sell.
* @param buyAmountMin The minimum amount of the to asset to buy.
* @param data The data for the swap.
* @dev Rebalance the assets.
*/
function rebalance(
address ammProtocol,
address from,
address to,
uint256 sellAmount,
uint256 buyAmountMin,
bytes memory data
) external;
/**
* @notice Add liquidity to the AMM provider.
* @dev Add liquidity to the AMM provider.
* @param ammProtocol The address of the AMM provider.
* @param data The data for the add liquidity.
* @dev Only the asset manager can execute it.
*/
function addLiquidity(
address ammProtocol,
address token0,
uint256 amount0,
address token1,
uint256 amount1,
bytes memory data
) external;
/**
* @notice Remove liquidity from the AMM provider.
* @dev Remove liquidity from the AMM provider.
* @param ammProtocol The address of the AMM provider.
* @param data The data for the remove liquidity.
* @dev Only the asset manager can execute it.
*/
function removeLiquidity(address ammProtocol, bytes memory data) external;
/**
* @notice Claim fees from the AMM provider.
* @dev Claim fees from the AMM provider.
* @param ammProtocol The address of the AMM provider.
* @param data The data for the claim fees.
* @dev Only the asset manager can execute it.
*/
function claimAMMFees(address ammProtocol, bytes memory data) external;
/**
* @notice Get the liquidity of the AMM provider.
* @dev Get the liquidity of the AMM provider.
* @param ammProtocol The address of the AMM provider.
* @param data The data for the get liquidity.
* @dev Only the asset manager can execute it.
*/
function getLiquidity(address ammProtocol, bytes memory data) external view returns (uint256);
/**
* @notice Disable the rebalance until the timestamp.
* @dev Disable the rebalance until the timestamp.
* @param timestamp The timestamp to disable the rebalance until.
*/
function disableRebalanceUntilTimestamp(uint256 timestamp) external;
/**
* @notice Add the lending providers.
* @param lendingProtocolAddresses The addresses of the lending providers.
* @dev Add the lending providers.
*/
function addLendingProtocols(address[] memory lendingProtocolAddresses) external;
/**
* @notice Remove the lending providers.
* @dev Remove the lending providers.
* @param lendingProtocolAddresses The addresses of the lending providers.
* @dev Remove the lending providers.
*/
function removeLendingProtocols(address[] memory lendingProtocolAddresses) external;
/**
* @notice Add the staking providers.
* @dev Add the staking providers.
* @param stakingProtocolAddresses The addresses of the staking providers.
* @dev Add the staking providers.
*/
function addStakingProtocols(address[] memory stakingProtocolAddresses) external;
/**
* @notice Remove the staking providers.
* @dev Remove the staking providers.
* @param stakingProtocolAddresses The addresses of the staking providers.
* @dev Remove the staking providers.
*/
function removeStakingProtocols(address[] memory stakingProtocolAddresses) external;
/**
* @notice Add the swap providers.
* @dev Add the swap providers.
* @param ammProtocolAddresses The addresses of the swap providers.
* @dev Add the swap providers.
*/
function addAMMProtocols(address[] memory ammProtocolAddresses) external;
/**
* @notice Remove the swap providers.
* @dev Remove the swap providers.
* @param ammProtocolAddresses The addresses of the swap providers.
* @dev Remove the swap providers.
*/
function removeAMMProtocols(address[] memory ammProtocolAddresses) external;
}
src/interfaces/IVault.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
// common errors
error AddressZero();
error AmountIsZero();
error TransferFailed();
error NotInitialized();
error AlreadyInitialized();
error InsufficientBalance();
// receiver errors
error ReceiverNotFound();
error ReceiverNameAlreadyExists();
error ReceiverImmutable();
error ReceiverPaymentCountZero();
error ReceiverTriggerError();
error ReceiverNotStartYet();
error ReceiverInDuration();
error ReceiverDurationTooShort();
error AssetAddressNotContract();
error NewReceiverProtectionOutOfRange();
error ReceiverProtectionNotEnded();
error PayMoreThanReceiverAmount();
error PayReceiverAmountTriggerEmpty();
error OnlyReceiver();
error AddingAssetsDisabled();
error AddingProtocolsDisabled();
error OwnerAndAssetManagerMustDiffer();
/**
* @title Bitty Vault
* @notice Multi-sigs + Bitty Vault ensure your safe.
*
* Vault is not going to fix the safety of private key management, the best practise of private key management is multi-sigs.
*
* Vault is going to implement:
* 1. Familly/Company weekly/monthly spending.
* 2. Money for kids get in the future.
* 3. Investment avoiding scams assets by Bitty Guard.
* 4. Yielding avoid high risk lending/staking protocols by Bitty Guard.
* 5. Trading avoid scam protocols by Bitty Guard.
* 6. Stay away from frontend supply chain attacks(which is the biggest security issue in DeFi) when interating with trading/lending/staking protocols.
*/
interface IVault {
event AssetsLocked();
event ProtocolsLocked();
event ReceiverAdded(string indexed name, Receiver receiver);
event ReceiverUpdated(string indexed name, Receiver receiver);
event ReceiverRemoved(string indexed name);
event ReceiverAddressChanged(
string indexed name, address indexed oldReceiverAddress, address indexed newReceiverAddress
);
event NewReceiverProtectionSet(uint256 protectionDuration);
event ReceiverPaid(
string indexed name,
address indexed receiverAddress,
address indexed assetAddress,
uint256 amount,
uint8 remainingPaymentCount
);
struct Receiver {
// a more complex receiver contract can be implemented for advanced users out of this repo
address receiverAddress;
// if this is not address(0), then only this trigger address can trigger the payment
address trigger;
address assetAddress;
uint256 amount;
uint8 paymentCount;
uint256 startTimestamp;
uint256 durationTimestamp;
bool isImmutable;
// if this is true, then the payment will not revert if the balance is insufficient
bool payWithInsufficientBalance;
}
/**
* @notice set the name of the vault.
* @param name the name of the vault.
* @dev Only the owner can set the name of the vault.
*/
function setName(string memory name) external;
/**
* @notice add a receiver.
* @param name Unique name; reverts if a receiver with this name already exists (use updateReceiver or removeReceiver first).
* @param receiver receiver.
*/
function addReceiver(string memory name, Receiver calldata receiver) external;
/**
*
* @param name name of the receiver.
* @param receiver the updated receiver.
*/
function updateReceiver(string memory name, Receiver calldata receiver) external;
/**
* @notice change the receiver address.
* @param name name of the receiver.
* @param newReceiverAddress new receiver address.
* @dev Only the old receiver address can execute it.
*/
function changeReceiverAddress(string memory name, address newReceiverAddress) external;
/**
* @notice remove a recipient.
* @param name the name of the recipient.
*/
function removeReceiver(string memory name) external;
/**
* @notice set the new receiver protection.
* @param newReceiverProtection the new receiver protection.
*/
function setNewReceiverProtection(uint256 newReceiverProtection) external;
/**
* @notice Human-readable name set at deploy time to distinguish vaults with the same owner.
*/
function name() external view returns (string memory);
/**
* @notice Add the assets to the vault.
* @dev Add the assets to the vault.
* @param assetAddresses The addresses of the assets.
*/
function addAssets(address[] memory assetAddresses) external;
/**
* @notice Disable the adding assets.
* @dev Disable the adding assets.
*
* After disabling, the assets can not be added, but can be removed.
* It would be useful when owner try to limit the fund to just buy limited assets like wbtc, weth.
*/
function disableAddingAssets() external;
/**
* @notice Check if the adding assets is disabled.
* @dev Check if the adding assets is disabled.
* @return bool True if the adding assets is disabled, false otherwise.
*/
function isAddingAssetsDisabled() external view returns (bool);
/**
* @notice Disable the adding protocols.
* @dev Disable the adding protocols.
*
* After disabling, the protocols can not be added, but can be removed.
* It would be useful when owner try to limit the fund to just buy limited protocols like aave, curve.
*/
function disableAddingProtocols() external;
/**
* @notice Check if the adding protocols is disabled.
* @dev Check if the adding protocols is disabled.
* @return bool True if the adding protocols is disabled, false otherwise.
*/
function isAddingProtocolsDisabled() external view returns (bool);
/**
* @notice Remove the assets from the vault.
* @dev Remove the assets from the vault.
* @param assetAddresses The addresses of the assets.
*/
function removeAssets(address[] memory assetAddresses) external;
/**
* @notice Get the assets of the vault.
* @dev Get the assets of the vault.
* @return The addresses of the assets.
*/
function getAssets() external view returns (address[] memory);
/**
* @notice Get the stable coins of the vault.
* @dev Get the stable coins of the vault.
* @return The addresses of the stable coins.
*/
function getStableCoins() external view returns (address[] memory);
/**
* @notice Pay the receiver with the full amount.
* @dev Pay the receiver.
* @param name the name of the recipient.
*/
function payReceiver(string memory name) external;
/**
*
* @param name the name of the recipient.
* @param amount the amount of the payment.
* @dev Trigger must be set to execute it, otherwise it may cause some unexpected issues.
*/
function payReceiverAmount(string memory name, uint256 amount) external;
}
src/logic/AssetManagerLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import {IGuard, NotRegistered, Deprecated} from "guard-contracts/src/interfaces/IGuard.sol";
import {
IAssetManager,
DisableRebalanceUntilTimestampTooEarly,
RebalanceDisabled,
RebalanceInMinimalTime,
RebalanceMaxAmount,
SellAmountMismatch,
BuyAmountNotEnough,
MinimalBalanceNotMet,
InvalidLendingProtocol,
InvalidStakingProtocol,
InvalidAMMProtocol,
InvalidSwapData
} from "../interfaces/IAssetManager.sol";
import {IProtocol} from "protocol-contracts/src/interfaces/IProtocol.sol";
import {ILendingProtocol} from "protocol-contracts/src/interfaces/ILendingProtocol.sol";
import {IStakingProtocol} from "protocol-contracts/src/interfaces/IStakingProtocol.sol";
import {IAMMProtocol} from "protocol-contracts/src/interfaces/IAMMProtocol.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {Address} from "openzeppelin-contracts/contracts/utils/Address.sol";
import {Clones} from "openzeppelin-contracts/contracts/proxy/Clones.sol";
import {
AddressZero,
AmountIsZero,
InsufficientBalance,
NotInitialized,
AlreadyInitialized,
AddingProtocolsDisabled
} from "../interfaces/IVault.sol";
import {WETH} from "solmate/tokens/WETH.sol";
import {ETHBalanceNotEnough, WETHBalanceNotEnough} from "../interfaces/IAssetManager.sol";
import {AssetManagerStorage, VaultStorage} from "./Storages.sol";
import {VaultLogic} from "./VaultLogic.sol";
library AssetManagerLogic {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
using Clones for address;
modifier onlyInitialized(AssetManagerStorage storage logicStorage) {
if (!logicStorage.isInitialized) {
revert NotInitialized();
}
_;
}
modifier onlyNotInitialized(AssetManagerStorage storage logicStorage) {
if (logicStorage.isInitialized) {
revert AlreadyInitialized();
}
_;
}
modifier onlyAddingProtocolsEnabled(AssetManagerStorage storage logicStorage) {
if (logicStorage.addingProtocolsDisabled) {
revert AddingProtocolsDisabled();
}
_;
}
function initialize(AssetManagerStorage storage logicStorage, address guardAddress, address wethAddress)
external
onlyNotInitialized(logicStorage)
{
if (guardAddress == address(0)) {
revert AddressZero();
}
logicStorage.guard = IGuard(guardAddress);
logicStorage.weth = wethAddress;
logicStorage.isInitialized = true;
}
function _cloneProtocol(AssetManagerStorage storage logicStorage, address protocol)
private
onlyInitialized(logicStorage)
returns (address clonedProtocol)
{
clonedProtocol = logicStorage.clonedProtocols[protocol];
if (clonedProtocol != address(0)) {
return clonedProtocol;
}
clonedProtocol = protocol.clone();
IProtocol(clonedProtocol).initialize(address(this));
logicStorage.clonedProtocols[protocol] = clonedProtocol;
return clonedProtocol;
}
function ETHToWETH(AssetManagerStorage storage logicStorage, uint256 amount)
external
onlyInitialized(logicStorage)
{
uint256 ethBalance = address(this).balance;
if (ethBalance < amount) {
revert ETHBalanceNotEnough();
}
WETH(payable(logicStorage.weth)).deposit{value: amount}();
}
function WETHToETH(AssetManagerStorage storage logicStorage, uint256 amount)
external
onlyInitialized(logicStorage)
{
uint256 wethBalance = IERC20(logicStorage.weth).balanceOf(address(this));
if (wethBalance < amount) {
revert WETHBalanceNotEnough();
}
WETH(payable(logicStorage.weth)).withdraw(amount);
}
function setRebalanceConfig(
AssetManagerStorage storage logicStorage,
address assetAddress,
IAssetManager.RebalanceConfig memory assetConfig
) external onlyInitialized(logicStorage) {
if (assetAddress == address(0)) {
revert AddressZero();
}
logicStorage.rebalanceConfigs[assetAddress] = assetConfig;
}
function supply(
AssetManagerStorage storage logicStorage,
address lendingProtocol,
address assetAddress,
uint256 amount
) external onlyInitialized(logicStorage) {
if (!logicStorage.lendingProtocols.contains(lendingProtocol)) {
revert InvalidLendingProtocol();
}
if (logicStorage.guard.isLendingProtocolDeprecated(lendingProtocol)) {
revert Deprecated();
}
if (assetAddress == address(0)) {
revert AddressZero();
}
if (amount == 0) {
revert AmountIsZero();
}
lendingProtocol = _cloneProtocol(logicStorage, lendingProtocol);
IERC20(assetAddress).safeIncreaseAllowance(lendingProtocol, amount);
ILendingProtocol(lendingProtocol).supply(assetAddress, amount);
uint256 remaining = IERC20(assetAddress).allowance(address(this), lendingProtocol);
if (remaining > 0) {
IERC20(assetAddress).safeDecreaseAllowance(lendingProtocol, remaining);
}
}
function withdraw(
AssetManagerStorage storage logicStorage,
address lendingProtocol,
address assetAddress,
uint256 amount
) external onlyInitialized(logicStorage) {
if (!logicStorage.lendingProtocols.contains(lendingProtocol)) {
revert InvalidLendingProtocol();
}
if (assetAddress == address(0)) {
revert AddressZero();
}
if (amount == 0) {
revert AmountIsZero();
}
lendingProtocol = _cloneProtocol(logicStorage, lendingProtocol);
uint256 supplyAmount = ILendingProtocol(lendingProtocol).getSuppliedBalance(assetAddress);
if (supplyAmount < amount) {
revert InsufficientBalance();
}
ILendingProtocol(lendingProtocol).withdraw(assetAddress, amount);
}
function getSuppliedBalance(AssetManagerStorage storage logicStorage, address lendingProtocol, address assetAddress)
external
view
onlyInitialized(logicStorage)
returns (uint256)
{
if (!logicStorage.lendingProtocols.contains(lendingProtocol)) {
revert InvalidLendingProtocol();
}
address _clonedProtocol = logicStorage.clonedProtocols[lendingProtocol];
if (_clonedProtocol == address(0)) {
return 0;
}
return ILendingProtocol(_clonedProtocol).getSuppliedBalance(assetAddress);
}
function stake(
AssetManagerStorage storage logicStorage,
address stakingProtocol,
address assetAddress,
uint256 amount
) external onlyInitialized(logicStorage) {
if (!logicStorage.stakingProtocols.contains(stakingProtocol)) {
revert InvalidStakingProtocol();
}
if (logicStorage.guard.isStakingProtocolDeprecated(stakingProtocol)) {
revert Deprecated();
}
if (assetAddress == address(0)) {
revert AddressZero();
}
if (amount == 0) {
revert AmountIsZero();
}
stakingProtocol = _cloneProtocol(logicStorage, stakingProtocol);
IERC20(assetAddress).safeIncreaseAllowance(stakingProtocol, amount);
IStakingProtocol(stakingProtocol).stake(assetAddress, amount);
uint256 remaining = IERC20(assetAddress).allowance(address(this), stakingProtocol);
if (remaining > 0) {
IERC20(assetAddress).safeDecreaseAllowance(stakingProtocol, remaining);
}
}
function unstake(
AssetManagerStorage storage logicStorage,
address stakingProtocol,
address assetAddress,
uint256 amount
) external onlyInitialized(logicStorage) {
if (!logicStorage.stakingProtocols.contains(stakingProtocol)) {
revert InvalidStakingProtocol();
}
if (assetAddress == address(0)) {
revert AddressZero();
}
if (amount == 0) {
revert AmountIsZero();
}
stakingProtocol = _cloneProtocol(logicStorage, stakingProtocol);
uint256 stakingBalance = IStakingProtocol(stakingProtocol).getStakedBalance(assetAddress);
if (stakingBalance < amount) {
revert InsufficientBalance();
}
IStakingProtocol(stakingProtocol).unstake(assetAddress, amount);
}
function getStakedBalance(AssetManagerStorage storage logicStorage, address stakingProtocol, address assetAddress)
external
view
onlyInitialized(logicStorage)
returns (uint256)
{
if (!logicStorage.stakingProtocols.contains(stakingProtocol)) {
revert InvalidStakingProtocol();
}
if (assetAddress == address(0)) {
revert AddressZero();
}
address _clonedProtocol = logicStorage.clonedProtocols[stakingProtocol];
if (_clonedProtocol == address(0)) {
return 0;
}
return IStakingProtocol(_clonedProtocol).getStakedBalance(assetAddress);
}
function getUnstakeRequestIds(AssetManagerStorage storage logicStorage, address stakingProtocol)
external
view
onlyInitialized(logicStorage)
returns (uint256[] memory)
{
if (!logicStorage.stakingProtocols.contains(stakingProtocol)) {
revert InvalidStakingProtocol();
}
address _clonedProtocol = logicStorage.clonedProtocols[stakingProtocol];
if (_clonedProtocol == address(0)) {
return new uint256[](0);
}
return IStakingProtocol(_clonedProtocol).getUnstakeRequestIds();
}
function claimUnstaked(
AssetManagerStorage storage logicStorage,
address stakingProtocol,
uint256[] memory requestIds
) external onlyInitialized(logicStorage) {
if (!logicStorage.stakingProtocols.contains(stakingProtocol)) {
revert InvalidStakingProtocol();
}
if (requestIds.length == 0) {
return;
}
stakingProtocol = _cloneProtocol(logicStorage, stakingProtocol);
IStakingProtocol(stakingProtocol).claimUnstaked(requestIds);
}
function _addressBalance(address assetAddress) private view returns (uint256) {
if (assetAddress == address(0)) {
revert AddressZero();
}
return IERC20(assetAddress).balanceOf(address(this));
}
function _checkAMMProtocol(AssetManagerStorage storage logicStorage, address ammProtocol) private view {
if (!logicStorage.ammProtocols.contains(ammProtocol)) {
revert InvalidAMMProtocol();
}
if (!logicStorage.guard.isAMMProtocolRegistered(ammProtocol)) {
revert NotRegistered();
}
}
function _checkRebalanceDisabledUntilTimestamp(AssetManagerStorage storage logicStorage) private view {
if (
logicStorage.rebalanceDisabledUntilTimestamp > 0
&& block.timestamp < logicStorage.rebalanceDisabledUntilTimestamp
) {
revert RebalanceDisabled();
}
}
function _validateRebalance(
AssetManagerStorage storage logicStorage,
VaultStorage storage vaultStorage,
address from,
address to,
uint256 sellAmount
)
private
view
returns (IAssetManager.RebalanceConfig memory configFrom, IAssetManager.RebalanceConfig memory configTo)
{
VaultLogic.checkAsset(vaultStorage, from);
VaultLogic.checkAsset(vaultStorage, to);
_checkRebalanceDisabledUntilTimestamp(logicStorage);
configFrom = logicStorage.rebalanceConfigs[from];
configTo = logicStorage.rebalanceConfigs[to];
if (
configFrom.maxAmount == 0 && configFrom.minimalBalance == 0 && configFrom.minimalDuration == 0
&& configTo.maxAmount == 0 && configTo.minimalBalance == 0 && configTo.minimalDuration == 0
) {
return (configFrom, configTo);
}
if (configFrom.maxAmount > 0 && configFrom.maxAmount < sellAmount) {
revert RebalanceMaxAmount();
}
uint256 fromBalance = _addressBalance(from);
if (configFrom.minimalBalance > 0) {
if (fromBalance < sellAmount || fromBalance - sellAmount < configFrom.minimalBalance) {
revert MinimalBalanceNotMet();
}
}
if (
(configFrom.minimalDuration > 0
&& logicStorage.lastRebalanceTimestamps[from] > 0
&& block.timestamp - logicStorage.lastRebalanceTimestamps[from] < configFrom.minimalDuration)
|| (configTo.minimalDuration > 0
&& logicStorage.lastRebalanceTimestamps[to] > 0
&& block.timestamp - logicStorage.lastRebalanceTimestamps[to] < configTo.minimalDuration)
) {
revert RebalanceInMinimalTime();
}
return (configFrom, configTo);
}
function _updateRebalanceTimestamps(
AssetManagerStorage storage logicStorage,
IAssetManager.RebalanceConfig memory assetConfigFrom,
IAssetManager.RebalanceConfig memory assetConfigTo,
address from,
address to
) private {
if (assetConfigFrom.minimalDuration > 0) {
logicStorage.lastRebalanceTimestamps[from] = block.timestamp;
}
if (assetConfigTo.minimalDuration > 0) {
logicStorage.lastRebalanceTimestamps[to] = block.timestamp;
}
}
function addLiquidity(
AssetManagerStorage storage logicStorage,
address ammProtocol,
address token0,
uint256 amount0,
address token1,
uint256 amount1,
bytes memory data
) external onlyInitialized(logicStorage) {
_checkAMMProtocol(logicStorage, ammProtocol);
address clone = logicStorage.clonedProtocols[ammProtocol];
if (clone == address(0)) {
revert InvalidAMMProtocol();
}
if (token0 != address(0) && amount0 > 0 && IERC20(token0).allowance(address(this), clone) < amount0) {
IERC20(token0).safeIncreaseAllowance(clone, amount0);
}
if (token1 != address(0) && amount1 > 0 && IERC20(token1).allowance(address(this), clone) < amount1) {
IERC20(token1).safeIncreaseAllowance(clone, amount1);
}
IAMMProtocol(clone).addLiquidity(data);
}
function removeLiquidity(AssetManagerStorage storage logicStorage, address ammProtocol, bytes memory data)
external
onlyInitialized(logicStorage)
{
_checkAMMProtocol(logicStorage, ammProtocol);
address clone = logicStorage.clonedProtocols[ammProtocol];
if (clone == address(0)) {
revert InvalidAMMProtocol();
}
IAMMProtocol(clone).removeLiquidity(data);
}
function claimAMMFees(AssetManagerStorage storage logicStorage, address ammProtocol, bytes memory data)
external
onlyInitialized(logicStorage)
{
_checkAMMProtocol(logicStorage, ammProtocol);
address clone = logicStorage.clonedProtocols[ammProtocol];
if (clone == address(0)) {
revert InvalidAMMProtocol();
}
IAMMProtocol(clone).claimAMMFees(data);
}
function rebalance(
AssetManagerStorage storage logicStorage,
VaultStorage storage vaultStorage,
address ammProtocol,
address from,
address to,
uint256 sellAmount,
uint256 buyAmountMin,
bytes memory data
) external onlyInitialized(logicStorage) {
_checkAMMProtocol(logicStorage, ammProtocol);
(IAssetManager.RebalanceConfig memory assetConfigFrom, IAssetManager.RebalanceConfig memory assetConfigTo) =
_validateRebalance(logicStorage, vaultStorage, from, to, sellAmount);
_swap(logicStorage, ammProtocol, from, sellAmount, to, buyAmountMin, data);
_updateRebalanceTimestamps(logicStorage, assetConfigFrom, assetConfigTo, from, to);
}
function _swap(
AssetManagerStorage storage logicStorage,
address ammProtocol,
address sellAssetAddress,
uint256 sellAmount,
address toAssetAddress,
uint256 buyAmountMin,
bytes memory data
) private {
if (sellAmount == 0 || buyAmountMin == 0) {
revert AmountIsZero();
}
(address sellToken_, uint256 sellAmount_, address buyToken_, uint256 buyAmountMin_) =
abi.decode(data, (address, uint256, address, uint256));
if (
sellToken_ != sellAssetAddress || sellAmount_ != sellAmount || buyToken_ != toAssetAddress
|| buyAmountMin_ != buyAmountMin
) {
revert InvalidSwapData();
}
uint256 sellAssetBalanceBefore = _addressBalance(sellAssetAddress);
if (sellAssetBalanceBefore < sellAmount) {
revert InsufficientBalance();
}
uint256 buyAssetBalanceBefore = _addressBalance(toAssetAddress);
ammProtocol = _cloneProtocol(logicStorage, ammProtocol);
if (IERC20(sellAssetAddress).allowance(address(this), ammProtocol) < sellAmount) {
IERC20(sellAssetAddress).safeIncreaseAllowance(ammProtocol, sellAmount);
}
IAMMProtocol(ammProtocol).swap(data);
uint256 sellAssetBalanceAfter = _addressBalance(sellAssetAddress);
if (sellAssetBalanceBefore - sellAssetBalanceAfter != sellAmount) {
revert SellAmountMismatch();
}
uint256 buyAssetBalanceAfter = _addressBalance(toAssetAddress);
if (buyAssetBalanceAfter - buyAssetBalanceBefore < buyAmountMin) {
revert BuyAmountNotEnough();
}
}
function disableRebalanceUntilTimestamp(AssetManagerStorage storage logicStorage, uint256 timestamp)
external
onlyInitialized(logicStorage)
{
if (timestamp == 0) {
return;
}
if (timestamp < logicStorage.rebalanceDisabledUntilTimestamp) {
revert DisableRebalanceUntilTimestampTooEarly();
}
logicStorage.rebalanceDisabledUntilTimestamp = timestamp;
}
function disableAddingProtocols(AssetManagerStorage storage logicStorage) external onlyInitialized(logicStorage) {
logicStorage.addingProtocolsDisabled = true;
}
function addLendingProtocols(AssetManagerStorage storage logicStorage, address[] memory lendingProtocolAddresses)
external
onlyAddingProtocolsEnabled(logicStorage)
onlyInitialized(logicStorage)
{
for (uint256 i = 0; i < lendingProtocolAddresses.length; i++) {
if (!logicStorage.guard.isLendingProtocolRegistered(lendingProtocolAddresses[i])) {
revert NotRegistered();
}
logicStorage.lendingProtocols.add(lendingProtocolAddresses[i]);
}
}
function addStakingProtocols(AssetManagerStorage storage logicStorage, address[] memory stakingProtocolAddresses)
external
onlyAddingProtocolsEnabled(logicStorage)
onlyInitialized(logicStorage)
{
for (uint256 i = 0; i < stakingProtocolAddresses.length; i++) {
if (!logicStorage.guard.isStakingProtocolRegistered(stakingProtocolAddresses[i])) {
revert NotRegistered();
}
logicStorage.stakingProtocols.add(stakingProtocolAddresses[i]);
}
}
function removeLendingProtocols(AssetManagerStorage storage logicStorage, address[] memory lendingProtocolAddresses)
external
onlyInitialized(logicStorage)
{
for (uint256 i = 0; i < lendingProtocolAddresses.length; i++) {
logicStorage.lendingProtocols.remove(lendingProtocolAddresses[i]);
}
}
function removeStakingProtocols(AssetManagerStorage storage logicStorage, address[] memory stakingProtocolAddresses)
external
onlyInitialized(logicStorage)
{
for (uint256 i = 0; i < stakingProtocolAddresses.length; i++) {
logicStorage.stakingProtocols.remove(stakingProtocolAddresses[i]);
}
}
function addAMMProtocols(AssetManagerStorage storage logicStorage, address[] memory ammProtocolAddresses)
external
onlyAddingProtocolsEnabled(logicStorage)
onlyInitialized(logicStorage)
{
for (uint256 i = 0; i < ammProtocolAddresses.length; i++) {
if (!logicStorage.guard.isAMMProtocolRegistered(ammProtocolAddresses[i])) {
revert NotRegistered();
}
logicStorage.ammProtocols.add(ammProtocolAddresses[i]);
}
}
function removeAMMProtocols(AssetManagerStorage storage logicStorage, address[] memory ammProtocolAddresses)
external
onlyInitialized(logicStorage)
{
for (uint256 i = 0; i < ammProtocolAddresses.length; i++) {
logicStorage.ammProtocols.remove(ammProtocolAddresses[i]);
}
}
function getLendingProtocols(AssetManagerStorage storage logicStorage) external view returns (address[] memory) {
return logicStorage.lendingProtocols.values();
}
function getStakingProtocols(AssetManagerStorage storage logicStorage) external view returns (address[] memory) {
return logicStorage.stakingProtocols.values();
}
function getAMMProtocols(AssetManagerStorage storage logicStorage) external view returns (address[] memory) {
return logicStorage.ammProtocols.values();
}
function getLiquidity(AssetManagerStorage storage logicStorage, address ammProtocol, bytes memory data)
external
view
returns (uint256)
{
_checkAMMProtocol(logicStorage, ammProtocol);
address clone = logicStorage.clonedProtocols[ammProtocol];
if (clone == address(0)) return 0;
return IAMMProtocol(clone).getLiquidity(data);
}
}
src/logic/Storages.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import {IAssetManager} from "../interfaces/IAssetManager.sol";
import {IGuard} from "guard-contracts/src/interfaces/IGuard.sol";
import {IVault} from "../interfaces/IVault.sol";
struct AssetManagerStorage {
bool isInitialized;
address weth;
mapping(address => address) clonedProtocols;
mapping(address => IAssetManager.RebalanceConfig) rebalanceConfigs;
mapping(address => uint256) lastRebalanceTimestamps;
EnumerableSet.AddressSet lendingProtocols;
EnumerableSet.AddressSet stakingProtocols;
EnumerableSet.AddressSet ammProtocols;
IGuard guard;
bool addingProtocolsDisabled;
uint256 rebalanceDisabledUntilTimestamp;
}
struct VaultStorage {
bool isInitialized;
mapping(string => IVault.Receiver) receivers;
mapping(string => uint256) lastReceiveTimestamps;
mapping(string => uint256) newReceiverProtectionTimestamps;
IGuard guard;
EnumerableSet.AddressSet assets;
EnumerableSet.AddressSet stableCoins;
bool addingAssetsDisabled;
uint256 newReceiverProtection;
}
src/logic/VaultLogic.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.34;
import {EnumerableSet} from "openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol";
import {
AlreadyInitialized,
AddressZero,
AmountIsZero,
NotInitialized,
InsufficientBalance
} from "../interfaces/IVault.sol";
import {IGuard, NotRegistered} from "guard-contracts/src/interfaces/IGuard.sol";
import {IERC20} from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {VaultStorage} from "./Storages.sol";
import {
IVault,
ReceiverNotFound,
ReceiverNameAlreadyExists,
ReceiverImmutable,
ReceiverPaymentCountZero,
ReceiverTriggerError,
ReceiverNotStartYet,
ReceiverInDuration,
AddingAssetsDisabled,
ReceiverDurationTooShort,
AssetAddressNotContract,
NewReceiverProtectionOutOfRange,
ReceiverProtectionNotEnded,
PayMoreThanReceiverAmount,
PayReceiverAmountTriggerEmpty
} from "../interfaces/IVault.sol";
library VaultLogic {
/**
* The vault will be drained by one attack in a very short time if no this protection.
* @dev this is a protection for the vault.
*/
uint256 constant RECEIVER_MINIMAL_DURATION = 1 days;
/**
* To protect the vault owner, the longer it is, the harder to attack the owner.
* The RECEIVER_NEW_PROTECTION_MIN is actually RECEIVER_MINIMAL_DURATION.
* @dev this is a protection for the vault.
*/
uint256 constant RECEIVER_NEW_PROTECTION_MAX = 30 days;
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
modifier onlyInitialized(VaultStorage storage vaultStorage) {
_onlyInitialized(vaultStorage);
_;
}
function _onlyInitialized(VaultStorage storage vaultStorage) private view {
if (!vaultStorage.isInitialized) {
revert NotInitialized();
}
}
modifier onlyNotInitialized(VaultStorage storage vaultStorage) {
_onlyNotInitialized(vaultStorage);
_;
}
function _onlyNotInitialized(VaultStorage storage vaultStorage) private view {
if (vaultStorage.isInitialized) {
revert AlreadyInitialized();
}
}
function initialize(VaultStorage storage vaultStorage, address guardAddress)
external
onlyNotInitialized(vaultStorage)
{
vaultStorage.guard = IGuard(guardAddress);
vaultStorage.isInitialized = true;
}
function addReceiver(VaultStorage storage vaultStorage, string memory name, IVault.Receiver memory receiver)
external
onlyInitialized(vaultStorage)
{
if (vaultStorage.receivers[name].amount != 0) {
revert ReceiverNameAlreadyExists();
}
_checkReceiver(receiver);
vaultStorage.receivers[name] = receiver;
if (vaultStorage.newReceiverProtection != 0) {
vaultStorage.newReceiverProtectionTimestamps[name] = block.timestamp + vaultStorage.newReceiverProtection;
}
emit IVault.ReceiverAdded(name, receiver);
}
function getReceiverAddress(VaultStorage storage vaultStorage, string memory name) external view returns (address) {
return vaultStorage.receivers[name].receiverAddress;
}
function changeReceiverAddress(VaultStorage storage vaultStorage, string memory name, address newReceiverAddress)
external
onlyInitialized(vaultStorage)
{
IVault.Receiver storage receiver = vaultStorage.receivers[name];
if (receiver.isImmutable) {
revert ReceiverImmutable();
}
if (newReceiverAddress == address(0)) {
revert AddressZero();
}
address oldReceiverAddress = receiver.receiverAddress;
receiver.receiverAddress = newReceiverAddress;
emit IVault.ReceiverAddressChanged(name, oldReceiverAddress, newReceiverAddress);
}
function updateReceiver(VaultStorage storage vaultStorage, string memory name, IVault.Receiver memory receiver)
external
onlyInitialized(vaultStorage)
{
IVault.Receiver memory existing = vaultStorage.receivers[name];
if (existing.receiverAddress == address(0)) {
revert ReceiverNotFound();
}
if (existing.isImmutable) {
revert ReceiverImmutable();
}
_checkReceiver(receiver);
vaultStorage.receivers[name] = receiver;
emit IVault.ReceiverUpdated(name, receiver);
}
function _checkReceiver(IVault.Receiver memory receiver) internal view {
if (receiver.receiverAddress == address(0)) {
revert AddressZero();
}
if (receiver.assetAddress.code.length == 0) {
revert AssetAddressNotContract();
}
if (receiver.amount == 0) {
revert AmountIsZero();
}
if (receiver.paymentCount == 0) {
revert ReceiverPaymentCountZero();
}
if (receiver.paymentCount > 1 && receiver.durationTimestamp < RECEIVER_MINIMAL_DURATION) {
revert ReceiverDurationTooShort();
}
}
function removeReceiver(VaultStorage storage vaultStorage, string memory name)
external
onlyInitialized(vaultStorage)
{
delete vaultStorage.receivers[name];
delete vaultStorage.newReceiverProtectionTimestamps[name];
emit IVault.ReceiverRemoved(name);
}
function setNewReceiverProtection(VaultStorage storage vaultStorage, uint256 newReceiverProtection)
external
onlyInitialized(vaultStorage)
{
if (newReceiverProtection > RECEIVER_NEW_PROTECTION_MAX) {
revert NewReceiverProtectionOutOfRange();
}
vaultStorage.newReceiverProtection = newReceiverProtection;
emit IVault.NewReceiverProtectionSet(newReceiverProtection);
}
function payReceiver(VaultStorage storage vaultStorage, string memory name) external {
IVault.Receiver storage receiver = vaultStorage.receivers[name];
if (receiver.trigger != address(0) && msg.sender != receiver.trigger) {
revert ReceiverTriggerError();
}
_payReceiver(vaultStorage, receiver, name);
}
function payReceiverAmount(VaultStorage storage vaultStorage, string memory name, uint256 amount) external {
IVault.Receiver storage receiver = vaultStorage.receivers[name];
if (receiver.amount < amount) {
revert PayMoreThanReceiverAmount();
}
if (receiver.trigger == address(0)) {
revert PayReceiverAmountTriggerEmpty();
}
_payReceiver(vaultStorage, receiver, name);
}
function _payReceiver(VaultStorage storage vaultStorage, IVault.Receiver storage receiver, string memory name)
internal
{
if (receiver.amount == 0) {
revert ReceiverNotFound();
}
if (receiver.paymentCount == 0) {
revert ReceiverPaymentCountZero();
}
if (receiver.startTimestamp > block.timestamp) {
revert ReceiverNotStartYet();
}
if (
receiver.durationTimestamp != 0 && vaultStorage.lastReceiveTimestamps[name] > 0
&& block.timestamp - vaultStorage.lastReceiveTimestamps[name] < receiver.durationTimestamp
) {
revert ReceiverInDuration();
}
if (vaultStorage.newReceiverProtectionTimestamps[name] > 0) {
if (block.timestamp < vaultStorage.newReceiverProtectionTimestamps[name]) {
revert ReceiverProtectionNotEnded();
} else {
delete vaultStorage.newReceiverProtectionTimestamps[name];
}
}
vaultStorage.lastReceiveTimestamps[name] = block.timestamp;
receiver.paymentCount = receiver.paymentCount - 1;
uint256 paidAmount = _transferMoney(
receiver.assetAddress, receiver.amount, receiver.receiverAddress, receiver.payWithInsufficientBalance
);
emit IVault.ReceiverPaid(
name, receiver.receiverAddress, receiver.assetAddress, paidAmount, receiver.paymentCount
);
}
function _transferMoney(
address erc20Address,
uint256 amount,
address receiverAddress,
bool payWithInsufficientBalance
) internal returns (uint256 paidAmount) {
IERC20 asset = IERC20(erc20Address);
uint256 balance = asset.balanceOf(address(this));
if (!payWithInsufficientBalance && balance < amount) {
revert InsufficientBalance();
}
paidAmount = balance < amount ? balance : amount;
asset.safeTransfer(receiverAddress, paidAmount);
}
function addAssets(VaultStorage storage vaultStorage, address[] memory assetAddresses)
external
onlyInitialized(vaultStorage)
{
if (vaultStorage.addingAssetsDisabled) {
revert AddingAssetsDisabled();
}
for (uint256 i = 0; i < assetAddresses.length; i++) {
if (vaultStorage.guard.isAssetRegistered(assetAddresses[i])) {
vaultStorage.assets.add(assetAddresses[i]);
} else if (vaultStorage.guard.isStableCoinRegistered(assetAddresses[i])) {
vaultStorage.stableCoins.add(assetAddresses[i]);
} else {
revert NotRegistered();
}
}
}
function disableAddingAssets(VaultStorage storage vaultStorage) external onlyInitialized(vaultStorage) {
vaultStorage.addingAssetsDisabled = true;
}
function removeAssets(VaultStorage storage vaultStorage, address[] memory assetAddresses)
external
onlyInitialized(vaultStorage)
{
for (uint256 i = 0; i < assetAddresses.length; i++) {
if (vaultStorage.assets.contains(assetAddresses[i])) {
vaultStorage.assets.remove(assetAddresses[i]);
} else if (vaultStorage.stableCoins.contains(assetAddresses[i])) {
vaultStorage.stableCoins.remove(assetAddresses[i]);
} else {
revert NotRegistered();
}
}
}
function getAssets(VaultStorage storage vaultStorage) external view returns (address[] memory) {
return vaultStorage.assets.values();
}
function getStableCoins(VaultStorage storage vaultStorage) external view returns (address[] memory) {
return vaultStorage.stableCoins.values();
}
function checkAsset(VaultStorage storage logicStorage, address assetAddress) external view {
if (logicStorage.assets.contains(assetAddress) || logicStorage.stableCoins.contains(assetAddress)) {
return;
}
revert NotRegistered();
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/BittyVault.sol": {
"VaultLogic": "0xfb20542a2fea887578d598e102e14d0e86db8291",
"AssetManagerLogic": "0xd76ccd236eec113f44a6c404226006fdaf0f4ff5"
}
},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"guard-contracts/=lib/guard-contracts/",
"protocol-contracts/=lib/protocol-contracts/",
"solmate/=lib/solmate/src/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/guard-contracts/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.