Description:
Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"contracts/infinite-proxy/interfaces/IProxy.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IProxy {
function setAdmin(address newAdmin_) external;
function setDummyImplementation(address newDummyImplementation_) external;
function addImplementation(
address implementation_,
bytes4[] calldata sigs_
) external;
function removeImplementation(address implementation_) external;
function getAdmin() external view returns (address);
function getDummyImplementation() external view returns (address);
function getImplementationSigs(
address impl_
) external view returns (bytes4[] memory);
function getSigsImplementation(bytes4 sig_) external view returns (address);
function readFromStorage(
bytes32 slot_
) external view returns (uint256 result_);
}
"
},
"contracts/vault/common/interfaces/IDSA.sol": {
"content": "//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IDSA {
function cast(
string[] calldata _targetNames,
bytes[] calldata _datas,
address _origin
) external payable returns (bytes32);
}
"
},
"contracts/vault/common/interfaces/IToken.sol": {
"content": "//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IToken {
function approve(address, uint256) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
function totalSupply() external view returns (uint);
function allowance(
address owner,
address spender
) external view returns (uint256);
}
"
},
"contracts/vault/common/interfaces/IVaultV3.sol": {
"content": "//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
interface IVaultV3 {
function readFromStorage(bytes32 slot_) external view returns (uint256 result_);
function getWithdrawFee(uint256 amount_) external view returns (uint256);
function getProtocolRatio(uint8 protocolId_) external view returns (uint256 ratio_);
function getNetAssets() external view returns (uint256 totalAssets_, uint256 totalDebt_, uint256 netAssets_, uint256 aggregatedRatio_);
function getTokenExchangeRate(address tokenAddress_) external view returns (uint256 exchangeRate_);
}
"
},
"contracts/vault/common/variables/constants.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
contract Constants {
address internal constant _TEAM_MULTISIG = 0x4F6F977aCDD1177DCD81aB83074855EcB9C2D49e;
address internal constant _INSTA_INDEX_ADDRESS = 0x2971AdFa57b20E5a416aE5a708A8655A9c74f723;
address internal constant _USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // 6 decimals
}
"
},
"contracts/vault/common/variables/primaryHelpers.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import {Constants} from "./constants.sol";
import {StorageVariables} from "./storageVariables.sol";
import {IProxy} from "../../../infinite-proxy/interfaces/IProxy.sol";
import {Structs} from "./structs.sol";
import {IVaultV3} from "../interfaces/IVaultV3.sol";
import {IToken} from "../interfaces/IToken.sol";
contract PrimaryHelpers is Constants, StorageVariables {
using Structs for Structs.AuthTypes;
/***********************************|
| ERRORS |
|__________________________________*/
error Helpers__UnsupportedProtocolId();
error Helpers__NotRebalancer();
error Helpers__NotPrimaryRebalancer();
error Helpers__Reentrant();
error Helpers__NotAuth();
error Helpers__InvalidAuthType();
error Helpers__NotEnoughSwapLimit();
function _auth(
Structs.AuthTypes authType_,
address account_
) internal view {
address admin_ = IProxy(address(this)).getAdmin();
if (authType_ == Structs.AuthTypes.Owner) {
if (admin_ != account_) {
revert Helpers__NotAuth();
}
} else if (authType_ == Structs.AuthTypes.SecondaryAuth) {
if (
secondaryAuth != account_ &&
admin_ != account_
) {
revert Helpers__NotAuth();
}
} else if (authType_ == Structs.AuthTypes.PrimaryRebalancer) {
if (!isPrimaryRebalancer[account_] && admin_ != account_) {
revert Helpers__NotAuth();
}
} else if (authType_ == Structs.AuthTypes.Rebalancer) {
if (
!isSecondaryRebalancer[account_] &&
!isPrimaryRebalancer[account_] &&
admin_ != account_
) {
revert Helpers__NotAuth();
}
} else {
revert Helpers__InvalidAuthType();
}
}
/***********************************|
| MODIFIERS |
|__________________________________*/
/// @notice reverts if msg.sender is not auth.
modifier onlyAuth() {
_auth(Structs.AuthTypes.Owner, msg.sender);
_;
}
/// @notice reverts if msg.sender is not secondaryAuth or auth
modifier onlySecondaryAuth() {
_auth(Structs.AuthTypes.SecondaryAuth, msg.sender);
_;
}
/// @notice reverts if msg.sender is not rebalancer or auth
modifier onlyRebalancer() {
_auth(Structs.AuthTypes.Rebalancer, msg.sender);
_;
}
/// @notice reverts if msg.sender is not primaryRebalancer or auth
modifier onlyPrimaryRebalancer() {
_auth(Structs.AuthTypes.PrimaryRebalancer, msg.sender);
_;
}
/**
* @dev reentrancy gaurd.
*/
modifier nonReentrant() {
if (_status == 2) revert Helpers__Reentrant();
_status = 2;
_;
_status = 1;
}
/// @notice Implements a method to read uint256 data from storage at a bytes32 storage slot key.
function readFromStorage(
bytes32 slot_
) public view returns (uint256 result_) {
assembly {
result_ := sload(slot_) // read value from the storage slot
}
}
function _getAmountInUsd(
address tokenAddress_,
uint256 amount_,
uint256 exchangeRate_
) internal view returns (uint256 amountInUsd_) {
uint256 tokenDecimals_ = IToken(tokenAddress_).decimals();
amountInUsd_ =
(amount_ * exchangeRate_) /
10 ** (2 * tokenDecimals_ - 6);
}
/// @notice Checks the available swap limit.
/// @return availableSwapLimit_ The available swap limit.
function checkAvailableSwapLimit()
public
view
returns (uint256 availableSwapLimit_)
{
uint256 timeElapsed_ = block.timestamp - lastSwapTimestamp;
availableSwapLimit_ = availableSwapLimit;
/// @dev If time has elapsed, calculate the refill.
if (timeElapsed_ > 0) {
uint256 refill_ = (timeElapsed_ * maxDailySwapLimit) /
(24 * 60 * 60);
availableSwapLimit_ += refill_;
availableSwapLimit_ = availableSwapLimit_ > maxDailySwapLimit
? maxDailySwapLimit
: availableSwapLimit_;
}
}
function _handleSwapLimitCheck(uint256 amount_) internal {
availableSwapLimit = checkAvailableSwapLimit();
if (availableSwapLimit < amount_) {
revert Helpers__NotEnoughSwapLimit();
}
availableSwapLimit -= amount_;
lastSwapTimestamp = block.timestamp;
}
}
"
},
"contracts/vault/common/variables/storageVariables.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import {IDSA} from "../../common/interfaces/IDSA.sol";
import {Structs} from "../../common/variables/structs.sol";
contract StorageVariables {
using Structs for Structs.FluidVaultDetails;
/****************************************************************************|
| @notice Protocol IDs |
| // AAVE-V3 : 1 (SUSDe, USDe, USDC, USDT, GHO, USDS) |
| // FLUID-WSTUSR-USDC : 2 (wstUSR, USDC) |
| // FLUID-WSTUSR-USDT : 3 (wstUSR, USDT) |
| // FLUID-WSTUSR-GHO : 4 (wstUSR, GHO) |
| // FLUID-SUSDE-USDC : 5 (SUSDe, USDC) |
| // FLUID-SUSDE-USDT : 6 (SUSDe, USDT) |
| // FLUID-SUSDE-GHO : 7 (SUSDe, GHO) |
| // FLUID-syrupUSDC-USDC : 8 (syrupUSDC, USDC) |
| // FLUID-syrupUSDC-USDT : 9 (syrupUSDC, USDT) |
| // FLUID-syrupUSDC-GHO : 10 (syrupUSDC, GHO) |
|___________________________________________________________________________*/
/***********************************|
| STATE VARIABLES |
|__________________________________*/
// 1: open
// 2: closed
uint8 internal _status;
IDSA public vaultDSA;
/// @notice Secondary auth that only has the power to reduce max risk ratio.
address public secondaryAuth;
/// @notice Current exchange price.
uint256 public exchangePrice;
/// @notice Last timestamp the exchange price was updated
/// @dev This is used to calculate the rate of the vault
uint256 public lastExchangePriceUpdatedAt;
/// @notice Mapping to store allowed primary rebalancers
/// @dev Primary rebalancers are the ones that can perform swap related actions
/// Modifiable by auth
mapping(address => bool) public isPrimaryRebalancer;
/// @notice Mapping to store allowed secondary rebalancers
/// @dev Secondary rebalancers are the ones that can perform all rebalancer actions except swap related actions
/// Modifiable by auth
mapping(address => bool) public isSecondaryRebalancer;
// Mapping of protocol id => max risk ratio, scaled to use basis points. i.e. 1e4 = 100%, 1e2 = 1%
// 1: AAVE-V3
// 2: FLUID-WSTUSR-USDC
// 3: FLUID-WSTUSR-USDT
// 4: FLUID-WSTUSR-GHO
// 5: FLUID-SUSDE-USDC
// 6: FLUID-SUSDE-USDT
// 7: FLUID-SUSDE-GHO
mapping(uint8 => uint256) public maxRiskRatio;
// Max aggregated risk ratio of the vault that can be reached, scaled to use basis points. i.e. 1e4 = 100%, 1e2 = 1%
// i.e. 1e4 = 100%, 1e2 = 1%
uint256 public aggrMaxVaultRatio;
/// @notice withdraw fee is either amount in percentage or absolute minimum.
/// @dev This var defines the percentage in basis points. i.e. 1e4 = 100%, 1e2 = 1%
/// Modifiable by owner
uint256 public withdrawalFeePercentage;
/// @notice withdraw fee is either amount in percentage or absolute minimum. This var defines the absolute minimum
/// this number is given in decimals for the respective asset of the vault.
/// Modifiable by owner
uint256 public withdrawFeeAbsoluteMin; // in underlying base asset, i.e. USDT
// charge from the profits, scaled to use basis points. i.e. 1e4 = 100%, 1e2 = 1%
uint256 public revenueFeePercentage;
/// @notice Stores reserves for the vault (previously revenue)
/// @dev Reserves - also serve a purpose to cover unknown users losses
/// @dev Reserves can be negative if there is not enough revenue to cover the losses
int256 public reserves;
/// @notice Min APR for the vault. This is the minimum APR the vault must yield.
/// @dev Can be modified by the owner / secondary auth.
uint256 public minRate;
/// @notice Max APR for the vault. This is the maximum APR the vault can yield.
/// @dev Can be modified by the owner / secondary auth.
uint256 public maxRate;
/// @notice Revenue will be transffered to this address upon collection.
address public treasury;
///@notice Mapping to store fluid vault details
/// @dev Protocol ID => Fluid Vault Details (VaultAddress, NFTId)
/// 2: FLUID-WSTUSR-USDC
/// 3: FLUID-WSTUSR-USDT
/// 4: FLUID-WSTUSR-GHO
/// 5: FLUID-SUSDE-USDC
/// 6: FLUID-SUSDE-USDT
/// 7: FLUID-SUSDE-GHO
/// 8: FLUID-syrupUSDC-USDC
/// 9: FLUID-syrupUSDC-USDT
/// 10: FLUID-syrupUSDC-GHO
mapping(uint8 => Structs.FluidVaultDetails) public fluidVaultDetails;
/// @notice Daily swap limit of the vault.
/// @dev This is used to prevent abuse of the swap functionality.
/// @dev Team multisig can update this value.
uint256 public maxDailySwapLimit;
/// @notice Available swap limit of the vault.
/// @dev This is used to track the available swap limit of the vault.
uint256 public availableSwapLimit;
/// @notice Last timestamp the swap limit was recalculated.
uint256 public lastSwapTimestamp;
/// @notice Maximum loss in USD that can be incurred during a swap.
/// In Percentage, scaled to use the basis points. i.e. 1e4 = 100%, 1e2 = 1%
uint256 public maxSwapLossPercentage;
}
"
},
"contracts/vault/common/variables/structs.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
library Structs {
struct FluidVaultDetails {
address vaultAddress;
uint256 nftId;
}
enum AuthTypes {
Owner,
SecondaryAuth,
PrimaryRebalancer,
Rebalancer
}
}
"
},
"contracts/vault/common/variables/variablesBuffer.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
/// @title VariablesBuffer
/// @notice Allocates space of 151 slots to maintain storage
/// consistency with imported variables in VariablesPrimaryHelper.
contract VariablesBuffer {
uint[151] internal __buffergap;
}
"
},
"contracts/vault/common/variables/variablesBufferHelper.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
/// @title VariablesBufferHelper
/// @notice Buffer Helper for variables that imports all the primary
/// helpers from the storage slot 152.
import {VariablesBuffer} from "./variablesBuffer.sol";
import {PrimaryHelpers} from "./primaryHelpers.sol";
// Buffer & variables
contract VariablesBufferHelper is VariablesBuffer, PrimaryHelpers {}
"
},
"contracts/vault/modules/leverage-module/events.sol": {
"content": "//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
contract Events {
event LogLeverage(
uint8 indexed protocolId,
uint256 indexed debtFlashloanAmount,
uint256 route,
address debtToken,
address colToken
);
}
"
},
"contracts/vault/modules/leverage-module/interfaces.sol": {
"content": "//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
library LeverageStructs {
struct LeverageParams {
uint8 protocolId;
uint256 route;
address debtToken;
address colToken;
uint256 debtFlashloanAmount;
uint256 minBuyAmount;
string[] swapConnectors;
bytes[] swapCallDatas;
}
struct LeverageWithSwapVariables {
uint256 spellIndex;
uint256 spellsLength;
string[] targets;
bytes[] calldatas;
uint256 sellTokenExchangeRate;
uint256 buyTokenExchangeRate;
uint256 swapAmountInUsd;
uint256 beforeNetAssets;
uint256 afterNetAssets;
uint256 aggregatedRatio;
}
}
"
},
"contracts/vault/modules/leverage-module/main.sol": {
"content": "//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import {Events} from "./events.sol";
import {LeverageStructs} from "./interfaces.sol";
import {IVaultV3} from "../../common/interfaces/IVaultV3.sol";
import {VariablesBufferHelper} from "../../common/variables/variablesBufferHelper.sol";
contract LeverageModule is VariablesBufferHelper, Events {
using LeverageStructs for LeverageStructs.LeverageParams;
using LeverageStructs for LeverageStructs.LeverageWithSwapVariables;
/***********************************|
| ERRORS |
|__________________________________*/
error LeverageModule__LessAssetsReceived();
error LeverageModule__InvalidProtocolId();
error LeverageModule__MaxRiskRatioExceeded();
error LeverageModule__AggregatedRatioExceeded();
/***********************************|
| MODIFIERS |
|__________________________________*/
function _isLeverageAllowedProtocolId(uint8 protocolId_) internal pure {
if (
protocolId_ != 1 &&
protocolId_ != 2 &&
protocolId_ != 3 &&
protocolId_ != 4 &&
protocolId_ != 5 &&
protocolId_ != 6 &&
protocolId_ != 7
) {
revert LeverageModule__InvalidProtocolId();
}
}
modifier leverageAllowedProtocolId(uint8 protocolId_) {
_isLeverageAllowedProtocolId(protocolId_);
_;
}
function leverage(
LeverageStructs.LeverageParams memory leverageParams_
)
external
nonReentrant
onlyPrimaryRebalancer
leverageAllowedProtocolId(leverageParams_.protocolId)
{
LeverageStructs.LeverageWithSwapVariables
memory leverageWithSwapVariables_;
if (leverageParams_.protocolId == 1) {
leverageWithSwapVariables_.spellsLength = 4;
} else if (
leverageParams_.protocolId == 2 ||
leverageParams_.protocolId == 3 ||
leverageParams_.protocolId == 4 ||
leverageParams_.protocolId == 5 ||
leverageParams_.protocolId == 6 ||
leverageParams_.protocolId == 7
) {
leverageWithSwapVariables_.spellsLength = 3;
}
leverageWithSwapVariables_.spellIndex = 0;
leverageWithSwapVariables_.targets = new string[](
leverageWithSwapVariables_.spellsLength
);
leverageWithSwapVariables_.calldatas = new bytes[](
leverageWithSwapVariables_.spellsLength
);
leverageWithSwapVariables_.sellTokenExchangeRate = IVaultV3(
address(this)
).getTokenExchangeRate(leverageParams_.debtToken);
leverageWithSwapVariables_.buyTokenExchangeRate = IVaultV3(
address(this)
).getTokenExchangeRate(leverageParams_.colToken);
leverageWithSwapVariables_.swapAmountInUsd = _getAmountInUsd(
leverageParams_.debtToken,
leverageParams_.debtFlashloanAmount,
leverageWithSwapVariables_.sellTokenExchangeRate
);
_handleSwapLimitCheck(leverageWithSwapVariables_.swapAmountInUsd);
// 1. Swap Debt Token to Collateral Token
leverageWithSwapVariables_.targets[
leverageWithSwapVariables_.spellIndex
] = "SWAP-AGGREGATOR-B";
leverageWithSwapVariables_.calldatas[
leverageWithSwapVariables_.spellIndex
] = abi.encodeWithSignature(
"swap(address,address,uint256,uint256,uin256,uint256,string[],bytes[])",
leverageParams_.debtToken,
leverageParams_.colToken,
leverageParams_.minBuyAmount,
leverageWithSwapVariables_.sellTokenExchangeRate,
leverageWithSwapVariables_.buyTokenExchangeRate,
maxSwapLossPercentage,
leverageParams_.swapConnectors,
leverageParams_.swapCallDatas
);
leverageWithSwapVariables_.spellIndex++;
if (leverageParams_.protocolId == 1) {
// 2. Deposit Collateral Token (supply max)
leverageWithSwapVariables_.targets[
leverageWithSwapVariables_.spellIndex
] = "AAVE-V3-A";
leverageWithSwapVariables_.calldatas[
leverageWithSwapVariables_.spellIndex
] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
leverageParams_.colToken,
type(uint256).max,
0,
0
);
leverageWithSwapVariables_.spellIndex++;
// 3. Borrow Debt Token
leverageWithSwapVariables_.targets[
leverageWithSwapVariables_.spellIndex
] = "AAVE-V3-A";
leverageWithSwapVariables_.calldatas[
leverageWithSwapVariables_.spellIndex
] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
leverageParams_.debtToken,
leverageParams_.debtFlashloanAmount, // Amount should be flashloanBorrowAmount
2, // Interest rate mode
0,
0
);
leverageWithSwapVariables_.spellIndex++;
// 4. Repay Flashloan
leverageWithSwapVariables_.targets[
leverageWithSwapVariables_.spellIndex
] = "INSTAPOOL-D";
leverageWithSwapVariables_.calldatas[
leverageWithSwapVariables_.spellIndex
] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
leverageParams_.debtToken,
leverageParams_.debtFlashloanAmount,
0,
0
);
leverageWithSwapVariables_.spellIndex++;
} else if (
leverageParams_.protocolId == 2 ||
leverageParams_.protocolId == 3 ||
leverageParams_.protocolId == 4 ||
leverageParams_.protocolId == 5 ||
leverageParams_.protocolId == 6 ||
leverageParams_.protocolId == 7
) {
// 2. Deposit Collateral Token (supply max) & borrow debt token (debtFlashloanAmount_)
leverageWithSwapVariables_.targets[
leverageWithSwapVariables_.spellIndex
] = "FLUID-A";
leverageWithSwapVariables_.calldatas[
leverageWithSwapVariables_.spellIndex
] = abi.encodeWithSignature(
"operate(address,uint256,int256,int256,uint256)",
fluidVaultDetails[leverageParams_.protocolId].vaultAddress,
fluidVaultDetails[leverageParams_.protocolId].nftId,
type(int256).max,
leverageParams_.debtFlashloanAmount,
0
);
leverageWithSwapVariables_.spellIndex++;
// 4. Repay Flashloan
leverageWithSwapVariables_.targets[
leverageWithSwapVariables_.spellIndex
] = "INSTAPOOL-D";
leverageWithSwapVariables_.calldatas[
leverageWithSwapVariables_.spellIndex
] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
leverageParams_.debtToken,
leverageParams_.debtFlashloanAmount,
0,
0
);
leverageWithSwapVariables_.spellIndex++;
}
// Flash Borrow and Cast
bytes memory encodedFlashData_ = abi.encode(
leverageWithSwapVariables_.targets,
leverageWithSwapVariables_.calldatas
);
string[] memory flashTarget = new string[](1);
bytes[] memory flashCalldata = new bytes[](1);
flashTarget[0] = "INSTAPOOL-D";
flashCalldata[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
leverageParams_.debtToken,
leverageParams_.debtFlashloanAmount,
leverageParams_.route,
encodedFlashData_,
"0x"
);
(, , leverageWithSwapVariables_.beforeNetAssets, ) = IVaultV3(
address(this)
).getNetAssets();
vaultDSA.cast(flashTarget, flashCalldata, address(this));
(
,
,
leverageWithSwapVariables_.afterNetAssets,
leverageWithSwapVariables_.aggregatedRatio
) = IVaultV3(address(this)).getNetAssets();
// Net Assets Checks
if (
leverageWithSwapVariables_.afterNetAssets >
leverageWithSwapVariables_.beforeNetAssets
) {
reserves += int256(
leverageWithSwapVariables_.afterNetAssets -
leverageWithSwapVariables_.beforeNetAssets
);
} else if (
(((leverageWithSwapVariables_.beforeNetAssets * (1e8 - 1)) / 1e8) >
leverageWithSwapVariables_.afterNetAssets)
) {
revert LeverageModule__LessAssetsReceived();
}
// Aggregated Ratio Checks
if (leverageWithSwapVariables_.aggregatedRatio > aggrMaxVaultRatio) {
revert LeverageModule__AggregatedRatioExceeded();
}
emit LogLeverage(
leverageParams_.protocolId,
leverageParams_.debtFlashloanAmount,
leverageParams_.route,
leverageParams_.debtToken,
leverageParams_.colToken
);
}
}
"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
}
}
}}
Submitted on: 2025-10-30 14:08:22
Comments
Log in to comment.
No comments yet.