Quantillon Protocol Smart Contracts
Euro-pegged stablecoin protocol with dual-pool architecture, yield generation, and governance mechanisms
📖 Overview
Quantillon Protocol is a comprehensive DeFi ecosystem built around QEURO, a Euro-pegged stablecoin. The protocol features a dual-pool architecture that separates user deposits from hedging operations, enabling efficient yield generation while maintaining stability.
📚 Documentation
- API Documentation - Complete API reference for all smart contracts
- Technical Reference - Detailed technical specifications and implementation details
- Quick Start Guide - Get started quickly with integration examples
- Integration Examples - Comprehensive integration examples and patterns
- Deployment Guide - Complete deployment instructions and procedures
- Secure Deployment Guide - Environment and operational security practices
- Documentation Hub - Comprehensive documentation overview
🎯 Key Features
- Euro-Pegged Stablecoin: QEURO maintains 1:1 peg with Euro through sophisticated mechanisms
- Dual-Pool Architecture: Separates user deposits from hedging operations for optimal risk management
- Yield Generation: Multiple yield sources including protocol fees, interest differentials, and yield farming
- Governance Token: QTI token with vote-escrow mechanics for decentralized governance
- Advanced Hedging: EUR/USD hedging positions with margin management and liquidation systems
- Yield-Bearing Wrapper: stQEURO token that automatically accrues yield for holders
- Aave Integration: Automated yield farming through Aave protocol integration
- Comprehensive Security: Role-based access control, reentrancy protection, and emergency pause mechanisms
- 🔐 Secure Environment Variables: Enterprise-grade security with standard .env files
🏗️ Architecture
Core Contracts
| Contract | Purpose | Key Features |
|---|---|---|
| QEUROToken | Euro-pegged stablecoin | Mint/burn controls, rate limiting, compliance features, 18 decimals |
| QTIToken | Governance token | Vote-escrow mechanics, fixed supply, lock periods, voting power multipliers |
| QuantillonVault | Main vault | Overcollateralized minting, liquidation system, fee management |
| UserPool | User deposits | Staking rewards, yield distribution, deposit/withdrawal management |
| HedgerPool | Hedging operations | EUR/USD positions, margin management, liquidation system |
| stQEUROToken | Yield-bearing wrapper | Automatic yield accrual, exchange rate mechanism |
| AaveVault | Aave integration | Automated yield farming, risk management, emergency controls |
| YieldShift | Yield management | Dynamic yield distribution, pool rebalancing, performance metrics |
| ChainlinkOracle | Price feeds | EUR/USD and USDC/USD price feeds with circuit breakers |
🚀 Quick Start
Prerequisites
1. Clone and Setup
git clone https://github.com/quantillon/smart-contracts.git
cd smart-contracts/quantillon-protocol
npm install
2. Environment Configuration
# Copy environment template
cp .env.example .env
# Fill in your values (API keys, private keys, etc.)
# Edit .env with your actual configuration
# Environment variables are ready to use
3. Build and Test
# Build contracts
make build
# Run tests
make test
# Run security analysis
make slither
🚀 Deployment
🔐 Multi-Phase Deployment Strategy
The protocol uses a 4-phase atomic deployment (A→B→C→D) to stay within Base Sepolia/Mainnet's 24.9M gas limit per transaction:
| Phase | Gas | Contracts | Purpose |
|---|---|---|---|
| A | ~17M | TimeProvider, Oracle, QEURO, FeeCollector, Vault | Core infrastructure |
| B | ~16M | QTI, AaveVault, stQEURO | Token layer |
| C | ~11M | UserPool, HedgerPool | Pool layer |
| D | ~7M | YieldShift + wiring | Yield management |
Key Features:
- ✅ All phases well under 24.9M limit (8-13M gas headroom)
- ✅ Automatic address passing between phases
- ✅ Minimal initialization with governance setters for post-deployment wiring
- ✅ Frontend address updater merges all phase broadcasts automatically
See Deployment Guide for complete details.
🔐 Secure Deployment
The protocol uses standard environment variable configuration:
# Deploy to localhost with mock contracts
./scripts/deployment/deploy.sh localhost --with-mocks
# Deploy to Base Sepolia testnet
./scripts/deployment/deploy.sh base-sepolia --verify
# Deploy to Base mainnet (production)
./scripts/deployment/deploy.sh base --production --verify
📋 Deployment Options
| Environment | Command | Description |
|---|---|---|
| localhost | ./scripts/deployment/deploy.sh localhost --with-mocks | Development with Anvil and mock contracts |
| base-sepolia | ./scripts/deployment/deploy.sh base-sepolia --verify | Testnet deployment with contract verification |
| base | ./scripts/deployment/deploy.sh base --production --verify | Production deployment with multisig governance |
🔧 Deployment Features
- 🔐 Secure Environment Variables: Manage secrets with standard
.envfiles (never commit them) - 🌐 Multi-Network Support: Localhost, Base Sepolia, and Base Mainnet
- 🎭 Mock Contract Handling: Automatic mock deployment for localhost
- ✅ Contract Verification: Automatic verification on block explorers
- 🧪 Dry-Run Capability: Test deployments without broadcasting
- 📝 Post-Deployment Tasks: Automatic ABI copying and address updates
🛡️ Security Features
- Environment Variables: Use standard
.envfiles (never commit them) - Secret Management: Prefer a secret manager for production (e.g., AWS Secrets Manager)
🧪 Testing
Run All Tests
make test
Run Specific Test Suites
# Core protocol tests
forge test --match-contract QuantillonVault
# Integration tests
forge test --match-contract IntegrationTests
# Security tests
forge test --match-contract SecurityTests
Gas Analysis
make gas-analysis
🔍 Security
Automated Security Analysis
# Run Slither static analysis
make slither
# Run Mythril analysis
make mythril
# Validate NatSpec documentation
make validate-natspec
Security Features
- Role-Based Access Control: Granular permissions for different operations
- Reentrancy Protection: Comprehensive reentrancy guards
- Emergency Pause: Circuit breakers for critical functions
- Input Validation: Extensive parameter validation
- Overflow Protection: Safe math operations throughout
- Secret Handling: Environment variables loaded from
.envduring development
📊 Development
Available Commands
# Build contracts
make build
# Run tests
make test
# Run security analysis
make slither
# Generate documentation
make docs
# Clean build artifacts
make clean
# Gas analysis
make gas-analysis
Code Quality
- NatSpec Documentation: Comprehensive documentation for all functions
- Test Coverage: Extensive test suite with 678+ tests
- Security Analysis: Regular security audits and static analysis
- Gas Optimization: Optimized for deployment size and execution cost
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Follow Solidity style guide
- Write comprehensive tests
- Update documentation
- Ensure security best practices
- Protect secrets; never commit
.env
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
- Website: https://quantillon.money
- Documentation: https://docs.quantillon.money
- Discord: https://discord.gg/quantillon
- Twitter: @QuantillonLabs
🙏 Acknowledgments
- OpenZeppelin for secure contract libraries
- Chainlink for reliable price feeds
- Aave for yield farming integration
- Foundry for development framework
- Standard .env files for environment variable management
Contents
- vaults
- yieldmanagement
- FeeCollector
- HedgerPool
- QEUROToken
- QTIToken
- QuantillonVault
- SecureUpgradeable
- TimelockUpgradeable
- UserPool
- stQEUROToken
Contents
IPool
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Note: security-contact: team@quantillon.money
Functions
supply
Supply assets to Aave protocol
Supplies assets to Aave protocol on behalf of a user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | Address of the asset to supply |
amount | uint256 | Amount of assets to supply |
onBehalfOf | address | Address to supply on behalf of |
referralCode | uint16 | Referral code for Aave protocol |
withdraw
Withdraw assets from Aave protocol
Withdraws assets from Aave protocol to a specified address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function withdraw(address asset, uint256 amount, address to) external returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | Address of the asset to withdraw |
amount | uint256 | Amount of assets to withdraw |
to | address | Address to withdraw to |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Amount of assets withdrawn |
getReserveData
Get reserve data for an asset
Returns reserve data for a specific asset in Aave protocol
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getReserveData(address asset) external view returns (ReserveData memory);
Parameters
| Name | Type | Description |
|---|---|---|
asset | address | Address of the asset |
Returns
| Name | Type | Description |
|---|---|---|
<none> | ReserveData | ReserveData Reserve data structure |
IPoolAddressesProvider
Functions
getPool
Get the pool address
Returns the address of the Aave pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPool() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address Address of the Aave pool |
IRewardsController
Functions
claimRewards
Claim rewards from Aave protocol
Claims rewards for specified assets and amount
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimRewards(address[] calldata assets, uint256 amount, address to) external returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
assets | address[] | Array of asset addresses |
amount | uint256 | Amount of rewards to claim |
to | address | Address to send rewards to |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Amount of rewards claimed |
getUserRewards
Get user rewards for specified assets
Returns the rewards for a user across specified assets
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserRewards(address[] calldata assets, address user) external view returns (uint256[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
assets | address[] | Array of asset addresses |
user | address | Address of the user |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256[] | uint256[] Array of reward amounts for each asset |
ReserveData
struct ReserveData {
uint256 configuration;
uint128 liquidityIndex;
uint128 currentLiquidityRate;
uint128 variableBorrowIndex;
uint128 currentVariableBorrowRate;
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
uint16 id;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
uint128 accruedToTreasury;
uint128 unbacked;
uint128 isolationModeTotalDebt;
}
AaveVault
Inherits: Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable, PausableUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Aave integration vault for yield generation through USDC lending
Main characteristics:
- USDC deposits into Aave lending protocol for yield generation
- Automatic yield harvesting and distribution
- Risk management with exposure limits and health monitoring
- Emergency withdrawal capabilities for crisis situations
- Dynamic allocation based on market conditions
- Upgradeable via UUPS pattern
Deposit mechanics:
- USDC supplied to Aave protocol for lending
- Receives aUSDC tokens representing interest-bearing deposits
- Principal tracking for yield calculation
- Maximum exposure limits for risk management
- Health checks before deposits
Yield harvesting:
- Automatic detection of accrued interest
- Threshold-based harvesting to optimize gas costs
- Protocol fees charged on harvested yield
- Net yield distributed to yield shift mechanism
- Real-time yield tracking and reporting
Risk management:
- Maximum Aave exposure limits (default 50M USDC)
- Utilization rate monitoring for liquidity risk
- Emergency mode for immediate withdrawals
- Health monitoring of Aave protocol status
- Slippage protection on withdrawals
Allocation strategy:
- Dynamic allocation based on Aave APY
- Rebalancing thresholds for optimal yield
- Market condition adjustments
- Liquidity availability considerations
- Expected yield calculations
Fee structure:
- Yield fees charged on harvested interest (default 10%)
- Protocol fees for sustainability
- Dynamic fee adjustment based on performance
- Fee collection and distribution tracking
Security features:
- Role-based access control for all critical operations
- Reentrancy protection for all external calls
- Emergency pause mechanism for crisis situations
- Upgradeable architecture for future improvements
- Secure withdrawal validation
- Health monitoring and circuit breakers
Integration points:
- Aave lending protocol for yield generation
- USDC for deposits and withdrawals
- aUSDC tokens for interest accrual tracking
- Yield shift mechanism for yield distribution
- Rewards controller for additional incentives
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
VAULT_MANAGER_ROLE
bytes32 public constant VAULT_MANAGER_ROLE = keccak256("VAULT_MANAGER_ROLE")
EMERGENCY_ROLE
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
usdc
IERC20 public usdc
aUSDC
IERC20 public aUSDC
aavePool
IPool public aavePool
aaveProvider
IPoolAddressesProvider public aaveProvider
rewardsController
IRewardsController public rewardsController
yieldShift
IYieldShift public yieldShift
maxAaveExposure
uint256 public maxAaveExposure
harvestThreshold
uint256 public harvestThreshold
yieldFee
uint256 public yieldFee
rebalanceThreshold
uint256 public rebalanceThreshold
principalDeposited
uint256 public principalDeposited
lastHarvestTime
uint256 public lastHarvestTime
totalYieldHarvested
uint256 public totalYieldHarvested
totalFeesCollected
uint256 public totalFeesCollected
utilizationLimit
uint256 public utilizationLimit
emergencyExitThreshold
uint256 public emergencyExitThreshold
emergencyMode
bool public emergencyMode
treasury
address public treasury
Functions
constructor
Constructor for AaveVault implementation
Disables initialization on implementation for security
Notes:
-
security: Disables initialization on implementation for security
-
validation: No input validation required
-
state-changes: Disables initializers
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not protected - constructor only
-
access: Public constructor
-
oracle: No oracle dependencies
constructor() ;
initialize
Initialize the AaveVault contract
Sets up the contract with all required addresses and roles
Notes:
-
security: Validates all addresses are not zero
-
validation: Validates all input addresses
-
state-changes: Initializes ReentrancyGuard, AccessControl, and Pausable
-
events: Emits initialization events
-
errors: Throws if any address is zero
-
reentrancy: Protected by initializer modifier
-
access: Public initializer
-
oracle: No oracle dependencies
function initialize(
address admin,
address _usdc,
address _aaveProvider,
address _rewardsController,
address _yieldShift,
address _timelock,
address _treasury
) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address of the admin role |
_usdc | address | Address of the USDC token contract |
_aaveProvider | address | Address of the Aave pool addresses provider |
_rewardsController | address | Address of the Aave rewards controller |
_yieldShift | address | Address of the yield shift contract |
_timelock | address | Address of the timelock contract |
_treasury | address | Address of the treasury |
deployToAave
Deploy USDC to Aave V3 pool to earn yield
Supplies USDC to Aave protocol and receives aUSDC tokens representing the deposit
Notes:
-
security: Validates oracle price freshness, enforces exposure limits and health checks
-
validation: Validates amount > 0, checks max exposure limits, verifies Aave pool health
-
state-changes: Updates principalDeposited, transfers USDC from caller, receives aUSDC
-
events: Emits DeployedToAave with operation details
-
errors: Throws WouldExceedLimit if exceeds maxAaveExposure, AavePoolNotHealthy if pool unhealthy
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to VAULT_MANAGER_ROLE
-
oracle: Requires fresh EUR/USD price for health validation
function deployToAave(uint256 amount) external nonReentrant whenNotPaused returns (uint256 aTokensReceived);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | USDC amount to supply (6 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
aTokensReceived | uint256 | Amount of aUSDC received (6 decimals) |
withdrawFromAave
Withdraw USDC from Aave V3 pool
Withdraws USDC from Aave protocol, validates slippage and updates principal tracking
Notes:
-
security: Validates withdrawal constraints, enforces minimum balance requirements
-
validation: Validates amount > 0, checks sufficient aUSDC balance, validates slippage
-
state-changes: Updates principalDeposited, withdraws aUSDC, receives USDC
-
events: Emits WithdrawnFromAave with withdrawal details
-
errors: Throws InsufficientBalance if not enough aUSDC, WouldBreachMinimum if below threshold
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to VAULT_MANAGER_ROLE
-
oracle: No oracle dependency for withdrawals
function withdrawFromAave(uint256 amount) external nonReentrant returns (uint256 usdcWithdrawn);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of aUSDC to withdraw (6 decimals, use type(uint256).max for all) |
Returns
| Name | Type | Description |
|---|---|---|
usdcWithdrawn | uint256 | Amount of USDC actually withdrawn (6 decimals) |
_validateAndCalculateWithdrawAmount
Validates and calculates the actual withdrawal amount
Internal function to validate withdrawal parameters and calculate actual amount
Notes:
-
security: Validates sufficient balance and handles max withdrawal requests
-
validation: Validates aaveBalance > 0, amount <= aaveBalance
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InsufficientBalance if balance too low
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _validateAndCalculateWithdrawAmount(uint256 amount, uint256 aaveBalance)
internal
pure
returns (uint256 withdrawAmount);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Requested withdrawal amount (6 decimals) |
aaveBalance | uint256 | Current aUSDC balance (6 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
withdrawAmount | uint256 | Actual amount to withdraw (6 decimals) |
_validateWithdrawalConstraints
Validates withdrawal constraints (emergency mode, minimum balance)
Internal function to validate withdrawal constraints and minimum balance requirements
Notes:
-
security: Enforces minimum balance requirements unless in emergency mode
-
validation: Validates remaining balance >= minimum threshold
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: Throws WouldBreachMinimum if below minimum balance threshold
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _validateWithdrawalConstraints(uint256 withdrawAmount, uint256 aaveBalance) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
withdrawAmount | uint256 | Amount to withdraw (6 decimals) |
aaveBalance | uint256 | Current aUSDC balance (6 decimals) |
_validateExpectedWithdrawal
Validates expected withdrawal amounts before external call
Validates expected withdrawal amounts before external call
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _validateExpectedWithdrawal(uint256 withdrawAmount) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
withdrawAmount | uint256 | Amount to withdraw |
_executeAaveWithdrawal
Executes the Aave withdrawal with proper error handling
Executes the Aave withdrawal with proper error handling
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _executeAaveWithdrawal(uint256 originalAmount, uint256 withdrawAmount, uint256 usdcBefore)
internal
returns (uint256 usdcWithdrawn);
Parameters
| Name | Type | Description |
|---|---|---|
originalAmount | uint256 | Original amount requested |
withdrawAmount | uint256 | Amount to withdraw from Aave |
usdcBefore | uint256 | USDC balance before withdrawal |
Returns
| Name | Type | Description |
|---|---|---|
usdcWithdrawn | uint256 | Actual amount withdrawn |
_validateWithdrawalResult
Validates the withdrawal result and slippage
Validates the withdrawal result and slippage
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _validateWithdrawalResult(
uint256 originalAmount,
uint256 withdrawAmount,
uint256 usdcBefore,
uint256 usdcWithdrawn
) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
originalAmount | uint256 | Original amount requested |
withdrawAmount | uint256 | Amount to withdraw from Aave |
usdcBefore | uint256 | USDC balance before withdrawal |
usdcWithdrawn | uint256 | Actual amount withdrawn |
claimAaveRewards
Claim Aave rewards (if any)
Claims any available Aave protocol rewards for the vault's aUSDC position
Notes:
-
security: No additional security checks required - Aave handles reward validation
-
validation: No input validation required - view function checks pending rewards
-
state-changes: Claims rewards to vault address, updates reward tracking
-
events: Emits AaveRewardsClaimed with reward details
-
errors: No errors thrown - safe to call even with no rewards
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to VAULT_MANAGER_ROLE
-
oracle: No oracle dependency for reward claims
function claimAaveRewards() external nonReentrant returns (uint256 rewardsClaimed);
Returns
| Name | Type | Description |
|---|---|---|
rewardsClaimed | uint256 | Claimed reward amount (18 decimals) |
harvestAaveYield
Harvest Aave yield and distribute via YieldShift
Harvests available yield from Aave lending, charges protocol fees, distributes net yield
Notes:
-
security: Uses CEI pattern, validates slippage, enforces harvest threshold
-
validation: Validates available yield >= harvestThreshold before harvesting
-
state-changes: Updates lastHarvestTime, totalFeesCollected, totalYieldHarvested
-
events: Emits AaveYieldHarvested with harvest details
-
errors: Throws BelowThreshold if yield < harvestThreshold, ExcessiveSlippage if slippage too high
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to VAULT_MANAGER_ROLE
-
oracle: No oracle dependency for yield harvesting
function harvestAaveYield() external nonReentrant returns (uint256 yieldHarvested);
Returns
| Name | Type | Description |
|---|---|---|
yieldHarvested | uint256 | Amount harvested (6 decimals) |
getAvailableYield
Returns the total available yield from Aave lending
Calculates yield based on current aToken balance vs principal deposited
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAvailableYield() public view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The amount of yield available for distribution |
getYieldDistribution
Returns the breakdown of yield distribution between users and protocol
Shows how yield is allocated according to current distribution parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldDistribution()
external
view
returns (uint256 protocolYield, uint256 userYield, uint256 hedgerYield);
Returns
| Name | Type | Description |
|---|---|---|
protocolYield | uint256 | Amount of yield allocated to protocol fees |
userYield | uint256 | Amount of yield allocated to users |
hedgerYield | uint256 | Amount of yield allocated to hedgers |
getAaveBalance
Returns the current balance of aTokens held by this vault
Represents the total amount deposited in Aave plus accrued interest
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveBalance() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The current aToken balance |
getAccruedInterest
Returns the total interest accrued from Aave lending
Calculates interest as current balance minus principal deposited
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAccruedInterest() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The amount of interest accrued |
getAaveAPY
Returns the current APY offered by Aave for the deposited asset
Fetches the supply rate from Aave's reserve data
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveAPY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The current APY in basis points |
getAavePositionDetails
Returns detailed information about the Aave position
Provides comprehensive data about the vault's Aave lending position
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAavePositionDetails()
external
view
returns (uint256 principalDeposited_, uint256 currentBalance, uint256 aTokenBalance, uint256 lastUpdateTime);
Returns
| Name | Type | Description |
|---|---|---|
principalDeposited_ | uint256 | Total amount originally deposited |
currentBalance | uint256 | Current aToken balance including interest |
aTokenBalance | uint256 | Current aToken balance |
lastUpdateTime | uint256 | Timestamp of last position update |
getAaveMarketData
Returns current Aave market data for the deposited asset
Fetches real-time market information from Aave protocol
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveMarketData()
external
view
returns (uint256 supplyRate, uint256 utilizationRate, uint256 totalSupply, uint256 availableLiquidity);
Returns
| Name | Type | Description |
|---|---|---|
supplyRate | uint256 | Current supply rate for the asset |
utilizationRate | uint256 | Current utilization rate of the reserve |
totalSupply | uint256 | Total supply of the underlying asset |
availableLiquidity | uint256 | Available liquidity in the reserve |
checkAaveHealth
Performs health checks on the Aave position
Validates that the Aave position is healthy and functioning properly
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function checkAaveHealth() external view returns (bool isHealthy, bool pauseStatus, uint256 lastUpdate);
Returns
| Name | Type | Description |
|---|---|---|
isHealthy | bool | True if position is healthy, false if issues detected |
pauseStatus | bool | Current pause status of the contract |
lastUpdate | uint256 | Timestamp of last health check update |
_isAaveHealthy
Check if Aave protocol is healthy
Checks if Aave protocol is functioning properly by verifying reserve data
Notes:
-
security: Uses try-catch to handle potential failures gracefully
-
validation: No input validation required
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - uses try-catch
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _isAaveHealthy() internal view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if Aave is healthy, false otherwise |
autoRebalance
Automatically rebalance the vault allocation
Rebalances the vault allocation based on optimal allocation calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function autoRebalance() external returns (bool rebalanced, uint256 newAllocation, uint256 expectedYield);
Returns
| Name | Type | Description |
|---|---|---|
rebalanced | bool | True if rebalancing occurred, false otherwise |
newAllocation | uint256 | New allocation percentage after rebalancing |
expectedYield | uint256 | Expected yield from the new allocation |
calculateOptimalAllocation
Calculates the optimal allocation of funds to Aave
Determines best allocation strategy based on current market conditions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateOptimalAllocation() external view returns (uint256 optimalAllocation, uint256 expectedYield);
Returns
| Name | Type | Description |
|---|---|---|
optimalAllocation | uint256 | Recommended amount to allocate to Aave |
expectedYield | uint256 | Expected yield from the recommended allocation |
setMaxAaveExposure
Sets the maximum exposure limit for Aave deposits
Governance function to control risk by limiting Aave exposure
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setMaxAaveExposure(uint256 _maxExposure) external;
Parameters
| Name | Type | Description |
|---|---|---|
_maxExposure | uint256 | Maximum amount that can be deposited to Aave |
emergencyWithdrawFromAave
Emergency withdrawal from Aave protocol
Emergency function to withdraw all funds from Aave protocol
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyWithdrawFromAave() external nonReentrant returns (uint256 amountWithdrawn);
Returns
| Name | Type | Description |
|---|---|---|
amountWithdrawn | uint256 | Amount of USDC withdrawn from Aave |
getRiskMetrics
Returns comprehensive risk metrics for the Aave position
Provides detailed risk analysis including concentration and volatility metrics
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRiskMetrics()
external
view
returns (uint256 exposureRatio, uint256 concentrationRisk, uint256 liquidityRisk);
Returns
| Name | Type | Description |
|---|---|---|
exposureRatio | uint256 | Percentage of total assets exposed to Aave |
concentrationRisk | uint256 | Risk level due to concentration in Aave (1-3 scale) |
liquidityRisk | uint256 | Risk level based on Aave liquidity conditions (1-3 scale) |
updateAaveParameters
Update Aave parameters
Updates harvest threshold, yield fee, and rebalance threshold
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateAaveParameters(uint256 newHarvestThreshold, uint256 newYieldFee, uint256 newRebalanceThreshold)
external;
Parameters
| Name | Type | Description |
|---|---|---|
newHarvestThreshold | uint256 | New harvest threshold in USDC |
newYieldFee | uint256 | New yield fee in basis points |
newRebalanceThreshold | uint256 | New rebalance threshold in basis points |
getAaveConfig
Returns the current Aave integration configuration
Provides access to all configuration parameters for Aave integration
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveConfig()
external
view
returns (address aavePool_, address aUSDC_, uint256 harvestThreshold_, uint256 yieldFee_, uint256 maxExposure_);
Returns
| Name | Type | Description |
|---|---|---|
aavePool_ | address | Address of the Aave pool contract |
aUSDC_ | address | Address of the aUSDC token contract |
harvestThreshold_ | uint256 | Minimum yield threshold for harvesting |
yieldFee_ | uint256 | Fee percentage charged on yield |
maxExposure_ | uint256 | Maximum allowed exposure to Aave |
toggleEmergencyMode
Toggles emergency mode for the Aave vault
Emergency function to enable/disable emergency mode during critical situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function toggleEmergencyMode(bool enabled, string calldata reason) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable or disable emergency mode |
reason | string | Human-readable reason for the change |
pause
Pauses all Aave vault operations
Emergency function to halt all vault operations when needed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpauses Aave vault operations
Resumes normal vault operations after emergency is resolved
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
recoverToken
Recovers accidentally sent ERC20 tokens from the vault
Emergency function to recover tokens that are not part of normal operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The token address to recover |
amount | uint256 | The amount of tokens to recover |
recoverETH
Recovers accidentally sent ETH from the vault
Emergency function to recover ETH that shouldn't be in the vault
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
Events
DeployedToAave
OPTIMIZED: Indexed operation type for efficient filtering
event DeployedToAave(string indexed operationType, uint256 amount, uint256 aTokensReceived, uint256 newBalance);
WithdrawnFromAave
event WithdrawnFromAave(
string indexed operationType, uint256 amountRequested, uint256 amountWithdrawn, uint256 newBalance
);
AaveYieldHarvested
event AaveYieldHarvested(string indexed harvestType, uint256 yieldHarvested, uint256 protocolFee, uint256 netYield);
AaveRewardsClaimed
event AaveRewardsClaimed(address indexed rewardToken, uint256 rewardAmount, address recipient);
PositionRebalanced
OPTIMIZED: Indexed reason and parameter for efficient filtering
event PositionRebalanced(string indexed reason, uint256 oldAllocation, uint256 newAllocation);
AaveParameterUpdated
event AaveParameterUpdated(string indexed parameter, uint256 oldValue, uint256 newValue);
EmergencyWithdrawal
event EmergencyWithdrawal(string indexed reason, uint256 amountWithdrawn, uint256 timestamp);
EmergencyModeToggled
event EmergencyModeToggled(string indexed reason, bool enabled);
Contents
YieldShift
Inherits: Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable, PausableUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Dynamic yield distribution system balancing rewards between users and hedgers
Main characteristics:
- Dynamic yield allocation based on pool balance ratios
- Time-weighted average price (TWAP) calculations for stability
- Multiple yield sources integration (Aave, fees, interest differentials)
- Automatic yield distribution with holding period requirements
- Emergency pause mechanism for crisis situations
- Upgradeable via UUPS pattern
Yield shift mechanics:
- Base yield shift determines default allocation (default 50/50)
- Maximum yield shift caps allocation changes (default 90/10)
- Adjustment speed controls how quickly shifts occur
- Target pool ratio defines optimal balance point
- Real-time calculations based on pool metrics
Distribution algorithm:
- Monitors user pool vs hedger pool size ratios
- Adjusts yield allocation to incentivize balance
- Higher user pool → more yield to hedgers (attract hedging)
- Higher hedger pool → more yield to users (attract deposits)
- Gradual adjustments prevent dramatic shifts
- Flash deposit protection through eligible pool size calculations
- Only deposits meeting holding period requirements count toward yield distribution
Yield sources:
- Aave yield from USDC deposits in lending protocols
- Protocol fees from minting, redemption, and trading
- Interest rate differentials from hedging operations
- External yield farming opportunities
- Authorized source validation for security
Time-weighted calculations:
- 24-hour TWAP for pool size measurements
- Historical data tracking for trend analysis
- Maximum history length prevents unbounded storage
- Drift tolerance for timestamp validation
- Automatic data cleanup and optimization
Holding period requirements:
- Minimum 7-day holding period for yield claims
- Prevents yield farming attacks and speculation
- Encourages long-term protocol participation
- Tracked per user with deposit timestamps
- Enhanced protection against flash deposit manipulation
- Eligible pool sizes exclude recent deposits from yield calculations
- Dynamic discount system based on deposit timing and activity
Security features:
- Role-based access control for all critical operations
- Reentrancy protection for all external calls
- Emergency pause mechanism for crisis situations
- Upgradeable architecture for future improvements
- Authorized yield source validation
- Secure yield distribution mechanisms
- Flash deposit attack prevention through holding period requirements
- Eligible pool size calculations for yield distribution
- Time-weighted protection against yield manipulation
Integration points:
- User pool for deposit and staking metrics
- Hedger pool for hedging exposure metrics
- Aave vault for yield generation and harvesting
- stQEURO token for user yield distribution
- USDC for yield payments and transfers
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
YIELD_MANAGER_ROLE
bytes32 public constant YIELD_MANAGER_ROLE = keccak256("YIELD_MANAGER_ROLE")
EMERGENCY_ROLE
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
usdc
IERC20 public usdc
userPool
IUserPool public userPool
hedgerPool
IHedgerPool public hedgerPool
aaveVault
IAaveVault public aaveVault
stQEURO
IstQEURO public stQEURO
TIME_PROVIDER
TimeProvider contract for centralized time management
Used to replace direct block.timestamp usage for testability and consistency
TimeProvider public immutable TIME_PROVIDER
baseYieldShift
uint256 public baseYieldShift
maxYieldShift
uint256 public maxYieldShift
adjustmentSpeed
uint256 public adjustmentSpeed
targetPoolRatio
uint256 public targetPoolRatio
MIN_HOLDING_PERIOD
uint256 public constant MIN_HOLDING_PERIOD = 7 days
TWAP_PERIOD
uint256 public constant TWAP_PERIOD = 24 hours
MAX_TIME_ELAPSED
uint256 public constant MAX_TIME_ELAPSED = 365 days
currentYieldShift
uint256 public currentYieldShift
lastUpdateTime
uint256 public lastUpdateTime
totalYieldGenerated
uint256 public totalYieldGenerated
totalYieldDistributed
uint256 public totalYieldDistributed
userYieldPool
uint256 public userYieldPool
hedgerYieldPool
uint256 public hedgerYieldPool
treasury
address public treasury
yieldSources
mapping(bytes32 => uint256) public yieldSources
yieldSourceNames
bytes32[] public yieldSourceNames
authorizedYieldSources
mapping(address => bool) public authorizedYieldSources
sourceToYieldType
mapping(address => bytes32) public sourceToYieldType
userPendingYield
mapping(address => uint256) public userPendingYield
hedgerPendingYield
mapping(address => uint256) public hedgerPendingYield
userLastClaim
mapping(address => uint256) public userLastClaim
hedgerLastClaim
mapping(address => uint256) public hedgerLastClaim
lastDepositTime
mapping(address => uint256) public lastDepositTime
userPoolHistory
PoolSnapshot[] public userPoolHistory
hedgerPoolHistory
PoolSnapshot[] public hedgerPoolHistory
MAX_HISTORY_LENGTH
uint256 public constant MAX_HISTORY_LENGTH = 1000
yieldShiftHistory
YieldShiftSnapshot[] public yieldShiftHistory
Functions
constructor
Constructor for YieldShift implementation
Sets up the time provider and disables initialization on implementation for security
Notes:
-
security: Validates time provider address and disables initialization on implementation
-
validation: Validates time provider is not zero address
-
state-changes: Sets time provider and disables initializers
-
events: No events emitted
-
errors: Throws ZeroAddress if time provider is zero
-
reentrancy: Not protected - constructor only
-
access: Public constructor
-
oracle: No oracle dependencies
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | Address of the time provider contract |
initialize
Initialize the YieldShift contract
Sets up the contract with all required addresses and roles
Notes:
-
security: Validates all addresses are not zero
-
validation: Validates all input addresses
-
state-changes: Initializes ReentrancyGuard, AccessControl, and Pausable
-
events: Emits initialization events
-
errors: Throws if any address is zero
-
reentrancy: Protected by initializer modifier
-
access: Public initializer
-
oracle: No oracle dependencies
function initialize(
address admin,
address _usdc,
address _userPool,
address _hedgerPool,
address _aaveVault,
address _stQEURO,
address _timelock,
address _treasury
) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address of the admin role |
_usdc | address | Address of the USDC token contract |
_userPool | address | Address of the user pool contract |
_hedgerPool | address | Address of the hedger pool contract |
_aaveVault | address | Address of the Aave vault contract |
_stQEURO | address | Address of the stQEURO token contract |
_timelock | address | Address of the timelock contract |
_treasury | address | Address of the treasury |
bootstrapDefaults
Governance bootstrap to set initial histories and source metadata after minimal init
function bootstrapDefaults() external;
updateYieldDistribution
Updates the yield distribution between users and hedgers
Recalculates and applies new yield distribution ratios based on current pool states
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateYieldDistribution() external nonReentrant whenNotPaused;
addYield
Add yield from authorized sources
Adds yield from authorized sources and distributes it according to current yield shift
Notes:
-
security: Validates caller is authorized for the yield source
-
validation: Validates yield amount is positive and matches actual received
-
state-changes: Updates yield sources and total yield generated
-
events: Emits YieldAdded event
-
errors: Throws if caller is unauthorized or yield amount mismatch
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to authorized yield sources
-
oracle: No oracle dependencies
function addYield(uint256 yieldAmount, bytes32 source) external nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield to add (6 decimals) |
source | bytes32 | Source identifier for the yield |
claimUserYield
Claim user yield
Claims yield for a user after holding period requirements are met
Notes:
-
security: Validates caller is authorized and holding period is met
-
validation: Validates user has pending yield and meets holding period
-
state-changes: Updates user pending yield and transfers USDC
-
events: Emits YieldClaimed event
-
errors: Throws if caller is unauthorized or holding period not met
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to user or user pool
-
oracle: No oracle dependencies
function claimUserYield(address user) external nonReentrant returns (uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to claim yield for |
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield claimed |
claimHedgerYield
Claim hedger yield
Claims yield for a hedger
Notes:
-
security: Validates caller is authorized
-
validation: Validates hedger has pending yield
-
state-changes: Updates hedger pending yield and transfers USDC
-
events: Emits HedgerYieldClaimed event
-
errors: Throws if caller is unauthorized or insufficient yield
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to hedger or hedger pool
-
oracle: No oracle dependencies
function claimHedgerYield(address hedger) external nonReentrant returns (uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to claim yield for |
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield claimed |
_calculateOptimalYieldShift
Calculate optimal yield shift based on current pool ratio
Calculates optimal yield allocation to incentivize pool balance
Notes:
-
security: Uses tolerance checks to prevent excessive adjustments
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _calculateOptimalYieldShift(uint256 poolRatio) internal view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolRatio | uint256 | Current ratio between user and hedger pools (basis points) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Optimal yield shift percentage (basis points) |
_applyGradualAdjustment
Apply gradual adjustment to yield shift to prevent sudden changes
Gradually adjusts yield shift based on adjustmentSpeed to prevent volatility
Notes:
-
security: Limits adjustment speed to prevent sudden changes
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _applyGradualAdjustment(uint256 targetShift) internal view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
targetShift | uint256 | Target yield shift percentage (basis points) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Adjusted yield shift percentage (basis points) |
_getCurrentPoolMetrics
Get current pool metrics
Returns current pool sizes and ratio for yield shift calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _getCurrentPoolMetrics()
internal
view
returns (uint256 userPoolSize, uint256 hedgerPoolSize, uint256 poolRatio);
Returns
| Name | Type | Description |
|---|---|---|
userPoolSize | uint256 | Current user pool size |
hedgerPoolSize | uint256 | Current hedger pool size |
poolRatio | uint256 | Ratio of user to hedger pool sizes |
_getEligiblePoolMetrics
Get eligible pool metrics that only count deposits meeting holding period requirements
SECURITY: Prevents flash deposit attacks by excluding recent deposits from yield calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _getEligiblePoolMetrics()
internal
view
returns (uint256 userPoolSize, uint256 hedgerPoolSize, uint256 poolRatio);
Returns
| Name | Type | Description |
|---|---|---|
userPoolSize | uint256 | Eligible user pool size (deposits older than MIN_HOLDING_PERIOD) |
hedgerPoolSize | uint256 | Eligible hedger pool size (deposits older than MIN_HOLDING_PERIOD) |
poolRatio | uint256 | Ratio of eligible pool sizes |
_calculateHoldingPeriodDiscount
Calculate holding period discount based on recent deposit activity
Returns a percentage (in basis points) representing eligible deposits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _calculateHoldingPeriodDiscount() internal view returns (uint256 discountBps);
Returns
| Name | Type | Description |
|---|---|---|
discountBps | uint256 | Discount in basis points (10000 = 100%) |
_isWithinTolerance
Check if a value is within tolerance of a target value
Helper function for yield shift calculations
Notes:
-
security: Uses safe arithmetic to prevent overflow
-
validation: No input validation required - pure function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _isWithinTolerance(uint256 value, uint256 target, uint256 toleranceBps) internal pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
value | uint256 | The value to check |
target | uint256 | The target value |
toleranceBps | uint256 | Tolerance in basis points (e.g., 1000 = 10%) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if value is within tolerance, false otherwise |
updateLastDepositTime
Updates the last deposit timestamp for a user
Called by UserPool to track user deposit timing for yield calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateLastDepositTime(address user) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address to update |
getCurrentYieldShift
Returns the current yield shift percentage
Shows how much yield is currently being shifted between pools
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getCurrentYieldShift() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The current yield shift percentage in basis points |
getUserPendingYield
Returns the pending yield amount for a specific user
Calculates unclaimed yield based on user's deposits and current rates
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserPendingYield(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The pending yield amount |
getHedgerPendingYield
Returns the pending yield amount for a specific hedger
Calculates unclaimed yield based on hedger's positions and current rates
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getHedgerPendingYield(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | The hedger address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The pending yield amount |
getTotalYieldGenerated
Returns the total yield generated by the protocol
Aggregates all yield generated from various sources
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTotalYieldGenerated() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total yield generated |
getYieldDistributionBreakdown
Returns detailed breakdown of yield distribution
Shows how yield is allocated between different pools and stakeholders
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldDistributionBreakdown()
external
view
returns (uint256 userYieldPool_, uint256 hedgerYieldPool_, uint256 distributionRatio);
Returns
| Name | Type | Description |
|---|---|---|
userYieldPool_ | uint256 | Yield allocated to user pool |
hedgerYieldPool_ | uint256 | Yield allocated to hedger pool |
distributionRatio | uint256 | Current distribution ratio between pools |
getPoolMetrics
Returns comprehensive metrics for both user and hedger pools
Provides detailed analytics about pool performance and utilization
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPoolMetrics()
external
view
returns (uint256 userPoolSize, uint256 hedgerPoolSize, uint256 poolRatio, uint256 targetRatio);
Returns
| Name | Type | Description |
|---|---|---|
userPoolSize | uint256 | Total size of user pool |
hedgerPoolSize | uint256 | Total size of hedger pool |
poolRatio | uint256 | Current ratio between pools |
targetRatio | uint256 | Target ratio between pools |
calculateOptimalYieldShift
Calculates the optimal yield shift based on current market conditions
Uses algorithms to determine best yield distribution strategy
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateOptimalYieldShift() external view returns (uint256 optimalShift, uint256 currentDeviation);
Returns
| Name | Type | Description |
|---|---|---|
optimalShift | uint256 | Recommended yield shift percentage |
currentDeviation | uint256 | Current deviation from optimal shift |
getYieldSources
Returns information about all yield sources
Provides details about different yield-generating mechanisms
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldSources()
external
view
returns (uint256 aaveYield, uint256 protocolFees, uint256 interestDifferential, uint256 otherSources);
Returns
| Name | Type | Description |
|---|---|---|
aaveYield | uint256 | Yield from Aave protocol |
protocolFees | uint256 | Protocol fees collected |
interestDifferential | uint256 | Interest rate differential yield |
otherSources | uint256 | Other miscellaneous yield sources |
getHoldingPeriodProtectionStatus
Returns the current holding period protection status
Useful for monitoring and debugging holding period protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getHoldingPeriodProtectionStatus()
external
view
returns (uint256 minHoldingPeriod, uint256 baseDiscount, uint256 currentDiscount, uint256 timeSinceLastUpdate);
Returns
| Name | Type | Description |
|---|---|---|
minHoldingPeriod | uint256 | Current minimum holding period |
baseDiscount | uint256 | Current base discount percentage |
currentDiscount | uint256 | Current calculated discount percentage |
timeSinceLastUpdate | uint256 | Time since last yield distribution update |
getHistoricalYieldShift
Returns historical yield shift data for a specified period
Provides analytics about yield shift patterns over time
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getHistoricalYieldShift(uint256 period)
external
view
returns (uint256 averageShift, uint256 maxShift, uint256 minShift, uint256 volatility);
Parameters
| Name | Type | Description |
|---|---|---|
period | uint256 | The time period to analyze (in seconds) |
Returns
| Name | Type | Description |
|---|---|---|
averageShift | uint256 | Average yield shift during the period |
maxShift | uint256 | Maximum yield shift during the period |
minShift | uint256 | Minimum yield shift during the period |
volatility | uint256 | Volatility measure of yield shifts |
getYieldPerformanceMetrics
Returns comprehensive performance metrics for yield operations
Provides detailed analytics about yield performance and efficiency
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldPerformanceMetrics()
external
view
returns (
uint256 totalYieldDistributed_,
uint256 averageUserYield,
uint256 averageHedgerYield,
uint256 yieldEfficiency
);
Returns
| Name | Type | Description |
|---|---|---|
totalYieldDistributed_ | uint256 | Total yield distributed to date |
averageUserYield | uint256 | Average yield for users |
averageHedgerYield | uint256 | Average yield for hedgers |
yieldEfficiency | uint256 | Yield efficiency ratio |
_calculateUserAllocation
Calculate user allocation from current yield shift
Calculates how much yield should be allocated to users
Notes:
-
security: Uses safe arithmetic to prevent overflow
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _calculateUserAllocation() internal view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | User allocation amount based on current yield shift percentage |
_calculateHedgerAllocation
Calculate hedger allocation from current yield shift
Calculates how much yield should be allocated to hedgers
Notes:
-
security: Uses safe arithmetic to prevent overflow
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _calculateHedgerAllocation() internal view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Hedger allocation amount based on current yield shift percentage |
setYieldShiftParameters
Set yield shift parameters
Sets the base yield shift, maximum yield shift, and adjustment speed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates yield shift ranges and adjustment speed
-
state-changes: Updates yield shift parameters
-
events: Emits YieldShiftParametersUpdated event
-
errors: Throws if parameters are invalid
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to governance role
-
oracle: No oracle dependencies
function setYieldShiftParameters(uint256 _baseYieldShift, uint256 _maxYieldShift, uint256 _adjustmentSpeed)
external;
Parameters
| Name | Type | Description |
|---|---|---|
_baseYieldShift | uint256 | Base yield shift percentage in basis points |
_maxYieldShift | uint256 | Maximum yield shift percentage in basis points |
_adjustmentSpeed | uint256 | Adjustment speed in basis points |
setTargetPoolRatio
Sets the target ratio between user and hedger pools
Governance function to adjust pool balance for optimal yield distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setTargetPoolRatio(uint256 _targetPoolRatio) external;
Parameters
| Name | Type | Description |
|---|---|---|
_targetPoolRatio | uint256 | The new target pool ratio in basis points |
authorizeYieldSource
Authorize a yield source for specific yield type
Authorizes a yield source to add yield of a specific type
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function authorizeYieldSource(address source, bytes32 yieldType) external;
Parameters
| Name | Type | Description |
|---|---|---|
source | address | Address of the yield source |
yieldType | bytes32 | Type of yield this source is authorized for |
revokeYieldSource
Revoke authorization for a yield source
Revokes authorization for a yield source
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeYieldSource(address source) external;
Parameters
| Name | Type | Description |
|---|---|---|
source | address | Address of the yield source to revoke |
updateUserPool
Governance-only setters to wire references post-initialization (phased deploy)
function updateUserPool(address _userPool) external;
updateHedgerPool
function updateHedgerPool(address _hedgerPool) external;
updateAaveVault
function updateAaveVault(address _aaveVault) external;
updateStQEURO
function updateStQEURO(address _stQEURO) external;
updateYieldAllocation
Updates yield allocation for a specific user or hedger
Called by pools to update individual yield allocations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateYieldAllocation(address user, uint256 amount, bool isUser) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user or hedger address |
amount | uint256 | The allocation amount |
isUser | bool | True if user, false if hedger |
emergencyYieldDistribution
Executes emergency yield distribution with specified amounts
Emergency function to manually distribute yield during critical situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyYieldDistribution(uint256 userAmount, uint256 hedgerAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
userAmount | uint256 | Amount to distribute to user pool |
hedgerAmount | uint256 | Amount to distribute to hedger pool |
pauseYieldDistribution
Pauses all yield distribution operations
Emergency function to halt yield distribution during critical situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pauseYieldDistribution() external;
resumeYieldDistribution
Resumes yield distribution operations after being paused
Restarts yield distribution when emergency is resolved
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function resumeYieldDistribution() external;
getYieldShiftConfig
Returns the current yield shift configuration
Provides access to all yield shift parameters and settings
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldShiftConfig()
external
view
returns (uint256 baseShift, uint256 maxShift, uint256 adjustmentSpeed_, uint256 lastUpdate);
Returns
| Name | Type | Description |
|---|---|---|
baseShift | uint256 | Base yield shift percentage |
maxShift | uint256 | Maximum allowed yield shift |
adjustmentSpeed_ | uint256 | Speed of yield adjustments |
lastUpdate | uint256 | Timestamp of last configuration update |
isYieldDistributionActive
Checks if yield distribution is currently active
Returns false if paused or in emergency mode
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isYieldDistributionActive() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if yield distribution is active, false otherwise |
isYieldSourceAuthorized
Check if a yield source is authorized
Checks if a yield source is authorized for a specific yield type
Checks if a yield source is authorized for a specific yield type
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isYieldSourceAuthorized(address source, bytes32 yieldType) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
source | address | Source address |
yieldType | bytes32 | Yield type identifier |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if authorized |
checkAndUpdateYieldDistribution
Checks current conditions and updates yield distribution if needed
Automated function to maintain optimal yield distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function checkAndUpdateYieldDistribution() external;
forceUpdateYieldDistribution
Forces an immediate update of yield distribution
Emergency function to bypass normal update conditions and force distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function forceUpdateYieldDistribution() external;
getTimeWeightedAverage
Get time weighted average of pool history
Calculates time weighted average of pool history over a specified period
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTimeWeightedAverage(PoolSnapshot[] storage poolHistory, uint256 period, bool isUserPool)
internal
view
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolHistory | PoolSnapshot[] | Array of pool snapshots |
period | uint256 | Time period for calculation |
isUserPool | bool | Whether this is for user pool or hedger pool |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Time weighted average value |
_recordPoolSnapshot
Record pool snapshot
Records current pool metrics as a snapshot for historical tracking
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _recordPoolSnapshot() internal;
_recordPoolSnapshotWithEligibleSizes
Record pool snapshot using eligible pool sizes to prevent manipulation
SECURITY: Uses eligible pool sizes that respect holding period requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _recordPoolSnapshotWithEligibleSizes(uint256 eligibleUserPoolSize, uint256 eligibleHedgerPoolSize)
internal;
Parameters
| Name | Type | Description |
|---|---|---|
eligibleUserPoolSize | uint256 | Eligible user pool size for yield calculations |
eligibleHedgerPoolSize | uint256 | Eligible hedger pool size for yield calculations |
_addToPoolHistory
Add pool snapshot to history
Adds a pool snapshot to the history array with size management
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _addToPoolHistory(PoolSnapshot[] storage poolHistory, uint256 poolSize, bool isUserPool) internal;
Parameters
| Name | Type | Description |
|---|---|---|
poolHistory | PoolSnapshot[] | Array of pool snapshots to add to |
poolSize | uint256 | Size of the pool to record |
isUserPool | bool | Whether this is for user pool or hedger pool |
recoverToken
Recovers accidentally sent ERC20 tokens from the contract
Emergency function to recover tokens that are not part of normal operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The token address to recover |
amount | uint256 | The amount of tokens to recover |
recoverETH
Recovers accidentally sent ETH from the contract
Emergency function to recover ETH that shouldn't be in the contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
updateHoldingPeriodProtection
Update holding period protection parameters
SECURITY: Only governance can update these critical security parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateHoldingPeriodProtection(uint256 _minHoldingPeriod, uint256 _baseDiscount, uint256 _maxTimeFactor)
external;
Parameters
| Name | Type | Description |
|---|---|---|
_minHoldingPeriod | uint256 | New minimum holding period in seconds |
_baseDiscount | uint256 | New base discount percentage in basis points |
_maxTimeFactor | uint256 | New maximum time factor discount in basis points |
Events
YieldDistributionUpdated
OPTIMIZED: Indexed timestamp for efficient time-based filtering
event YieldDistributionUpdated(
uint256 newYieldShift, uint256 userYieldAllocation, uint256 hedgerYieldAllocation, uint256 indexed timestamp
);
UserYieldClaimed
event UserYieldClaimed(address indexed user, uint256 yieldAmount, uint256 timestamp);
HedgerYieldClaimed
event HedgerYieldClaimed(address indexed hedger, uint256 yieldAmount, uint256 timestamp);
YieldAdded
OPTIMIZED: Indexed source and timestamp for efficient filtering
event YieldAdded(uint256 yieldAmount, string indexed source, uint256 indexed timestamp);
YieldShiftParametersUpdated
OPTIMIZED: Indexed parameter type for efficient filtering
event YieldShiftParametersUpdated(
string indexed parameterType, uint256 baseYieldShift, uint256 maxYieldShift, uint256 adjustmentSpeed
);
HoldingPeriodProtectionUpdated
event HoldingPeriodProtectionUpdated(uint256 minHoldingPeriod, uint256 baseDiscount, uint256 maxTimeFactor);
YieldSourceAuthorized
event YieldSourceAuthorized(address indexed source, bytes32 indexed yieldType);
YieldSourceRevoked
event YieldSourceRevoked(address indexed source);
Structs
PoolSnapshot
OPTIMIZED: Packed struct for gas efficiency in historical arrays
struct PoolSnapshot {
uint128 userPoolSize;
uint128 hedgerPoolSize;
uint64 timestamp; // Timestamp (8 bytes, until year 2554)
}
YieldShiftSnapshot
OPTIMIZED: Packed struct for gas efficiency in yield shift tracking
struct YieldShiftSnapshot {
uint128 yieldShift;
uint64 timestamp; // Timestamp (8 bytes, until year 2554)
}
FeeCollector
Inherits: AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, UUPSUpgradeable
Author: Quantillon Protocol Team
Centralized fee collection and distribution contract for Quantillon Protocol
This contract handles all protocol fees from:
- QEURO minting fees
- QEURO redemption fees
- Hedger position fees
- Yield management fees
- Other protocol operations
Features:
- Centralized fee collection from all protocol contracts
- Governance-controlled fee distribution
- Multi-token fee support (USDC, QEURO, etc.)
- Fee analytics and tracking
- Emergency pause functionality
- Upgradeable via UUPS proxy
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
Governance role for fee distribution and configuration
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
TREASURY_ROLE
Treasury role for fee withdrawal
bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE")
EMERGENCY_ROLE
Emergency role for pausing and emergency operations
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
treasury
Treasury address for fee distribution
address public treasury
devFund
Protocol development fund address
address public devFund
communityFund
Community fund address
address public communityFund
treasuryRatio
Fee distribution ratios (in basis points, 10000 = 100%)
uint256 public treasuryRatio
devFundRatio
uint256 public devFundRatio
communityRatio
uint256 public communityRatio
totalFeesCollected
Total fees collected per token
mapping(address => uint256) public totalFeesCollected
totalFeesDistributed
Total fees distributed per token
mapping(address => uint256) public totalFeesDistributed
feeCollectionCount
Fee collection events per token
mapping(address => uint256) public feeCollectionCount
Functions
onlyFeeSource
Ensures only authorized contracts can collect fees
modifier onlyFeeSource() ;
initialize
Initializes the FeeCollector contract
Sets up the initial configuration for fee collection and distribution
Sets up roles, fund addresses, and default fee distribution ratios
Notes:
-
security: Protected by initializer modifier
-
validation: Validates that all addresses are non-zero
-
state-changes: Sets up roles, fund addresses, and default ratios
-
events: Emits role grant events and FundAddressesUpdated event
-
errors: Throws ZeroAddress if any address is zero
-
reentrancy: No external calls, safe
-
access: Can only be called once during initialization
-
oracle: No oracle dependencies
function initialize(address _admin, address _treasury, address _devFund, address _communityFund)
external
initializer;
Parameters
| Name | Type | Description |
|---|---|---|
_admin | address | Admin address (will receive DEFAULT_ADMIN_ROLE, GOVERNANCE_ROLE, and EMERGENCY_ROLE) |
_treasury | address | Treasury address (will receive TREASURY_ROLE) |
_devFund | address | Dev fund address (cannot be zero) |
_communityFund | address | Community fund address (cannot be zero) |
collectFees
Collects fees from protocol contracts
Transfers tokens from the caller to this contract and updates tracking variables
Only authorized fee sources can call this function
Emits FeesCollected event for transparency and analytics
Notes:
-
security: Protected by onlyFeeSource modifier and reentrancy guard
-
validation: Validates token address and amount parameters
-
state-changes: Updates totalFeesCollected and feeCollectionCount mappings
-
events: Emits FeesCollected event with collection details
-
errors: Throws InvalidAmount if amount is zero
-
errors: Throws ZeroAddress if token address is zero
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to authorized fee sources only
-
oracle: No oracle dependencies
function collectFees(address token, uint256 amount, string calldata sourceType)
external
onlyFeeSource
whenNotPaused
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to collect fees for (cannot be zero address) |
amount | uint256 | Amount of fees to collect (must be greater than zero) |
sourceType | string | Type of fee source (e.g., "minting", "redemption", "hedging") |
collectETHFees
Collects ETH fees from protocol contracts
Accepts ETH payments and updates tracking variables for ETH (tracked as address(0))
Only authorized fee sources can call this function
Emits FeesCollected event for transparency and analytics
Notes:
-
security: Protected by onlyFeeSource modifier and reentrancy guard
-
validation: Validates that msg.value is greater than zero
-
state-changes: Updates totalFeesCollected and feeCollectionCount for address(0)
-
events: Emits FeesCollected event with ETH collection details
-
errors: Throws InvalidAmount if msg.value is zero
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to authorized fee sources only
-
oracle: No oracle dependencies
function collectETHFees(string calldata sourceType) external payable onlyFeeSource whenNotPaused nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
sourceType | string | Type of fee source (e.g., "staking", "governance", "liquidation") |
distributeFees
Distributes collected fees according to configured ratios
Calculates distribution amounts based on treasuryRatio, devFundRatio, and communityRatio
Handles rounding by adjusting community amount to ensure total doesn't exceed balance
Only treasury role can call this function
Emits FeesDistributed event for transparency
Notes:
-
security: Protected by TREASURY_ROLE and reentrancy guard
-
validation: Validates that contract has sufficient balance
-
state-changes: Updates totalFeesDistributed and transfers tokens to fund addresses
-
events: Emits FeesDistributed event with distribution details
-
errors: Throws InsufficientBalance if contract balance is zero
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to TREASURY_ROLE only
-
oracle: No oracle dependencies
function distributeFees(address token) external onlyRole(TREASURY_ROLE) whenNotPaused nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to distribute (address(0) for ETH) |
_calculateDistributionAmounts
Calculate distribution amounts with rounding protection
Internal function to reduce cyclomatic complexity
Notes:
-
security: No external calls, pure calculation function
-
validation: Balance must be non-zero for meaningful distribution
-
state-changes: No state changes, view function
-
events: No events emitted
-
errors: No custom errors, uses SafeMath for overflow protection
-
reentrancy: No reentrancy risk, view function
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _calculateDistributionAmounts(uint256 balance)
internal
view
returns (uint256 treasuryAmount, uint256 devFundAmount, uint256 communityAmount);
Parameters
| Name | Type | Description |
|---|---|---|
balance | uint256 | Total balance to distribute |
Returns
| Name | Type | Description |
|---|---|---|
treasuryAmount | uint256 | Amount for treasury |
devFundAmount | uint256 | Amount for dev fund |
communityAmount | uint256 | Amount for community fund |
_executeTransfers
Execute transfers for ETH or ERC20 tokens
Internal function to reduce cyclomatic complexity
Notes:
-
security: Delegates to specific transfer functions with proper validation
-
validation: Amounts must be non-zero for transfers to execute
-
state-changes: Updates token balances through transfers
-
events: No direct events, delegated functions emit events
-
errors: May revert on transfer failures
-
reentrancy: Protected by internal function design
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _executeTransfers(address token, uint256 treasuryAmount, uint256 devFundAmount, uint256 communityAmount)
internal;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address (address(0) for ETH) |
treasuryAmount | uint256 | Amount for treasury |
devFundAmount | uint256 | Amount for dev fund |
communityAmount | uint256 | Amount for community fund |
_executeETHTransfers
Execute ETH transfers
Internal function to reduce cyclomatic complexity
Notes:
-
security: Uses secure ETH transfer with address validation
-
validation: Amounts must be non-zero for transfers to execute
-
state-changes: Reduces contract ETH balance, increases recipient balances
-
events: No direct events emitted
-
errors: Reverts with ETHTransferFailed on call failure
-
reentrancy: Protected by internal function design and address validation
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _executeETHTransfers(uint256 treasuryAmount, uint256 devFundAmount, uint256 communityAmount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
treasuryAmount | uint256 | Amount for treasury |
devFundAmount | uint256 | Amount for dev fund |
communityAmount | uint256 | Amount for community fund |
_secureETHTransfer
Secure ETH transfer with comprehensive validation
Validates recipient address against whitelist and performs secure ETH transfer
Notes:
-
security: Multiple validation layers prevent arbitrary sends:
-
Recipient must be one of three pre-authorized fund addresses
-
Addresses are validated to be non-zero and non-contract
-
Only GOVERNANCE_ROLE can update these addresses
-
This is NOT an arbitrary send as recipient is strictly controlled
-
validation: Ensures recipient is valid and amount is positive
-
state-changes: Transfers ETH from contract to recipient
-
events: No events emitted
-
errors: Reverts with ETHTransferFailed on transfer failure
-
reentrancy: Protected by address validation and call pattern
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _secureETHTransfer(address recipient, uint256 amount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
recipient | address | Address to receive ETH (must be treasury, devFund, or communityFund) |
amount | uint256 | Amount of ETH to transfer |
_executeERC20Transfers
Execute ERC20 token transfers
Internal function to reduce cyclomatic complexity
Notes:
-
security: Uses safeTransfer for ERC20 tokens with proper error handling
-
validation: Amounts must be non-zero for transfers to execute
-
state-changes: Reduces contract token balance, increases recipient balances
-
events: No direct events emitted
-
errors: May revert on transfer failures from ERC20 contract
-
reentrancy: Protected by internal function design and safeTransfer
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _executeERC20Transfers(
address token,
uint256 treasuryAmount,
uint256 devFundAmount,
uint256 communityAmount
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address |
treasuryAmount | uint256 | Amount for treasury |
devFundAmount | uint256 | Amount for dev fund |
communityAmount | uint256 | Amount for community fund |
updateFeeRatios
Updates fee distribution ratios
Sets new distribution ratios for treasury, dev fund, and community fund
Ratios must sum to exactly 10000 (100%) in basis points
Only governance role can call this function
Emits FeeRatiosUpdated event for transparency
Notes:
-
security: Protected by GOVERNANCE_ROLE
-
validation: Validates that ratios sum to exactly 10000
-
state-changes: Updates treasuryRatio, devFundRatio, and communityRatio
-
events: Emits FeeRatiosUpdated event with new ratios
-
errors: Throws InvalidRatio if ratios don't sum to 10000
-
reentrancy: No external calls, safe
-
access: Restricted to GOVERNANCE_ROLE only
-
oracle: No oracle dependencies
function updateFeeRatios(uint256 _treasuryRatio, uint256 _devFundRatio, uint256 _communityRatio)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasuryRatio | uint256 | New treasury ratio (in basis points, 10000 = 100%) |
_devFundRatio | uint256 | New dev fund ratio (in basis points, 10000 = 100%) |
_communityRatio | uint256 | New community ratio (in basis points, 10000 = 100%) |
updateFundAddresses
Updates fund addresses for fee distribution
Sets new addresses for treasury, dev fund, and community fund
All addresses must be non-zero
Only governance role can call this function
Emits FundAddressesUpdated event for transparency
Notes:
-
security: Protected by GOVERNANCE_ROLE
-
validation: Validates that all addresses are non-zero
-
state-changes: Updates treasury, devFund, and communityFund addresses
-
events: Emits FundAddressesUpdated event with new addresses
-
errors: Throws ZeroAddress if any address is zero
-
reentrancy: No external calls, safe
-
access: Restricted to GOVERNANCE_ROLE only
-
oracle: No oracle dependencies
function updateFundAddresses(address _treasury, address _devFund, address _communityFund)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address (cannot be zero) |
_devFund | address | New dev fund address (cannot be zero) |
_communityFund | address | New community fund address (cannot be zero) |
authorizeFeeSource
Authorizes a contract to collect fees
Grants TREASURY_ROLE to the specified address, allowing it to collect fees
Only governance role can call this function
Notes:
-
security: Protected by GOVERNANCE_ROLE
-
validation: Validates that feeSource is not zero address
-
state-changes: Grants TREASURY_ROLE to feeSource
-
events: Emits RoleGranted event for TREASURY_ROLE
-
errors: Throws ZeroAddress if feeSource is zero
-
reentrancy: No external calls, safe
-
access: Restricted to GOVERNANCE_ROLE only
-
oracle: No oracle dependencies
function authorizeFeeSource(address feeSource) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
feeSource | address | Contract address to authorize (cannot be zero) |
revokeFeeSource
Revokes fee collection authorization
Revokes TREASURY_ROLE from the specified address, preventing it from collecting fees
Only governance role can call this function
Notes:
-
security: Protected by GOVERNANCE_ROLE
-
validation: No validation required (can revoke from any address)
-
state-changes: Revokes TREASURY_ROLE from feeSource
-
events: Emits RoleRevoked event for TREASURY_ROLE
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Restricted to GOVERNANCE_ROLE only
-
oracle: No oracle dependencies
function revokeFeeSource(address feeSource) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
feeSource | address | Contract address to revoke authorization from |
pause
Pauses fee collection and distribution
Emergency function to pause all fee operations in case of security issues
Only emergency role can call this function
Notes:
-
security: Protected by EMERGENCY_ROLE
-
validation: No validation required
-
state-changes: Sets paused state to true
-
events: Emits Paused event
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Restricted to EMERGENCY_ROLE only
-
oracle: No oracle dependencies
function pause() external onlyRole(EMERGENCY_ROLE);
unpause
Unpauses fee collection and distribution
Resumes all fee operations after a pause
Only emergency role can call this function
Notes:
-
security: Protected by EMERGENCY_ROLE
-
validation: No validation required
-
state-changes: Sets paused state to false
-
events: Emits Unpaused event
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Restricted to EMERGENCY_ROLE only
-
oracle: No oracle dependencies
function unpause() external onlyRole(EMERGENCY_ROLE);
emergencyWithdraw
Emergency withdrawal of all tokens (only in extreme circumstances)
Emergency function to withdraw all tokens to treasury in case of critical issues
Only emergency role can call this function
Notes:
-
security: Protected by EMERGENCY_ROLE
-
validation: Validates that contract has sufficient balance
-
state-changes: Transfers all tokens to treasury address
-
events: No custom events (uses standard transfer events)
-
errors: Throws InsufficientBalance if contract balance is zero
-
errors: Throws ETHTransferFailed if ETH transfer fails
-
reentrancy: No external calls, safe
-
access: Restricted to EMERGENCY_ROLE only
-
oracle: No oracle dependencies
function emergencyWithdraw(address token) external onlyRole(EMERGENCY_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to withdraw (address(0) for ETH) |
getBalance
Returns the current balance of a token
Returns the current balance of the specified token held by this contract
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getBalance(address token) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address (address(0) for ETH) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current balance of the token in this contract |
getFeeStats
Returns fee collection statistics for a token
Returns comprehensive statistics about fee collection and distribution for a specific token
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getFeeStats(address token)
external
view
returns (uint256 totalCollected, uint256 totalDistributed, uint256 collectionCount, uint256 currentBalance);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address (address(0) for ETH) |
Returns
| Name | Type | Description |
|---|---|---|
totalCollected | uint256 | Total amount of fees collected for this token |
totalDistributed | uint256 | Total amount of fees distributed for this token |
collectionCount | uint256 | Number of fee collection transactions for this token |
currentBalance | uint256 | Current balance of this token in the contract |
isAuthorizedFeeSource
Checks if an address is authorized to collect fees
Returns whether the specified address has permission to collect fees
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function isAuthorizedFeeSource(address feeSource) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
feeSource | address | Address to check for authorization |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the address is authorized to collect fees, false otherwise |
_isAuthorizedFeeSource
Internal function to check if an address is authorized to collect fees
Internal helper function to check TREASURY_ROLE for fee collection authorization
Notes:
-
security: Internal function, no direct security implications
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (internal function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Internal function only
-
oracle: No oracle dependencies
function _isAuthorizedFeeSource(address feeSource) internal view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
feeSource | address | Address to check for authorization |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the address has TREASURY_ROLE, false otherwise |
_authorizeUpgrade
Authorizes upgrades (only governance)
Internal function to authorize contract upgrades via UUPS proxy pattern
Only governance role can authorize upgrades
Notes:
-
security: Protected by GOVERNANCE_ROLE
-
validation: No validation required (OpenZeppelin handles this)
-
state-changes: No state changes (authorization only)
-
events: No custom events (OpenZeppelin handles upgrade events)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Restricted to GOVERNANCE_ROLE only
-
oracle: No oracle dependencies
function _authorizeUpgrade(address newImplementation) internal override onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
Events
FeesCollected
Emitted when fees are collected
event FeesCollected(address indexed token, uint256 amount, address indexed source, string indexed sourceType);
FeesDistributed
Emitted when fees are distributed
event FeesDistributed(
address indexed token,
uint256 totalAmount,
uint256 treasuryAmount,
uint256 devFundAmount,
uint256 communityAmount
);
FeeRatiosUpdated
Emitted when fee distribution ratios are updated
event FeeRatiosUpdated(uint256 treasuryRatio, uint256 devFundRatio, uint256 communityRatio);
FundAddressesUpdated
Emitted when fund addresses are updated
event FundAddressesUpdated(address treasury, address devFund, address communityFund);
HedgerPool
Inherits: Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable, PausableUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Optimized EUR/USD hedging pool for managing currency risk and providing yield
Optimized version with reduced contract size through library extraction and code consolidation
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
LIQUIDATOR_ROLE
bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE")
EMERGENCY_ROLE
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
HEDGER_ROLE
bytes32 public constant HEDGER_ROLE = keccak256("HEDGER_ROLE")
usdc
IERC20 public usdc
oracle
IChainlinkOracle public oracle
yieldShift
IYieldShift public yieldShift
vault
IQuantillonVault public vault
treasury
address public treasury
TIME_PROVIDER
TimeProvider public immutable TIME_PROVIDER
coreParams
CoreParams public coreParams
totalMargin
uint256 public totalMargin
totalExposure
uint256 public totalExposure
activeHedgers
uint256 public activeHedgers
nextPositionId
uint256 public nextPositionId
isWhitelistedHedger
mapping(address => bool) public isWhitelistedHedger
hedgerWhitelistEnabled
bool public hedgerWhitelistEnabled
positions
mapping(uint256 => HedgePosition) public positions
hedgers
mapping(address => HedgerInfo) public hedgers
activePositionCount
mapping(address => uint256) public activePositionCount
hedgerHasPosition
mapping(address => mapping(uint256 => bool)) public hedgerHasPosition
positionIndex
mapping(address => mapping(uint256 => uint256)) public positionIndex
liquidationCommitments
mapping(bytes32 => bool) public liquidationCommitments
liquidationCommitmentTimes
mapping(bytes32 => uint256) public liquidationCommitmentTimes
lastLiquidationAttempt
mapping(address => uint256) public lastLiquidationAttempt
hasPendingLiquidation
mapping(address => mapping(uint256 => bool)) public hasPendingLiquidation
hedgerLastRewardBlock
mapping(address => uint256) public hedgerLastRewardBlock
MAX_POSITIONS_PER_HEDGER
uint256 public constant MAX_POSITIONS_PER_HEDGER = 50
MAX_UINT96_VALUE
uint96 public constant MAX_UINT96_VALUE = type(uint96).max
MAX_POSITION_SIZE
uint256 public constant MAX_POSITION_SIZE = MAX_UINT96_VALUE
MAX_MARGIN
uint256 public constant MAX_MARGIN = MAX_UINT96_VALUE
MAX_ENTRY_PRICE
uint256 public constant MAX_ENTRY_PRICE = MAX_UINT96_VALUE
MAX_LEVERAGE
uint256 public constant MAX_LEVERAGE = type(uint16).max
MAX_MARGIN_RATIO
uint256 public constant MAX_MARGIN_RATIO = 5000
MAX_UINT128_VALUE
uint128 public constant MAX_UINT128_VALUE = type(uint128).max
MAX_TOTAL_MARGIN
uint256 public constant MAX_TOTAL_MARGIN = MAX_UINT128_VALUE
MAX_TOTAL_EXPOSURE
uint256 public constant MAX_TOTAL_EXPOSURE = MAX_UINT128_VALUE
MAX_PENDING_REWARDS
uint256 public constant MAX_PENDING_REWARDS = MAX_UINT128_VALUE
LIQUIDATION_COOLDOWN
uint256 public constant LIQUIDATION_COOLDOWN = 300
MAX_REWARD_PERIOD
uint256 public constant MAX_REWARD_PERIOD = 365 days
Functions
flashLoanProtection
modifier flashLoanProtection() ;
secureNonReentrant
modifier secureNonReentrant() ;
constructor
Initializes the HedgerPool contract with a time provider
Constructor that sets up the time provider and disables initializers for upgrade safety
Notes:
-
security: Validates that the time provider is not zero address
-
validation: Ensures TIME_PROVIDER is a valid contract address
-
state-changes: Sets TIME_PROVIDER and disables initializers
-
events: None
-
errors: Throws ZeroAddress if _TIME_PROVIDER is address(0)
-
reentrancy: Not applicable - constructor
-
access: Public constructor
-
oracle: Not applicable
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | The time provider contract for timestamp management |
initialize
Initializes the HedgerPool with contracts and parameters
This function configures:
- Access roles and permissions
- References to external contracts
- Default protocol parameters
- Security (pause, reentrancy, upgrades)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Initializes all contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by initializer modifier
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(
address admin,
address _usdc,
address _oracle,
address _yieldShift,
address _timelock,
address _treasury,
address _vault
) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address with administrator privileges |
_usdc | address | Address of the USDC token contract |
_oracle | address | Address of the Oracle contract |
_yieldShift | address | Address of the YieldShift contract |
_timelock | address | Address of the timelock contract |
_treasury | address | Address of the treasury contract |
_vault | address | Address of the QuantillonVault contract |
enterHedgePosition
Opens a new hedge position for a hedger
Position opening process:
- Validates hedger whitelist status
- Fetches current EUR/USD price from oracle
- Calculates position size and validates parameters
- Transfers USDC to vault for unified liquidity
- Creates position record and updates hedger stats
Security features:
- Flash loan protection via secureNonReentrant
- Whitelist validation if enabled
- Parameter validation (leverage, amounts)
- Oracle price validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates amount > 0, leverage within limits, hedger whitelist
-
state-changes: Creates new position, updates hedger stats, transfers USDC to vault
-
events: Emits HedgePositionOpened with position details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by secureNonReentrant modifier and proper CEI pattern
-
access: Restricted to whitelisted hedgers (if whitelist enabled)
-
oracle: Requires fresh oracle price data
function enterHedgePosition(uint256 usdcAmount, uint256 leverage)
external
secureNonReentrant
returns (uint256 positionId);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC to deposit as margin (6 decimals) |
leverage | uint256 | Leverage multiplier for the position (1-20x) |
Returns
| Name | Type | Description |
|---|---|---|
positionId | uint256 | Unique identifier for the new position |
exitHedgePosition
Closes an existing hedge position
Position closing process:
- Validates position ownership and active status
- Checks protocol collateralization safety
- Calculates current PnL based on price change
- Determines net payout to hedger
- Updates hedger stats and removes position
- Withdraws USDC from vault for hedger payout
Security features:
- Position ownership validation
- Protocol collateralization safety check
- Pause protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates position ownership, active status, and protocol safety
-
state-changes: Closes position, updates hedger stats, withdraws USDC from vault
-
events: Emits HedgePositionClosed with position details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by whenNotPaused modifier
-
access: Restricted to position owner
-
oracle: Requires fresh oracle price data
function exitHedgePosition(uint256 positionId) external whenNotPaused returns (int256 pnl);
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | Unique identifier of the position to close |
Returns
| Name | Type | Description |
|---|---|---|
pnl | int256 | Profit or loss from the position (positive = profit, negative = loss) |
addMargin
Adds additional margin to an existing hedge position
Margin addition process:
- Validates position ownership and active status
- Validates amount is positive
- Checks liquidation cooldown and pending liquidation status
- Transfers USDC from hedger to vault
- Updates position margin and hedger stats
Security features:
- Flash loan protection
- Position ownership validation
- Liquidation cooldown validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates position ownership, active status, positive amount, liquidation cooldown
-
state-changes: Updates position margin, hedger stats, transfers USDC to vault
-
events: Emits MarginAdded with position details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by flashLoanProtection modifier
-
access: Restricted to position owner
-
oracle: No oracle dependencies
function addMargin(uint256 positionId, uint256 amount) external flashLoanProtection;
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | Unique identifier of the position |
amount | uint256 | Amount of USDC to add as margin (6 decimals) |
removeMargin
Removes margin from an existing hedge position
Margin removal process:
- Validates position ownership and active status
- Validates amount is positive
- Validates margin operation maintains minimum margin ratio
- Updates position margin and hedger stats
- Withdraws USDC from vault to hedger
Security features:
- Flash loan protection
- Position ownership validation
- Minimum margin ratio validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates position ownership, active status, positive amount, minimum margin ratio
-
state-changes: Updates position margin, hedger stats, withdraws USDC from vault
-
events: Emits MarginUpdated with position details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by flashLoanProtection modifier
-
access: Restricted to position owner
-
oracle: No oracle dependencies
function removeMargin(uint256 positionId, uint256 amount) external flashLoanProtection;
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | Unique identifier of the position |
amount | uint256 | Amount of USDC to remove from margin (6 decimals) |
commitLiquidation
Commits to liquidating a hedger position with a salt for MEV protection
Creates a liquidation commitment that must be executed within a time window
Notes:
-
security: Requires LIQUIDATOR_ROLE, validates addresses and position ID
-
validation: Ensures hedger is valid address, positionId > 0, commitment doesn't exist
-
state-changes: Sets liquidation commitment, timing, and pending liquidation flags
-
events: None (commitment phase)
-
errors: Throws InvalidRole, InvalidAddress, InvalidPosition, or CommitmentExists
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to LIQUIDATOR_ROLE
-
oracle: Not applicable
function commitLiquidation(address hedger, uint256 positionId, bytes32 salt) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position will be liquidated |
positionId | uint256 | ID of the position to liquidate |
salt | bytes32 | Random salt for commitment uniqueness and MEV protection |
liquidateHedger
Liquidates an undercollateralized hedge position
Liquidation process:
- Validates liquidator role and commitment
- Validates position ownership and active status
- Calculates liquidation reward and remaining margin
- Updates hedger stats and removes position
- Withdraws USDC from vault for liquidator reward and remaining margin
Security features:
- Role-based access control (LIQUIDATOR_ROLE)
- Commitment validation to prevent front-running
- Reentrancy protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates liquidator role, commitment, position ownership, active status
-
state-changes: Liquidates position, updates hedger stats, withdraws USDC from vault
-
events: Emits HedgerLiquidated with liquidation details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to LIQUIDATOR_ROLE
-
oracle: Requires fresh oracle price data
function liquidateHedger(address hedger, uint256 positionId, bytes32 salt)
external
nonReentrant
returns (uint256 liquidationReward);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to liquidate |
positionId | uint256 | Unique identifier of the position to liquidate |
salt | bytes32 | Random salt for commitment validation |
Returns
| Name | Type | Description |
|---|---|---|
liquidationReward | uint256 | Amount of USDC reward for the liquidator |
claimHedgingRewards
Claims hedging rewards for a hedger
Reward claiming process:
- Calculates interest differential based on exposure and rates
- Calculates yield shift rewards from YieldShift contract
- Updates hedger's last reward block
- Transfers total rewards to hedger
Security features:
- Reentrancy protection
- Reward calculation validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates hedger has active positions and rewards available
-
state-changes: Updates hedger reward tracking, transfers rewards
-
events: Emits HedgingRewardsClaimed with reward details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to hedgers with active positions
-
oracle: No oracle dependencies
function claimHedgingRewards()
external
nonReentrant
returns (uint256 interestDifferential, uint256 yieldShiftRewards, uint256 totalRewards);
Returns
| Name | Type | Description |
|---|---|---|
interestDifferential | uint256 | Interest differential rewards earned |
yieldShiftRewards | uint256 | Yield shift rewards earned |
totalRewards | uint256 | Total rewards claimed |
getHedgerPosition
Retrieves detailed information about a specific hedger position
Returns position data including current oracle price for real-time calculations
Notes:
-
security: Validates that the caller owns the position
-
validation: Ensures position exists and hedger matches
-
state-changes: None (view function with oracle call)
-
events: None
-
errors: Throws InvalidHedger if position doesn't belong to hedger
-
reentrancy: Protected by nonReentrant modifier
-
access: Public (anyone can query position data)
-
oracle: Calls _getValidOraclePrice() for current price
function getHedgerPosition(address hedger, uint256 positionId)
external
view
returns (
uint256 positionSize,
uint256 margin,
uint256 entryPrice,
uint256 currentPrice,
uint256 leverage,
uint256 lastUpdateTime
);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | ID of the position to retrieve |
Returns
| Name | Type | Description |
|---|---|---|
positionSize | uint256 | Current size of the position in USDC |
margin | uint256 | Current margin amount for the position |
entryPrice | uint256 | Price at which the position was opened |
currentPrice | uint256 | Current EUR/USD price from oracle |
leverage | uint256 | Leverage multiplier for the position |
lastUpdateTime | uint256 | Timestamp of last position update |
getHedgerMarginRatio
Calculates the current margin ratio for a hedger position
Returns margin ratio as basis points (10000 = 100%)
Notes:
-
security: Validates that the caller owns the position
-
validation: Ensures position exists and hedger matches
-
state-changes: None (view function)
-
events: None
-
errors: Throws InvalidHedger if position doesn't belong to hedger
-
reentrancy: Not applicable - view function
-
access: Public (anyone can query margin ratio)
-
oracle: Not applicable
function getHedgerMarginRatio(address hedger, uint256 positionId) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | ID of the position to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current margin ratio in basis points (margin/positionSize * 10000) |
isHedgerLiquidatable
Checks if a hedger position is eligible for liquidation
Uses current oracle price to determine if position is undercollateralized
Notes:
-
security: Validates that the caller owns the position
-
validation: Ensures position exists, is active, and hedger matches
-
state-changes: None (view function with oracle call)
-
events: None
-
errors: Throws InvalidHedger if position doesn't belong to hedger
-
reentrancy: Protected by nonReentrant modifier
-
access: Public (anyone can check liquidation status)
-
oracle: Calls _getValidOraclePrice() for current price comparison
function isHedgerLiquidatable(address hedger, uint256 positionId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | ID of the position to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if position can be liquidated, false otherwise |
getTotalHedgeExposure
Returns the total hedge exposure across all active positions
Provides aggregate exposure for risk management and monitoring
Notes:
-
security: No security validations required for view function
-
validation: None required for view function
-
state-changes: None (view function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - view function
-
access: Public (anyone can query total exposure)
-
oracle: Not applicable
function getTotalHedgeExposure() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total exposure amount in USDC across all active hedge positions |
updateHedgingParameters
Updates core hedging parameters for the protocol
Allows governance to adjust risk parameters for hedge positions
Notes:
-
security: Requires GOVERNANCE_ROLE, validates parameter ranges
-
validation: Ensures minMarginRatio >= 500, liquidationThreshold < minMarginRatio, maxLeverage <= 20, liquidationPenalty <= 1000
-
state-changes: Updates coreParams struct with new values
-
events: None
-
errors: Throws InvalidRole, ConfigValueTooLow, ConfigInvalid, or ConfigValueTooHigh
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: Not applicable
function updateHedgingParameters(
uint256 newMinMarginRatio,
uint256 newLiquidationThreshold,
uint256 newMaxLeverage,
uint256 newLiquidationPenalty
) external;
Parameters
| Name | Type | Description |
|---|---|---|
newMinMarginRatio | uint256 | New minimum margin ratio in basis points (minimum 500 = 5%) |
newLiquidationThreshold | uint256 | New liquidation threshold in basis points (must be < minMarginRatio) |
newMaxLeverage | uint256 | New maximum leverage multiplier (maximum 20x) |
newLiquidationPenalty | uint256 | New liquidation penalty in basis points (maximum 1000 = 10%) |
updateInterestRates
Updates interest rates for EUR and USD positions
Allows governance to adjust interest rates for yield calculations
Notes:
-
security: Requires GOVERNANCE_ROLE, validates rate limits
-
validation: Ensures both rates are <= 2000 basis points (20%)
-
state-changes: Updates coreParams with new interest rates
-
events: None
-
errors: Throws InvalidRole or ConfigValueTooHigh
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: Not applicable
function updateInterestRates(uint256 newEurRate, uint256 newUsdRate) external;
Parameters
| Name | Type | Description |
|---|---|---|
newEurRate | uint256 | New EUR interest rate in basis points (maximum 2000 = 20%) |
newUsdRate | uint256 | New USD interest rate in basis points (maximum 2000 = 20%) |
setHedgingFees
Sets the fee structure for hedge positions
Allows governance to adjust fees for position entry, exit, and margin operations
Notes:
-
security: Requires GOVERNANCE_ROLE, validates fee limits
-
validation: Ensures entryFee <= 100, exitFee <= 100, marginFee <= 50
-
state-changes: Updates coreParams with new fee values
-
events: None
-
errors: Throws InvalidRole or InvalidFee
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: Not applicable
function setHedgingFees(uint256 _entryFee, uint256 _exitFee, uint256 _marginFee) external;
Parameters
| Name | Type | Description |
|---|---|---|
_entryFee | uint256 | New entry fee in basis points (maximum 100 = 1%) |
_exitFee | uint256 | New exit fee in basis points (maximum 100 = 1%) |
_marginFee | uint256 | New margin fee in basis points (maximum 50 = 0.5%) |
emergencyClosePosition
Emergency closure of a hedge position by governance
Emergency closure process:
- Validates emergency role and position ownership
- Validates position is active
- Updates hedger stats and removes position
- Withdraws USDC from vault for hedger's margin
Security features:
- Role-based access control (EMERGENCY_ROLE)
- Position ownership validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates emergency role, position ownership, active status
-
state-changes: Closes position, updates hedger stats, withdraws USDC from vault
-
events: Emits EmergencyPositionClosed with position details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Not protected - emergency function
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies
function emergencyClosePosition(address hedger, uint256 positionId) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position to close |
positionId | uint256 | Unique identifier of the position to close |
pause
Pauses all contract operations in case of emergency
Emergency function to halt all user interactions
Notes:
-
security: Requires EMERGENCY_ROLE
-
validation: None required
-
state-changes: Sets contract to paused state
-
events: Emits Paused event
-
errors: Throws InvalidRole if caller lacks EMERGENCY_ROLE
-
reentrancy: Not applicable
-
access: Restricted to EMERGENCY_ROLE
-
oracle: Not applicable
function pause() external;
unpause
Unpauses contract operations after emergency
Resumes normal contract functionality
Notes:
-
security: Requires EMERGENCY_ROLE
-
validation: None required
-
state-changes: Sets contract to unpaused state
-
events: Emits Unpaused event
-
errors: Throws InvalidRole if caller lacks EMERGENCY_ROLE
-
reentrancy: Not applicable
-
access: Restricted to EMERGENCY_ROLE
-
oracle: Not applicable
function unpause() external;
hasPendingLiquidationCommitment
Checks if a position has a pending liquidation commitment
Returns true if a liquidation commitment exists for the position
Notes:
-
security: No security validations required for view function
-
validation: None required for view function
-
state-changes: None (view function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - view function
-
access: Public (anyone can query commitment status)
-
oracle: Not applicable
function hasPendingLiquidationCommitment(address hedger, uint256 positionId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | ID of the position to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if liquidation commitment exists, false otherwise |
getHedgingConfig
Returns the current hedging configuration parameters
Provides access to all core hedging parameters for external contracts
Notes:
-
security: No security validations required for view function
-
validation: None required for view function
-
state-changes: None (view function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - view function
-
access: Public (anyone can query configuration)
-
oracle: Not applicable
function getHedgingConfig()
external
view
returns (
uint256 minMarginRatio_,
uint256 liquidationThreshold_,
uint256 maxLeverage_,
uint256 liquidationPenalty_,
uint256 entryFee_,
uint256 exitFee_
);
Returns
| Name | Type | Description |
|---|---|---|
minMarginRatio_ | uint256 | Current minimum margin ratio in basis points |
liquidationThreshold_ | uint256 | Current liquidation threshold in basis points |
maxLeverage_ | uint256 | Current maximum leverage multiplier |
liquidationPenalty_ | uint256 | Current liquidation penalty in basis points |
entryFee_ | uint256 | Current entry fee in basis points |
exitFee_ | uint256 | Current exit fee in basis points |
marginFee
Returns the current margin fee rate
Provides the margin fee for margin operations
Notes:
-
security: No security validations required for view function
-
validation: None required for view function
-
state-changes: None (view function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - view function
-
access: Public (anyone can query margin fee)
-
oracle: Not applicable
function marginFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current margin fee in basis points |
getMaxValues
Returns the maximum allowed values for various parameters
Provides hard limits for position sizes, margins, and other constraints
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Public (anyone can query max values)
-
oracle: Not applicable
function getMaxValues()
external
pure
returns (
uint256 maxPositionSize,
uint256 maxMargin,
uint256 maxEntryPrice,
uint256 maxLeverageValue,
uint256 maxTotalMargin,
uint256 maxTotalExposure,
uint256 maxPendingRewards
);
Returns
| Name | Type | Description |
|---|---|---|
maxPositionSize | uint256 | Maximum position size in USDC |
maxMargin | uint256 | Maximum margin per position in USDC |
maxEntryPrice | uint256 | Maximum entry price for positions |
maxLeverageValue | uint256 | Maximum leverage multiplier |
maxTotalMargin | uint256 | Maximum total margin across all positions |
maxTotalExposure | uint256 | Maximum total exposure across all positions |
maxPendingRewards | uint256 | Maximum pending rewards amount |
isHedgingActive
Checks if hedging operations are currently active
Returns true if contract is not paused, false if paused
Notes:
-
security: No security validations required for view function
-
validation: None required for view function
-
state-changes: None (view function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - view function
-
access: Public (anyone can query hedging status)
-
oracle: Not applicable
function isHedgingActive() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if hedging is active, false if paused |
clearExpiredLiquidationCommitment
Clears expired liquidation commitments after cooldown period
Allows liquidators to clean up expired commitments
Notes:
-
security: Requires LIQUIDATOR_ROLE, checks cooldown period
-
validation: Ensures cooldown period has passed
-
state-changes: Clears pending liquidation flag if expired
-
events: None
-
errors: Throws InvalidRole if caller lacks LIQUIDATOR_ROLE
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to LIQUIDATOR_ROLE
-
oracle: Not applicable
function clearExpiredLiquidationCommitment(address hedger, uint256 positionId) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose commitment to clear |
positionId | uint256 | ID of the position whose commitment to clear |
cancelLiquidationCommitment
Cancels a liquidation commitment before execution
Allows liquidators to cancel their own commitments
Notes:
-
security: Requires LIQUIDATOR_ROLE, validates commitment exists
-
validation: Ensures commitment exists and belongs to caller
-
state-changes: Deletes commitment data and clears pending liquidation flag
-
events: None
-
errors: Throws InvalidRole or CommitmentNotFound
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to LIQUIDATOR_ROLE
-
oracle: Not applicable
function cancelLiquidationCommitment(address hedger, uint256 positionId, bytes32 salt) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position was committed for liquidation |
positionId | uint256 | ID of the position whose commitment to cancel |
salt | bytes32 | Salt used in the original commitment |
recoverToken
Recovers accidentally sent tokens to the treasury
Emergency function to recover tokens sent to the contract
Notes:
-
security: Requires DEFAULT_ADMIN_ROLE
-
validation: None required
-
state-changes: Transfers tokens from contract to treasury
-
events: None
-
errors: Throws InvalidRole if caller lacks DEFAULT_ADMIN_ROLE
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: Not applicable
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Address of the token to recover |
amount | uint256 | Amount of tokens to recover |
recoverETH
Recovers accidentally sent ETH to the treasury
Emergency function to recover ETH sent to the contract
Notes:
-
security: Requires DEFAULT_ADMIN_ROLE
-
validation: None required
-
state-changes: Transfers ETH from contract to treasury
-
events: Emits ETHRecovered event
-
errors: Throws InvalidRole if caller lacks DEFAULT_ADMIN_ROLE
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: Not applicable
function recoverETH() external;
updateTreasury
Updates the treasury address for fee collection
Allows governance to change the treasury address
Notes:
-
security: Requires GOVERNANCE_ROLE, validates address
-
validation: Ensures treasury is not zero address and passes validation
-
state-changes: Updates treasury address
-
events: Emits TreasuryUpdated event
-
errors: Throws InvalidRole, InvalidAddress, or zero address error
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: Not applicable
function updateTreasury(address _treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address for fee collection |
updateVault
Updates the vault address for USDC management
Allows governance to change the vault contract address
Notes:
-
security: Requires GOVERNANCE_ROLE, validates address
-
validation: Ensures vault is not zero address
-
state-changes: Updates vault address
-
events: Emits VaultUpdated event
-
errors: Throws InvalidRole or InvalidAddress
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: Not applicable
function updateVault(address _vault) external;
Parameters
| Name | Type | Description |
|---|---|---|
_vault | address | New vault address for USDC operations |
updateOracle
Updates the oracle address
Governance-only setter to allow phased wiring after minimal initialization
function updateOracle(address _oracle) external;
Parameters
| Name | Type | Description |
|---|---|---|
_oracle | address | New oracle address |
updateYieldShift
Updates the YieldShift address
Governance-only setter to allow phased wiring after minimal initialization
function updateYieldShift(address _yieldShift) external;
Parameters
| Name | Type | Description |
|---|---|---|
_yieldShift | address | New YieldShift address |
whitelistHedger
Whitelists a hedger address for position opening
Whitelisting process:
- Validates governance role and hedger address
- Checks hedger is not already whitelisted
- Adds hedger to whitelist and grants HEDGER_ROLE
Security features:
- Role-based access control (GOVERNANCE_ROLE)
- Address validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates governance role, hedger address, not already whitelisted
-
state-changes: Adds hedger to whitelist, grants HEDGER_ROLE
-
events: Emits HedgerWhitelisted with hedger and caller details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Not protected - governance function
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function whitelistHedger(address hedger) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to whitelist |
removeHedger
Removes a hedger from the whitelist
Removal process:
- Validates governance role and hedger address
- Checks hedger is currently whitelisted
- Removes hedger from whitelist and revokes HEDGER_ROLE
Security features:
- Role-based access control (GOVERNANCE_ROLE)
- Address validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates governance role, hedger address, currently whitelisted
-
state-changes: Removes hedger from whitelist, revokes HEDGER_ROLE
-
events: Emits HedgerRemoved with hedger and caller details
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Not protected - governance function
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function removeHedger(address hedger) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to remove from whitelist |
toggleHedgerWhitelistMode
Toggles the hedger whitelist mode on/off
Whitelist mode toggle:
- Validates governance role
- Updates hedgerWhitelistEnabled state
- Emits event for transparency
When enabled: Only whitelisted hedgers can open positions
When disabled: Any address can open positions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates governance role
-
state-changes: Updates hedgerWhitelistEnabled state
-
events: Emits HedgerWhitelistModeToggled with new state and caller
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Not protected - governance function
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function toggleHedgerWhitelistMode(bool enabled) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable or disable the whitelist mode |
_getValidOraclePrice
Gets a valid EUR/USD price from the oracle
Internal function to fetch and validate oracle price
Notes:
-
security: Validates oracle price is valid
-
validation: Validates oracle price is valid
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws InvalidOraclePrice if price is invalid
-
reentrancy: Not protected - internal function
-
access: Internal function - no access restrictions
-
oracle: Requires fresh oracle price data
function _getValidOraclePrice() internal view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | price Valid EUR/USD price from oracle |
_validateRole
Validates that the caller has the required role
Internal function to check role-based access control
Notes:
-
security: Validates caller has the specified role
-
validation: Checks role against AccessControlLibrary
-
state-changes: None (view function)
-
events: None
-
errors: Throws InvalidRole if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function
-
oracle: Not applicable
function _validateRole(bytes32 role) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to validate against |
_removePositionFromArrays
Removes a position from the hedger's position arrays
Internal function to maintain position tracking arrays
Notes:
-
security: Validates position exists before removal
-
validation: Ensures position exists in hedger's array
-
state-changes: Removes position from arrays and updates indices
-
events: None
-
errors: Throws PositionNotFound if position doesn't exist
-
reentrancy: Not applicable - internal function
-
access: Internal function
-
oracle: Not applicable
function _removePositionFromArrays(address hedger, uint256 positionId) internal;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position to remove |
positionId | uint256 | ID of the position to remove |
_packPositionOpenData
Packs position open data into a single bytes32 for gas efficiency
Encodes position size, margin, leverage, and entry price into a compact format
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: Uses provided entryPrice parameter
function _packPositionOpenData(uint256 positionSize, uint256 margin, uint256 leverage, uint256 entryPrice)
internal
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
positionSize | uint256 | Size of the position in USDC |
margin | uint256 | Margin amount for the position |
leverage | uint256 | Leverage multiplier for the position |
entryPrice | uint256 | Price at which the position was opened |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
_packPositionCloseData
Packs position close data into a single bytes32 for gas efficiency
Encodes exit price, PnL, and timestamp into a compact format
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: Not applicable
function _packPositionCloseData(uint256 exitPrice, int256 pnl, uint256 timestamp) internal pure returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
exitPrice | uint256 | Price at which the position was closed |
pnl | int256 | Profit or loss from the position (can be negative) |
timestamp | uint256 | Timestamp when the position was closed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
_packMarginData
Packs margin data into a single bytes32 for gas efficiency
Encodes margin amount, new margin ratio, and operation type
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: Not applicable
function _packMarginData(uint256 marginAmount, uint256 newMarginRatio, bool isAdded)
internal
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
marginAmount | uint256 | Amount of margin added or removed |
newMarginRatio | uint256 | New margin ratio after the operation |
isAdded | bool | True if margin was added, false if removed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
_packLiquidationData
Packs liquidation data into a single bytes32 for gas efficiency
Encodes liquidation reward and remaining margin
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: Not applicable
function _packLiquidationData(uint256 liquidationReward, uint256 remainingMargin) internal pure returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
liquidationReward | uint256 | Reward paid to the liquidator |
remainingMargin | uint256 | Margin remaining after liquidation |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
_packRewardData
Packs reward data into a single bytes32 for gas efficiency
Encodes interest differential, yield shift rewards, and total rewards
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: Not applicable
function _packRewardData(uint256 interestDifferential, uint256 yieldShiftRewards, uint256 totalRewards)
internal
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
interestDifferential | uint256 | Interest rate differential between EUR and USD |
yieldShiftRewards | uint256 | Rewards from yield shifting operations |
totalRewards | uint256 | Total rewards accumulated |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
_validatePositionClosureSafety
Validates that closing a position won't cause protocol undercollateralization
Checks if closing the position would make the protocol undercollateralized for QEURO minting
Notes:
-
security: Validates protocol collateralization status
-
validation: Checks vault collateralization ratio
-
state-changes: No state changes - validation only
-
events: No events emitted
-
errors: Throws PositionClosureRestricted if closure would cause undercollateralization
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _validatePositionClosureSafety(
uint256,
/* positionId */
uint256 positionMargin
)
internal
view;
Parameters
| Name | Type | Description |
|---|---|---|
<none> | uint256 | |
positionMargin | uint256 | The margin amount of the position being closed |
Events
HedgePositionOpened
event HedgePositionOpened(address indexed hedger, uint256 indexed positionId, bytes32 packedData);
HedgePositionClosed
event HedgePositionClosed(address indexed hedger, uint256 indexed positionId, bytes32 packedData);
MarginUpdated
event MarginUpdated(address indexed hedger, uint256 indexed positionId, bytes32 packedData);
HedgerLiquidated
event HedgerLiquidated(
address indexed hedger, uint256 indexed positionId, address indexed liquidator, bytes32 packedData
);
HedgingRewardsClaimed
event HedgingRewardsClaimed(address indexed hedger, bytes32 packedData);
HedgerWhitelisted
event HedgerWhitelisted(address indexed hedger, address indexed caller);
HedgerRemoved
event HedgerRemoved(address indexed hedger, address indexed caller);
HedgerWhitelistModeToggled
event HedgerWhitelistModeToggled(bool enabled, address indexed caller);
ETHRecovered
event ETHRecovered(address indexed to, uint256 indexed amount);
TreasuryUpdated
event TreasuryUpdated(address indexed treasury);
VaultUpdated
event VaultUpdated(address indexed vault);
Structs
CoreParams
struct CoreParams {
uint64 minMarginRatio;
uint64 liquidationThreshold;
uint16 maxLeverage;
uint16 liquidationPenalty;
uint16 entryFee;
uint16 exitFee;
uint16 marginFee;
uint16 eurInterestRate;
uint16 usdInterestRate;
uint8 reserved;
}
HedgePosition
struct HedgePosition {
address hedger;
uint96 positionSize;
uint96 margin;
uint96 entryPrice;
uint32 entryTime;
uint32 lastUpdateTime;
int128 unrealizedPnL;
uint16 leverage;
bool isActive;
}
HedgerInfo
struct HedgerInfo {
uint256[] positionIds;
uint128 totalMargin;
uint128 totalExposure;
uint128 pendingRewards;
uint64 lastRewardClaim;
bool isActive;
}
QEUROToken
Inherits: Initializable, ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Euro-pegged stablecoin token for the Quantillon protocol
Main characteristics:
- Standard ERC20 with 18 decimals
- Mint/Burn controlled only by the vault
- Emergency pause in case of issues
- Upgradeable via UUPS pattern
- Dynamic supply cap for governance flexibility
- Blacklist/whitelist functionality for compliance
- Rate limiting for mint/burn operations
- Decimal precision handling for external price feeds
Security features:
- Role-based access control for all critical operations
- Emergency pause mechanism for crisis situations
- Rate limiting to prevent abuse
- Blacklist/whitelist for regulatory compliance
- Upgradeable architecture for future improvements
Tokenomics:
- Initial supply: 0 (all tokens minted through vault operations)
- Maximum supply: Configurable by governance (default 100M QEURO)
- Decimals: 18 (standard for ERC20 tokens)
- Peg: 1:1 with Euro (managed by vault operations)
Note: security-contact: team@quantillon.money
State Variables
MINTER_ROLE
Role for minting tokens (assigned to QuantillonVault only)
keccak256 hash avoids role collisions with other contracts
Only the vault should have this role to maintain tokenomics
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE")
BURNER_ROLE
Role for burning tokens (assigned to QuantillonVault only)
keccak256 hash avoids role collisions with other contracts
Only the vault should have this role to maintain tokenomics
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE")
PAUSER_ROLE
Role for pausing the contract in emergency situations
keccak256 hash avoids role collisions with other contracts
Should be assigned to governance or emergency multisig
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE")
COMPLIANCE_ROLE
Role for managing blacklist/whitelist for compliance
keccak256 hash avoids role collisions with other contracts
Should be assigned to compliance team or governance
bytes32 public constant COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE")
DEFAULT_MAX_SUPPLY
Default maximum supply limit (100 million QEURO)
Can be updated by governance through updateMaxSupply()
Value: 100,000,000 * 10^18 = 100,000,000 QEURO
uint256 public constant DEFAULT_MAX_SUPPLY = 100_000_000 * 1e18
MAX_RATE_LIMIT
Maximum rate limit for mint/burn operations (per reset period)
Prevents abuse and provides time for emergency response
Value: 10,000,000 * 10^18 = 10,000,000 QEURO per reset period (~300 blocks)
uint256 public constant MAX_RATE_LIMIT = 10_000_000 * 1e18
RATE_LIMIT_RESET_PERIOD
Rate limit reset period in blocks (~1 hour assuming 12 second blocks)
Using block numbers instead of timestamps for security against miner manipulation
uint256 public constant RATE_LIMIT_RESET_PERIOD = 300
PRECISION
Precision for decimal calculations (18 decimals)
Standard precision used throughout the protocol
Value: 10^18
uint256 public constant PRECISION = 1e18
MAX_BATCH_SIZE
Maximum batch size for mint operations to prevent DoS
Prevents out-of-gas attacks through large arrays
uint256 public constant MAX_BATCH_SIZE = 100
MAX_COMPLIANCE_BATCH_SIZE
Maximum batch size for compliance operations to prevent DoS
Prevents out-of-gas attacks through large blacklist/whitelist arrays
uint256 public constant MAX_COMPLIANCE_BATCH_SIZE = 50
maxSupply
Current maximum supply limit (updatable by governance)
Initialized to DEFAULT_MAX_SUPPLY, can be changed by governance
Prevents infinite minting and maintains tokenomics
uint256 public maxSupply
rateLimitCaps
RateLimitCaps public rateLimitCaps
rateLimitInfo
RateLimitInfo public rateLimitInfo
mintingKillswitch
Emergency killswitch to prevent all QEURO minting operations
When enabled (true), blocks both regular and batch minting functions
Can only be toggled by addresses with PAUSER_ROLE
Used as a crisis management tool when protocol lacks sufficient collateral
Independent of the general pause mechanism - provides granular control
bool public mintingKillswitch
isBlacklisted
Blacklist mapping for compliance and security
Blacklisted addresses cannot transfer or receive tokens
Can be managed by addresses with COMPLIANCE_ROLE
mapping(address => bool) public isBlacklisted
isWhitelisted
Whitelist mapping for compliance (if enabled)
When whitelistEnabled is true, only whitelisted addresses can transfer
Can be managed by addresses with COMPLIANCE_ROLE
mapping(address => bool) public isWhitelisted
whitelistEnabled
Whether whitelist mode is enabled
When true, only whitelisted addresses can transfer tokens
Can be toggled by addresses with COMPLIANCE_ROLE
bool public whitelistEnabled
minPricePrecision
Minimum precision for external price feeds
Used to validate price feed precision for accurate calculations
Can be updated by governance through updateMinPricePrecision()
uint256 public minPricePrecision
treasury
Treasury address for ETH recovery
SECURITY: Only this address can receive ETH from recoverETH function
address public treasury
Functions
flashLoanProtection
Modifier to protect against flash loan attacks
Uses the FlashLoanProtectionLibrary to check QEURO balance consistency
modifier flashLoanProtection() ;
constructor
Constructor for QEURO token contract
Disables initializers for security
Notes:
-
security: Disables initializers for security
-
validation: No validation needed
-
state-changes: Disables initializers
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
-
oz-upgrades-unsafe-allow: constructor
constructor() ;
initialize
Initializes the QEURO token (called only once at deployment)
This function replaces the constructor. It:
- Initializes the ERC20 token with name and symbol
- Configures the role system
- Assigns appropriate roles
- Configures pause and upgrade system
- Sets initial rate limits and precision settings
Security considerations:
- Only callable once (initializer modifier)
- Validates input parameters
- Sets up proper role hierarchy
- Initializes all state variables
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Initializes all contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(address admin, address vault, address _timelock, address _treasury) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address that will have the DEFAULT_ADMIN_ROLE |
vault | address | Address of the QuantillonVault (will get MINTER_ROLE and BURNER_ROLE) |
_timelock | address | Address of the timelock contract |
_treasury | address | Treasury address for protocol fees |
mint
Mints QEURO tokens to a specified address
Implemented securities:
- Only the vault can call this function (MINTER_ROLE)
- The contract must not be paused
- Respect for maximum supply cap
- Input parameter validation
- Rate limiting
- Blacklist/whitelist checks Usage example: vault.mint(user, 1000 * 1e18) for 1000 QEURO
Security considerations:
- Only MINTER_ROLE can mint
- Pause check
- Rate limiting
- Blacklist/whitelist checks
- Supply cap verification
- Secure minting using OpenZeppelin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to MINTER_ROLE
-
oracle: No oracle dependencies
function mint(address to, uint256 amount)
external
onlyRole(MINTER_ROLE) // Only the vault can mint
whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address that will receive the tokens |
amount | uint256 | Amount of tokens to mint (in wei, 18 decimals) |
batchMint
Batch mint QEURO tokens to multiple addresses
Applies the same validations as single mint per item to avoid bypassing rate limits, blacklist/whitelist checks, and max supply constraints. Using external mint for each entry reuses all checks and events.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to MINTER_ROLE
-
oracle: No oracle dependencies
function batchMint(address[] calldata recipients, uint256[] calldata amounts)
external
onlyRole(MINTER_ROLE)
whenNotPaused
flashLoanProtection;
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of recipient addresses |
amounts | uint256[] | Array of amounts to mint (18 decimals) |
burn
Burns QEURO tokens from a specified address
Implemented securities:
- Only the vault can call this function (BURNER_ROLE)
- The contract must not be paused
- Sufficient balance verification
- Parameter validation
- Rate limiting Note: The vault must have an allowance or be authorized otherwise
Security considerations:
- Only BURNER_ROLE can burn
- Pause check
- Rate limiting
- Secure burning using OpenZeppelin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to BURNER_ROLE
-
oracle: No oracle dependencies
-
security: No flash loan protection needed - only vault can burn
function burn(address from, uint256 amount)
external
onlyRole(BURNER_ROLE) // Only the vault can burn
whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Address from which to burn tokens |
amount | uint256 | Amount of tokens to burn |
batchBurn
Batch burn QEURO tokens from multiple addresses
Applies the same validations as single burn per item to avoid bypassing rate limits and balance checks. Accumulates total for rate limiting.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to BURNER_ROLE
-
oracle: No oracle dependencies
function batchBurn(address[] calldata froms, uint256[] calldata amounts)
external
onlyRole(BURNER_ROLE)
whenNotPaused
flashLoanProtection;
Parameters
| Name | Type | Description |
|---|---|---|
froms | address[] | Array of addresses to burn from |
amounts | uint256[] | Array of amounts to burn (18 decimals) |
_checkAndUpdateMintRateLimit
Checks and updates the mint rate limit for the caller
Implements sliding window rate limiting using block numbers to prevent abuse
Notes:
-
security: Resets rate limit if reset period has passed (~300 blocks), prevents block manipulation
-
validation: Validates amount against current rate limit caps
-
state-changes: Updates rateLimitInfo.currentHourMinted and lastRateLimitReset
-
events: No events emitted
-
errors: Throws RateLimitExceeded if amount would exceed current rate limit
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _checkAndUpdateMintRateLimit(uint256 amount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to be minted (18 decimals), used to check against rate limits |
_checkAndUpdateBurnRateLimit
Checks and updates the burn rate limit for the caller
Implements sliding window rate limiting using block numbers to prevent abuse
Notes:
-
security: Resets rate limit if reset period has passed (~300 blocks), prevents block manipulation
-
validation: Validates amount against current rate limit caps
-
state-changes: Updates rateLimitInfo.currentHourBurned and lastRateLimitReset
-
events: No events emitted
-
errors: Throws RateLimitExceeded if amount would exceed current rate limit
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _checkAndUpdateBurnRateLimit(uint256 amount) internal;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to be burned (18 decimals), used to check against rate limits |
updateRateLimits
Updates rate limits for mint and burn operations
Only callable by admin
Security considerations:
- Validates new limits
- Ensures new limits are not zero
- Ensures new limits are not too high
- Updates rateLimitCaps (mint and burn) in a single storage slot
- Emits RateLimitsUpdated event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function updateRateLimits(uint256 newMintLimit, uint256 newBurnLimit) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newMintLimit | uint256 | New mint rate limit per reset period (~300 blocks) |
newBurnLimit | uint256 | New burn rate limit per reset period (~300 blocks) |
blacklistAddress
Blacklists an address
Only callable by compliance role
Security considerations:
- Validates input parameters
- Prevents blacklisting of zero address
- Prevents blacklisting of already blacklisted addresses
- Updates isBlacklisted mapping
- Emits AddressBlacklisted event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function blacklistAddress(address account, string memory reason) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to blacklist |
reason | string | Reason for blacklisting |
unblacklistAddress
Removes an address from blacklist
Only callable by compliance role
Security considerations:
- Validates input parameter
- Prevents unblacklisting of non-blacklisted addresses
- Updates isBlacklisted mapping
- Emits AddressUnblacklisted event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function unblacklistAddress(address account) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to remove from blacklist |
whitelistAddress
Whitelists an address
Only callable by compliance role
Security considerations:
- Validates input parameters
- Prevents whitelisting of zero address
- Prevents whitelisting of already whitelisted addresses
- Updates isWhitelisted mapping
- Emits AddressWhitelisted event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function whitelistAddress(address account) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to whitelist |
unwhitelistAddress
Removes an address from whitelist
Only callable by compliance role
Security considerations:
- Validates input parameter
- Prevents unwhitelisting of non-whitelisted addresses
- Updates isWhitelisted mapping
- Emits AddressUnwhitelisted event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function unwhitelistAddress(address account) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to remove from whitelist |
toggleWhitelistMode
Toggles whitelist mode
Only callable by compliance role
Security considerations:
- Validates input parameter
- Updates whitelistEnabled state
- Emits WhitelistModeToggled event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function toggleWhitelistMode(bool enabled) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable whitelist mode |
batchBlacklistAddresses
Batch blacklist multiple addresses
Only callable by compliance role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function batchBlacklistAddresses(address[] calldata accounts, string[] calldata reasons)
external
onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to blacklist |
reasons | string[] | Array of reasons for blacklisting |
batchUnblacklistAddresses
Batch unblacklist multiple addresses
Only callable by compliance role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function batchUnblacklistAddresses(address[] calldata accounts) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to remove from blacklist |
batchWhitelistAddresses
Batch whitelist multiple addresses
Only callable by compliance role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function batchWhitelistAddresses(address[] calldata accounts) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to whitelist |
batchUnwhitelistAddresses
Batch unwhitelist multiple addresses
Only callable by compliance role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to COMPLIANCE_ROLE
-
oracle: No oracle dependencies
function batchUnwhitelistAddresses(address[] calldata accounts) external onlyRole(COMPLIANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to remove from whitelist |
updateMinPricePrecision
Updates minimum price precision for external feeds
Only callable by admin
Security considerations:
- Validates input parameter
- Prevents setting precision to zero
- Prevents setting precision higher than PRECISION
- Updates minPricePrecision
- Emits MinPricePrecisionUpdated event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function updateMinPricePrecision(uint256 newPrecision) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newPrecision | uint256 | New minimum precision (e.g., 1e6 for 6 decimals) |
normalizePrice
Normalizes a price value to 18 decimals
Helper function for external integrations
Security considerations:
- Validates input parameters
- Prevents too many decimals
- Prevents zero price
- Handles normalization correctly
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function normalizePrice(uint256 price, uint8 feedDecimals) external pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
price | uint256 | Price value from external feed |
feedDecimals | uint8 | Number of decimals in the price feed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Normalized price with 18 decimals |
validatePricePrecision
Validates price precision from external feed
Helper function for external integrations
Security considerations:
- Validates input parameters
- Handles normalization if feedDecimals is not 18
- Returns true if price is above or equal to minPricePrecision
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function validatePricePrecision(uint256 price, uint8 feedDecimals) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
price | uint256 | Price value from external feed |
feedDecimals | uint8 | Number of decimals in the price feed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | Whether the price meets minimum precision requirements |
pause
Pauses all token operations (emergency only)
When paused:
- No transfers possible
- No mint/burn possible
- Only read functions work Used in case of:
- Critical bug discovered
- Ongoing attack
- Emergency protocol maintenance
Security considerations:
- Only PAUSER_ROLE can pause
- Pauses all token operations
- Prevents any state changes
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to PAUSER_ROLE
-
oracle: No oracle dependencies
function pause() external onlyRole(PAUSER_ROLE);
unpause
Removes pause and restores normal operations
Can only be called by a PAUSER_ROLE Used after resolving the issue that caused the pause
Security considerations:
- Only PAUSER_ROLE can unpause
- Unpauses all token operations
- Allows normal state changes
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to PAUSER_ROLE
-
oracle: No oracle dependencies
function unpause() external onlyRole(PAUSER_ROLE);
decimals
Returns the number of decimals for the token (always 18)
Always returns 18 for DeFi compatibility
Security considerations:
- Always returns 18
- No input validation
- No state changes
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function decimals() public pure override returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | Number of decimals (18 for DeFi compatibility) |
isMinter
Checks if an address has the minter role
Checks if account has MINTER_ROLE
Security considerations:
- Checks if account has MINTER_ROLE
- No input validation
- No state changes
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function isMinter(address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | true if the address can mint |
isBurner
Checks if an address has the burner role
Checks if account has BURNER_ROLE
Security considerations:
- Checks if account has BURNER_ROLE
- No input validation
- No state changes
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function isBurner(address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | true if the address can burn |
getSupplyUtilization
Calculates the percentage of maximum supply utilization
Useful for monitoring:
- 0 = 0% used
- 5000 = 50% used
- 10000 = 100% used (maximum supply reached)
Security considerations:
- Calculates percentage based on totalSupply and maxSupply
- Handles division by zero
- Returns 0 if totalSupply is 0
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function getSupplyUtilization() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Percentage in basis points (0-10000, where 10000 = 100%) |
getRemainingMintCapacity
Calculates remaining space for minting new tokens
Calculates remaining capacity by subtracting currentSupply from maxSupply
Security considerations:
- Calculates remaining capacity by subtracting currentSupply from maxSupply
- Handles case where currentSupply >= maxSupply
- Returns 0 if no more minting is possible
Notes:
-
security: No security checks needed
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public - no access restrictions
-
oracle: No oracle dependencies
function getRemainingMintCapacity() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Number of tokens that can still be minted (18 decimals) |
getRateLimitStatus
Gets current rate limit status
Returns current hour amounts if within the hour, zeros if an hour has passed
Security considerations:
- Returns current hour amounts if within the hour
- Returns zeros if an hour has passed
- Returns current limits and next reset time
- Includes bounds checking to prevent timestamp manipulation
Notes:
-
security: No security checks needed
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public - no access restrictions
-
oracle: No oracle dependencies
function getRateLimitStatus()
external
view
returns (
uint256 mintedThisHour,
uint256 burnedThisHour,
uint256 mintLimit,
uint256 burnLimit,
uint256 nextResetTime
);
Returns
| Name | Type | Description |
|---|---|---|
mintedThisHour | uint256 | Amount minted in current hour (18 decimals) |
burnedThisHour | uint256 | Amount burned in current hour (18 decimals) |
mintLimit | uint256 | Current mint rate limit (18 decimals) |
burnLimit | uint256 | Current burn rate limit (18 decimals) |
nextResetTime | uint256 | Block number when rate limits reset |
batchTransfer
Batch transfer QEURO tokens to multiple addresses
Performs multiple transfers from msg.sender to recipients. Uses OpenZeppelin's transfer mechanism with compliance checks.
Notes:
-
security: Validates all recipients and amounts, enforces blacklist/whitelist checks
-
validation: Validates array lengths match, amounts > 0, recipients != address(0)
-
state-changes: Updates balances for all recipients and sender
-
events: Emits Transfer events for each successful transfer
-
errors: Throws ArrayLengthMismatch, BatchSizeTooLarge, InvalidAddress, InvalidAmount, BlacklistedAddress, NotWhitelisted
-
reentrancy: Protected by whenNotPaused modifier
-
access: Public - requires sufficient balance and compliance checks
-
oracle: No oracle dependencies
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts)
external
whenNotPaused
returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of recipient addresses |
amounts | uint256[] | Array of amounts to transfer (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success Always returns true if all transfers succeed |
_update
Hook called before each token transfer
Adds pause verification and blacklist checks to standard OpenZeppelin transfers
Security considerations:
- Checks if transfer is from a blacklisted address
- Checks if transfer is to a blacklisted address
- If whitelist is enabled, checks if recipient is whitelisted
- Prevents transfers if any checks fail
- Calls super._update for standard ERC20 logic
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by whenNotPaused modifier
-
access: Internal function
-
oracle: No oracle dependencies
function _update(address from, address to, uint256 amount) internal override whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Source address (address(0) for mint) |
to | address | Destination address (address(0) for burn) |
amount | uint256 | Amount transferred |
recoverToken
Recover tokens accidentally sent to the contract to treasury only
Only DEFAULT_ADMIN_ROLE can recover tokens to treasury
Security considerations:
- Only DEFAULT_ADMIN_ROLE can recover
- Prevents recovery of own QEURO tokens
- Tokens are sent to treasury address only
- Uses SafeERC20 for secure transfers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function recoverToken(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to recover |
recoverETH
Recover ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
updateMaxSupply
Updates the maximum supply limit (governance only)
Function to adjust supply cap if necessary Requires governance and must be used with caution
IMPROVEMENT: Now functional with dynamic supply cap
Security considerations:
- Only DEFAULT_ADMIN_ROLE can update
- Validates newMaxSupply
- Prevents setting cap below current supply
- Prevents setting cap to zero
- Emits SupplyCapUpdated event
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function updateMaxSupply(uint256 newMaxSupply) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newMaxSupply | uint256 | New supply limit |
updateTreasury
Update treasury address
SECURITY: Only governance can update treasury address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function updateTreasury(address _treasury) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
getTokenInfo
Complete token information (for monitoring)
Returns current state of the token for monitoring purposes
Security considerations:
- Returns current state of the token
- No input validation
- No state changes
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function getTokenInfo()
external
view
returns (
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 totalSupply_,
uint256 maxSupply_,
bool isPaused_,
bool whitelistEnabled_,
uint256 mintRateLimit_,
uint256 burnRateLimit_
);
Returns
| Name | Type | Description |
|---|---|---|
name_ | string | Token name |
symbol_ | string | Token symbol |
decimals_ | uint8 | Number of decimals |
totalSupply_ | uint256 | Current total supply |
maxSupply_ | uint256 | Maximum authorized supply |
isPaused_ | bool | Pause state |
whitelistEnabled_ | bool | Whether whitelist mode is enabled |
mintRateLimit_ | uint256 | Current mint rate limit |
burnRateLimit_ | uint256 | Current burn rate limit |
mintRateLimit
Get current mint rate limit (per hour)
Returns current mint rate limit
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function mintRateLimit() external view returns (uint256 limit);
Returns
| Name | Type | Description |
|---|---|---|
limit | uint256 | Mint rate limit in wei per hour (18 decimals) |
setMintingKillswitch
Toggle the emergency minting killswitch to enable/disable all minting operations
Emergency function that provides granular control over minting without affecting other operations
Can only be called by addresses with PAUSER_ROLE for security
Used as a crisis management tool when protocol lacks sufficient collateral
Independent of the general pause mechanism - allows selective operation blocking
When enabled, both mint() and batchMint() functions will revert with MintingDisabled error
Burning operations remain unaffected by the killswitch
Notes:
-
security: Only callable by PAUSER_ROLE holders
-
validation: Validates caller has PAUSER_ROLE
-
events: Emits MintingKillswitchToggled event with new state and caller
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks PAUSER_ROLE
-
state-changes: Updates mintingKillswitch state variable
-
access: Restricted to PAUSER_ROLE
-
reentrancy: Not protected - simple state change
-
oracle: No oracle dependencies
function setMintingKillswitch(bool enabled) external onlyRole(PAUSER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | True to enable killswitch (block all minting), false to disable (allow minting) |
burnRateLimit
Get current burn rate limit (per hour)
Returns current burn rate limit
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function burnRateLimit() external view returns (uint256 limit);
Returns
| Name | Type | Description |
|---|---|---|
limit | uint256 | Burn rate limit in wei per hour (18 decimals) |
Events
TokensMinted
Emitted when tokens are minted
OPTIMIZED: Indexed amount for efficient filtering by mint size
event TokensMinted(address indexed to, uint256 indexed amount, address indexed minter);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Recipient of the tokens |
amount | uint256 | Amount minted in wei (18 decimals) |
minter | address | Address that performed the mint (vault) |
MintingKillswitchToggled
Emitted when the minting killswitch is toggled on or off
Provides transparency for emergency actions taken by protocol administrators
event MintingKillswitchToggled(bool enabled, address indexed caller);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | True if killswitch is being enabled (minting blocked), false if disabled (minting allowed) |
caller | address | Address of the PAUSER_ROLE holder who toggled the killswitch |
TokensBurned
Emitted when tokens are burned
OPTIMIZED: Indexed amount for efficient filtering by burn size
event TokensBurned(address indexed from, uint256 indexed amount, address indexed burner);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Address from which tokens are burned |
amount | uint256 | Amount burned in wei (18 decimals) |
burner | address | Address that performed the burn (vault) |
SupplyCapUpdated
Emitted when the supply limit is modified
Emitted when governance updates the maximum supply
event SupplyCapUpdated(uint256 oldCap, uint256 newCap);
Parameters
| Name | Type | Description |
|---|---|---|
oldCap | uint256 | Old supply limit in wei (18 decimals) |
newCap | uint256 | New supply limit in wei (18 decimals) |
RateLimitsUpdated
Emitted when rate limits are updated
OPTIMIZED: Indexed parameter type for efficient filtering
event RateLimitsUpdated(string indexed limitType, uint256 mintLimit, uint256 burnLimit);
Parameters
| Name | Type | Description |
|---|---|---|
limitType | string | |
mintLimit | uint256 | New mint rate limit in wei per hour (18 decimals) |
burnLimit | uint256 | New burn rate limit in wei per hour (18 decimals) |
TreasuryUpdated
Emitted when treasury address is updated
event TreasuryUpdated(address indexed treasury);
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | New treasury address |
AddressBlacklisted
Emitted when an address is blacklisted
OPTIMIZED: Indexed reason for efficient filtering by blacklist type
event AddressBlacklisted(address indexed account, string indexed reason);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address that was blacklisted |
reason | string | Reason for blacklisting (for compliance records) |
AddressUnblacklisted
Emitted when an address is removed from blacklist
Emitted when COMPLIANCE_ROLE removes an address from blacklist
event AddressUnblacklisted(address indexed account);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address that was removed from blacklist |
AddressWhitelisted
Emitted when an address is whitelisted
Emitted when COMPLIANCE_ROLE whitelists an address
event AddressWhitelisted(address indexed account);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address that was whitelisted |
AddressUnwhitelisted
Emitted when an address is removed from whitelist
Emitted when COMPLIANCE_ROLE removes an address from whitelist
event AddressUnwhitelisted(address indexed account);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address that was removed from whitelist |
WhitelistModeToggled
Emitted when whitelist mode is toggled
Emitted when COMPLIANCE_ROLE toggles whitelist mode
event WhitelistModeToggled(bool enabled);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether whitelist mode is enabled |
MinPricePrecisionUpdated
Emitted when minimum price precision is updated
Emitted when governance updates minimum price precision
event MinPricePrecisionUpdated(uint256 oldPrecision, uint256 newPrecision);
Parameters
| Name | Type | Description |
|---|---|---|
oldPrecision | uint256 | Old minimum precision value |
newPrecision | uint256 | New minimum precision value |
RateLimitReset
Emitted when rate limit is reset
OPTIMIZED: Indexed block number for efficient block-based filtering
event RateLimitReset(uint256 indexed blockNumber);
Parameters
| Name | Type | Description |
|---|---|---|
blockNumber | uint256 | Block number when reset occurred |
ETHRecovered
Emitted when ETH is recovered to treasury
event ETHRecovered(address indexed to, uint256 indexed amount);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address to which ETH was recovered |
amount | uint256 | Amount of ETH recovered |
Structs
RateLimitCaps
Packed rate limit caps for mint and burn (per hour)
Two uint128 packed into one slot for storage efficiency
struct RateLimitCaps {
uint128 mint;
uint128 burn;
}
RateLimitInfo
Rate limiting information - OPTIMIZED: Packed for storage efficiency
Resets every ~300 blocks (~1 hour assuming 12 second blocks) or when rate limits are updated
Used to enforce mintRateLimit and burnRateLimit
struct RateLimitInfo {
uint96 currentHourMinted; // Current minted amount in the current hour (12 bytes)
uint96 currentHourBurned; // Current burned amount in the current hour (12 bytes)
uint64 lastRateLimitReset; // Block number of the last rate limit reset (8 bytes)
}
QTIToken
Inherits: Initializable, ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Governance token for Quantillon Protocol with vote-escrow mechanics
Main characteristics:
- Standard ERC20 with 18 decimals
- Vote-escrow (ve) mechanics for governance power
- Progressive decentralization through governance
- Emergency pause mechanism for crisis situations
- Upgradeable via UUPS pattern
- Fixed supply cap for tokenomics
- Governance proposal and voting system
- Lock-based voting power calculation
Vote-escrow mechanics:
- Users can lock QTI tokens for governance power
- Longer locks = higher voting power (up to 4x multiplier)
- Minimum lock: 7 days, Maximum lock: 4 years
- Voting power decreases linearly over time
- Locked tokens cannot be transferred until unlock
Governance features:
- Proposal creation with minimum threshold
- Voting period with configurable duration
- Vote counting and execution
- Proposal cancellation and emergency actions
Security features:
- Role-based access control for all critical operations
- Emergency pause mechanism for crisis situations
- Upgradeable architecture for future improvements
- Secure vote-escrow mechanics
- Proposal execution safeguards
Tokenomics:
- Total supply: 100,000,000 QTI (fixed cap)
- Initial distribution: Through protocol mechanisms
- Decimals: 18 (standard for ERC20 tokens)
- Governance power: Based on locked amount and duration
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
Role for governance operations (proposal creation, execution)
keccak256 hash avoids role collisions with other contracts
Should be assigned to governance multisig or DAO
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
EMERGENCY_ROLE
Role for emergency operations (pause, emergency proposals)
keccak256 hash avoids role collisions with other contracts
Should be assigned to emergency multisig
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
MAX_LOCK_TIME
Maximum lock time for QTI tokens
Prevents extremely long locks that could impact governance
uint256 public constant MAX_LOCK_TIME = 365 days
MAX_BATCH_SIZE
Maximum batch size for lock operations to prevent DoS
Prevents out-of-gas attacks through large arrays
uint256 public constant MAX_BATCH_SIZE = 100
MAX_UNLOCK_BATCH_SIZE
Maximum batch size for unlock operations to prevent DoS
Prevents out-of-gas attacks through large user arrays
uint256 public constant MAX_UNLOCK_BATCH_SIZE = 50
MAX_VOTE_BATCH_SIZE
Maximum batch size for voting operations to prevent DoS
Prevents out-of-gas attacks through large proposal arrays
uint256 public constant MAX_VOTE_BATCH_SIZE = 50
MIN_LOCK_TIME
Minimum lock time for vote-escrow (1 week)
Prevents very short locks that could manipulate governance
Value: 7 days
uint256 public constant MIN_LOCK_TIME = 7 days
WEEK
Week duration in seconds (7 days)
Used for time calculations and voting periods
Value: 7 days = 604,800 seconds
uint256 public constant WEEK = 7 days
MAX_VE_QTI_MULTIPLIER
Maximum voting power multiplier (4x)
Maximum voting power a user can achieve through locking
Value: 4 (400% voting power for maximum lock)
uint256 public constant MAX_VE_QTI_MULTIPLIER = 4
MAX_TIME_ELAPSED
Maximum time elapsed for calculations to prevent manipulation
Caps time-based calculations to prevent timestamp manipulation
uint256 public constant MAX_TIME_ELAPSED = 10 * 365 days
TOTAL_SUPPLY_CAP
Total supply cap (100 million QTI)
Fixed supply cap for tokenomics
Value: 100,000,000 * 10^18 = 100,000,000 QTI
uint256 public constant TOTAL_SUPPLY_CAP = 100_000_000 * 1e18
locks
Vote-escrow locks per user address
Maps user addresses to their lock information
Used to track locked tokens and voting power
mapping(address => LockInfo) public locks
totalLocked
Total QTI tokens locked in vote-escrow
Sum of all locked amounts across all users
Used for protocol analytics and governance metrics
uint256 public totalLocked
totalVotingPower
Total voting power across all locked tokens
Sum of all voting power across all users
Used for governance quorum calculations
uint256 public totalVotingPower
proposals
Governance proposals by proposal ID
Maps proposal IDs to proposal data
Used to store and retrieve proposal information
mapping(uint256 => Proposal) public proposals
nextProposalId
Next proposal ID to be assigned
Auto-incremented for each new proposal
Used to generate unique proposal identifiers
uint256 public nextProposalId
proposalThreshold
Minimum QTI required to create a governance proposal
Prevents spam proposals and ensures serious governance participation
Can be updated by governance
uint256 public proposalThreshold
minVotingPeriod
Minimum voting period duration
Ensures adequate time for community discussion and voting
Can be updated by governance
uint256 public minVotingPeriod
maxVotingPeriod
Maximum voting period duration
Prevents excessively long voting periods
Can be updated by governance
uint256 public maxVotingPeriod
quorumVotes
Quorum required for proposal to pass
Minimum number of votes needed for a proposal to be considered valid
Can be updated by governance
uint256 public quorumVotes
treasury
Treasury address for protocol fees
Address where protocol fees are collected and distributed
Can be updated by governance
address public treasury
decentralizationStartTime
Progressive decentralization parameters
Start time for the decentralization process
Duration of the decentralization process
Current level of decentralization (0-10000)
uint256 public decentralizationStartTime
decentralizationDuration
uint256 public decentralizationDuration
currentDecentralizationLevel
uint256 public currentDecentralizationLevel
proposalExecutionTime
Execution time for each proposal (with random delay)
mapping(uint256 => uint256) public proposalExecutionTime
proposalExecutionHash
Execution hash for each proposal (for verification)
mapping(uint256 => bytes32) public proposalExecutionHash
proposalScheduled
Whether a proposal has been scheduled for execution
mapping(uint256 => bool) public proposalScheduled
TIME_PROVIDER
TimeProvider contract for centralized time management
Used to replace direct block.timestamp usage for testability and consistency
TimeProvider public immutable TIME_PROVIDER
Functions
flashLoanProtection
Modifier to protect against flash loan attacks
Uses the FlashLoanProtectionLibrary to check QTI balance consistency
modifier flashLoanProtection() ;
constructor
Constructor for QTI token contract
Sets up the time provider and disables initializers for security
Notes:
-
security: Validates time provider address and disables initializers
-
validation: Validates input parameters and business logic constraints
-
state-changes: Sets immutable time provider and disables initializers
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | TimeProvider contract for centralized time management |
initialize
Initializes the QTI token contract
Sets up the governance token with initial configuration and assigns roles to admin
Notes:
-
security: Validates all input addresses and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Initializes all contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(address admin, address _treasury, address _timelock) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address that receives admin and governance roles |
_treasury | address | Treasury address for protocol fees |
_timelock | address | Timelock contract address for secure upgrades |
lock
Locks QTI tokens for a specified duration to earn voting power (veQTI)
Longer lock periods generate more voting power via time-weighted calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function lock(uint256 amount, uint256 lockTime) external whenNotPaused flashLoanProtection returns (uint256 veQTI);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of QTI tokens to lock |
lockTime | uint256 | The duration to lock tokens (in seconds) |
Returns
| Name | Type | Description |
|---|---|---|
veQTI | uint256 | The amount of voting power (veQTI) earned from this lock |
unlock
Unlock QTI tokens after lock period expires
Releases locked QTI tokens and removes voting power when lock period has expired
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unlock() external whenNotPaused returns (uint256 amount);
Returns
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of QTI unlocked |
batchLock
Batch lock QTI tokens for voting power for multiple amounts
Efficiently locks multiple amounts with different lock times in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchLock(uint256[] calldata amounts, uint256[] calldata lockTimes)
external
whenNotPaused
flashLoanProtection
returns (uint256[] memory veQTIAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts to lock |
lockTimes | uint256[] | Array of lock durations (must be >= MIN_LOCK_TIME) |
Returns
| Name | Type | Description |
|---|---|---|
veQTIAmounts | uint256[] | Array of voting power calculated for each locked amount |
_validateBatchLockInputs
Validates basic batch lock inputs
Ensures array lengths match and batch size is within limits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _validateBatchLockInputs(uint256[] calldata amounts, uint256[] calldata lockTimes) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts to lock |
lockTimes | uint256[] | Array of lock durations |
_validateAndCalculateTotalAmount
Validates all amounts and lock times, returns total amount
Ensures all amounts and lock times are valid and calculates total amount
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _validateAndCalculateTotalAmount(uint256[] calldata amounts, uint256[] calldata lockTimes)
internal
pure
returns (uint256 totalAmount);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts to lock |
lockTimes | uint256[] | Array of lock durations |
Returns
| Name | Type | Description |
|---|---|---|
totalAmount | uint256 | Total amount of QTI to be locked |
_processBatchLocks
Processes all locks and calculates totals
Processes batch lock operations and calculates total voting power and amounts
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _processBatchLocks(
uint256[] calldata amounts,
uint256[] calldata lockTimes,
uint256[] memory veQTIAmounts,
LockInfo storage lockInfo
) internal returns (uint256 totalNewVotingPower, uint256 totalNewAmount);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts to lock |
lockTimes | uint256[] | Array of lock durations |
veQTIAmounts | uint256[] | Array to store calculated voting power amounts |
lockInfo | LockInfo | Storage reference to user's lock information |
Returns
| Name | Type | Description |
|---|---|---|
totalNewVotingPower | uint256 | Total new voting power from all locks |
totalNewAmount | uint256 | Total new amount locked |
_calculateUnlockTime
Calculates unlock time with proper validation
Calculates new unlock time based on current timestamp and lock duration
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateUnlockTime(uint256 currentTimestamp, uint256 lockTime, uint256 existingUnlockTime)
internal
pure
returns (uint256 newUnlockTime);
Parameters
| Name | Type | Description |
|---|---|---|
currentTimestamp | uint256 | Current timestamp for calculation |
lockTime | uint256 | Duration to lock tokens |
existingUnlockTime | uint256 | Existing unlock time if already locked |
Returns
| Name | Type | Description |
|---|---|---|
newUnlockTime | uint256 | Calculated unlock time |
_calculateVotingPower
Calculates voting power with overflow protection
Calculates voting power based on amount and lock time with overflow protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateVotingPower(uint256 amount, uint256 lockTime) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of QTI tokens to lock |
lockTime | uint256 | Duration to lock tokens |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | votingPower Calculated voting power |
_updateLockInfo
Updates lock info with overflow checks
Updates user's lock information with new amounts and times
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _updateLockInfo(
LockInfo storage lockInfo,
uint256 totalNewAmount,
uint256 newUnlockTime,
uint256 totalNewVotingPower,
uint256 lockTime
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
lockInfo | LockInfo | Storage reference to user's lock information |
totalNewAmount | uint256 | Total new amount to lock |
newUnlockTime | uint256 | New unlock time |
totalNewVotingPower | uint256 | Total new voting power |
lockTime | uint256 | Lock duration |
_updateGlobalTotalsAndTransfer
Updates global totals and transfers tokens
Updates global locked amounts and voting power, then transfers tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _updateGlobalTotalsAndTransfer(uint256 totalAmount, uint256 oldVotingPower, uint256 totalNewVotingPower)
internal;
Parameters
| Name | Type | Description |
|---|---|---|
totalAmount | uint256 | Total amount of tokens to lock |
oldVotingPower | uint256 | Previous voting power |
totalNewVotingPower | uint256 | New total voting power |
batchUnlock
Batch unlock QTI tokens for multiple users (admin function)
Efficiently unlocks tokens for multiple users in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function batchUnlock(address[] calldata users)
external
onlyRole(GOVERNANCE_ROLE)
whenNotPaused
returns (uint256[] memory amounts);
Parameters
| Name | Type | Description |
|---|---|---|
users | address[] | Array of user addresses to unlock for |
Returns
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts unlocked |
batchTransfer
Batch transfer QTI tokens to multiple addresses
Efficiently transfers tokens to multiple recipients in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: No access restrictions
-
oracle: No oracle dependencies
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts)
external
whenNotPaused
flashLoanProtection
returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of recipient addresses |
amounts | uint256[] | Array of amounts to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if all transfers were successful |
getVotingPower
Get voting power for an address with linear decay
Calculates current voting power with linear decay over time
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getVotingPower(address user) external view returns (uint256 votingPower);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address to get voting power for |
Returns
| Name | Type | Description |
|---|---|---|
votingPower | uint256 | Current voting power of the user (decays linearly over time) |
updateVotingPower
Update voting power for the caller based on current time
Updates voting power based on current time and lock duration
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateVotingPower() external returns (uint256 newVotingPower);
Returns
| Name | Type | Description |
|---|---|---|
newVotingPower | uint256 | Updated voting power |
getLockInfo
Get lock info for an address
Returns comprehensive lock information for a user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getLockInfo(address user)
external
view
returns (
uint256 amount,
uint256 unlockTime,
uint256 votingPower,
uint256 lastClaimTime,
uint256 initialVotingPower,
uint256 lockTime
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address to get lock info for |
Returns
| Name | Type | Description |
|---|---|---|
amount | uint256 | Locked QTI amount |
unlockTime | uint256 | Timestamp when lock expires |
votingPower | uint256 | Current voting power |
lastClaimTime | uint256 | Last claim time (for future use) |
initialVotingPower | uint256 | Initial voting power when locked |
lockTime | uint256 | Original lock duration |
createProposal
Create a new governance proposal
Creates a new governance proposal with specified parameters and voting period
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: No oracle dependencies
function createProposal(string calldata description, uint256 votingPeriod, bytes calldata data)
external
whenNotPaused
returns (uint256 proposalId);
Parameters
| Name | Type | Description |
|---|---|---|
description | string | Proposal description |
votingPeriod | uint256 | Voting period in seconds |
data | bytes | Execution data (function calls) |
Returns
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Unique identifier for the created proposal |
vote
Vote on a proposal
Allows users to vote on governance proposals with their voting power
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function vote(uint256 proposalId, bool support) external whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
support | bool | True for yes, false for no |
batchVote
Batch vote on multiple proposals
Efficiently votes on multiple proposals in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchVote(uint256[] calldata proposalIds, bool[] calldata supportVotes)
external
whenNotPaused
flashLoanProtection;
Parameters
| Name | Type | Description |
|---|---|---|
proposalIds | uint256[] | Array of proposal IDs to vote on |
supportVotes | bool[] | Array of vote directions (true for yes, false for no) |
executeProposal
Execute a successful proposal
Executes a proposal that has passed voting and meets quorum requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function executeProposal(uint256 proposalId) external nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
_verifyCallResult
Verifies call result and reverts with appropriate error
function _verifyCallResult(bool success) private pure;
Parameters
| Name | Type | Description |
|---|---|---|
success | bool | Whether the call was successful |
getProposalExecutionInfo
Get execution information for a scheduled proposal
Returns execution status and timing information for a proposal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getProposalExecutionInfo(uint256 proposalId)
external
view
returns (bool scheduled, uint256 executionTime, bool canExecute);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
Returns
| Name | Type | Description |
|---|---|---|
scheduled | bool | Whether the proposal is scheduled |
executionTime | uint256 | When the proposal can be executed |
canExecute | bool | Whether the proposal can be executed now |
getProposalExecutionHash
Get the execution hash for a scheduled proposal
Returns the execution hash required to execute a scheduled proposal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getProposalExecutionHash(uint256 proposalId) external view returns (bytes32 executionHash);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
Returns
| Name | Type | Description |
|---|---|---|
executionHash | bytes32 | Hash required to execute the proposal |
cancelProposal
Cancel a proposal (only proposer or admin)
Allows proposer or admin to cancel a proposal before execution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function cancelProposal(uint256 proposalId) external;
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
getProposal
Get proposal details
Returns comprehensive proposal information including voting results
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getProposal(uint256 proposalId)
external
view
returns (
address proposer,
uint256 startTime,
uint256 endTime,
uint256 forVotes,
uint256 againstVotes,
bool executed,
bool canceled,
string memory description
);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
Returns
| Name | Type | Description |
|---|---|---|
proposer | address | Address of the proposer |
startTime | uint256 | Timestamp when voting starts |
endTime | uint256 | Timestamp when voting ends |
forVotes | uint256 | Total votes in favor |
againstVotes | uint256 | Total votes against |
executed | bool | Whether the proposal was executed |
canceled | bool | Whether the proposal was canceled |
description | string | Proposal description |
getReceipt
Get voting receipt for a user
Returns voting information for a specific user on a specific proposal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getReceipt(uint256 proposalId, address voter)
external
view
returns (bool hasVoted, bool support, uint256 votes);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
voter | address | Address of the voter |
Returns
| Name | Type | Description |
|---|---|---|
hasVoted | bool | Whether the user has voted |
support | bool | True for yes vote, false for no vote |
votes | uint256 | Number of votes cast |
updateGovernanceParameters
Update governance parameters
Updates governance parameters including proposal threshold, voting period, and quorum
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateGovernanceParameters(uint256 _proposalThreshold, uint256 _minVotingPeriod, uint256 _quorumVotes)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_proposalThreshold | uint256 | New minimum QTI required to propose |
_minVotingPeriod | uint256 | New minimum voting period |
_quorumVotes | uint256 | New quorum required for proposals to pass |
updateTreasury
Update treasury address
Updates the treasury address for protocol fee collection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateTreasury(address _treasury) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
updateDecentralizationLevel
Update decentralization level
This function is intended to be called periodically by the governance to update the decentralization level based on the elapsed time. Includes bounds checking to prevent timestamp manipulation.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateDecentralizationLevel() external onlyRole(GOVERNANCE_ROLE);
_calculateVotingPowerMultiplier
Calculate voting power multiplier based on lock time
Calculates linear multiplier from 1x to 4x based on lock duration
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateVotingPowerMultiplier(uint256 lockTime) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
lockTime | uint256 | Duration of the lock |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | multiplier Voting power multiplier |
_updateVotingPower
Update voting power for a user based on current time
Updates voting power based on current time and lock duration with linear decay
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _updateVotingPower(address user) internal returns (uint256 newVotingPower);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to update |
Returns
| Name | Type | Description |
|---|---|---|
newVotingPower | uint256 | Updated voting power |
decimals
Returns the number of decimals for the QTI token
Always returns 18 for standard ERC20 compatibility
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function decimals() public pure override returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | The number of decimals (18) |
pause
Pauses all token operations including transfers and governance
Emergency function to halt all contract operations when needed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external onlyRole(EMERGENCY_ROLE);
unpause
Unpauses all token operations
Resumes normal contract operations after emergency is resolved
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external onlyRole(EMERGENCY_ROLE);
recoverToken
Recover accidentally sent tokens to treasury only
Recovers accidentally sent tokens to the treasury address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to recover |
recoverETH
Recover accidentally sent ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
getGovernanceInfo
Get current governance information
Returns comprehensive governance information including totals and parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getGovernanceInfo()
external
view
returns (
uint256 totalLocked_,
uint256 totalVotingPower_,
uint256 proposalThreshold_,
uint256 quorumVotes_,
uint256 currentDecentralizationLevel_
);
Returns
| Name | Type | Description |
|---|---|---|
totalLocked_ | uint256 | Total QTI tokens locked in vote-escrow |
totalVotingPower_ | uint256 | Total voting power across all locked tokens |
proposalThreshold_ | uint256 | Minimum QTI required to propose |
quorumVotes_ | uint256 | Quorum required for proposals to pass |
currentDecentralizationLevel_ | uint256 | Current decentralization level (0-10000) |
Events
TokensLocked
Emitted when tokens are locked for voting power
OPTIMIZED: Indexed amount and unlockTime for efficient filtering
event TokensLocked(address indexed user, uint256 indexed amount, uint256 indexed unlockTime, uint256 votingPower);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who locked tokens |
amount | uint256 | Amount of QTI locked |
unlockTime | uint256 | Timestamp when the lock expires |
votingPower | uint256 | Voting power calculated for the locked amount |
TokensUnlocked
Emitted when tokens are unlocked after lock period expires
OPTIMIZED: Indexed amount for efficient filtering by unlock size
event TokensUnlocked(address indexed user, uint256 indexed amount, uint256 votingPower);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who unlocked tokens |
amount | uint256 | Amount of QTI unlocked |
votingPower | uint256 | Voting power before unlocking |
VotingPowerUpdated
Emitted when voting power for an address is updated
event VotingPowerUpdated(address indexed user, uint256 oldPower, uint256 newPower);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user whose voting power changed |
oldPower | uint256 | Previous voting power |
newPower | uint256 | New voting power |
ProposalCreated
Emitted when a new governance proposal is created
event ProposalCreated(uint256 indexed proposalId, address indexed proposer, string description);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Unique identifier for the proposal |
proposer | address | Address of the proposer |
description | string | Description of the proposal |
Voted
Emitted when a user votes on a proposal
OPTIMIZED: Indexed support for efficient filtering by vote direction
event Voted(uint256 indexed proposalId, address indexed voter, bool indexed support, uint256 votes);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Unique identifier for the proposal |
voter | address | Address of the voter |
support | bool | True for yes vote, false for no vote |
votes | uint256 | Number of votes cast |
ProposalExecuted
Emitted when a proposal is successfully executed
event ProposalExecuted(uint256 indexed proposalId);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Unique identifier for the executed proposal |
ProposalCanceled
Emitted when a proposal is canceled
event ProposalCanceled(uint256 indexed proposalId);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Unique identifier for the canceled proposal |
GovernanceParametersUpdated
Emitted when governance parameters are updated
OPTIMIZED: Indexed parameter type for efficient filtering
event GovernanceParametersUpdated(
string indexed parameterType, uint256 proposalThreshold, uint256 minVotingPeriod, uint256 quorumVotes
);
Parameters
| Name | Type | Description |
|---|---|---|
parameterType | string | |
proposalThreshold | uint256 | New minimum QTI required to propose |
minVotingPeriod | uint256 | New minimum voting period |
quorumVotes | uint256 | New quorum required for proposals to pass |
DecentralizationLevelUpdated
Emitted when the decentralization level is updated
OPTIMIZED: Indexed level for efficient filtering by decentralization stage
event DecentralizationLevelUpdated(uint256 indexed newLevel);
Parameters
| Name | Type | Description |
|---|---|---|
newLevel | uint256 | New decentralization level (0-10000) |
ETHRecovered
Emitted when ETH is recovered from the contract
event ETHRecovered(address indexed to, uint256 indexed amount);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Recipient address |
amount | uint256 | Amount of ETH recovered |
Structs
LockInfo
Vote-escrow lock information for each user
Stores locked amount, unlock time, voting power, and claim time
Used to calculate governance power and manage locks
OPTIMIZED: Fields ordered for optimal storage packing
struct LockInfo {
uint96 amount; // Locked QTI amount in wei (18 decimals) - 12 bytes
uint96 votingPower; // Current voting power (calculated) - 12 bytes
uint96 initialVotingPower; // Initial voting power when locked - 12 bytes
uint32 unlockTime; // Timestamp when lock expires - 4 bytes
uint32 lastClaimTime; // Last claim time (for future use) - 4 bytes
uint32 lockTime; // Original lock duration - 4 bytes
}
Proposal
Governance proposal structure
Stores all proposal data including voting results and execution info
Used for governance decision making
struct Proposal {
address proposer; // Address that created the proposal
uint256 startTime; // Timestamp when voting starts
uint256 endTime; // Timestamp when voting ends
uint256 forVotes; // Total votes in favor
uint256 againstVotes; // Total votes against
bool executed; // Whether proposal was executed
bool canceled; // Whether proposal was canceled
string description; // Human-readable proposal description
bytes data; // Execution data (function calls)
mapping(address => Receipt) receipts; // Individual voting receipts
}
Receipt
Voting receipt for each voter in a proposal
Stores individual voting information for each user
Used to prevent double voting and track individual votes
struct Receipt {
bool hasVoted; // Whether user has voted on this proposal
bool support; // True for yes vote, false for no vote
uint256 votes; // Number of votes cast (voting power used)
}
QuantillonVault
Inherits: Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable, PausableUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Main vault managing QEURO minting against USDC collateral
Main characteristics:
- Simple USDC to QEURO swap mechanism
- USDC as input for QEURO minting
- Real-time EUR/USD price oracle integration
- Dynamic fee structure for protocol sustainability
- Emergency pause mechanism for crisis situations
- Upgradeable via UUPS pattern
Minting mechanics:
- Users swap USDC for QEURO
- QEURO is minted based on EUR/USD exchange rate
- Minting fees charged for protocol revenue
- Simple 1:1 exchange with price conversion
- Price deviation protection prevents flash loan manipulation
- Block-based validation ensures price freshness
Redemption mechanics:
- Users can redeem QEURO back to USDC
- Redemption based on current EUR/USD exchange rate
- Protocol fees charged on redemptions
- USDC returned to user after fee deduction
- Same price deviation protection as minting
- Consistent security across all operations
Risk management:
- Real-time price monitoring
- Emergency pause capabilities
- Slippage protection on swaps
- Flash loan attack prevention via price deviation checks
- Block-based price manipulation detection
- Comprehensive oracle validation and fallback mechanisms
Fee structure:
- Minting fees for creating QEURO
- Redemption fees for converting QEURO back to USDC
- Dynamic fee adjustment based on market conditions
Security features:
- Role-based access control for all critical operations
- Reentrancy protection for all external calls
- Emergency pause mechanism for crisis situations
- Upgradeable architecture for future improvements
- Secure collateral management
- Oracle price validation
- Flash loan protection through price deviation checks
- Block-based price update validation
- Comprehensive price manipulation attack prevention
Integration points:
- QEURO token for minting and burning
- USDC for collateral deposits and withdrawals
- Chainlink oracle for EUR/USD price feeds
- Vault math library for precise calculations
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
Role for governance operations (parameter updates, emergency actions)
keccak256 hash avoids role collisions with other contracts
Should be assigned to governance multisig or DAO
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
EMERGENCY_ROLE
Role for emergency operations (pause)
keccak256 hash avoids role collisions with other contracts
Should be assigned to emergency multisig
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
MAX_PRICE_DEVIATION
Maximum allowed price deviation between consecutive price updates (in basis points)
Prevents flash loan price manipulation attacks
200 basis points = 2% maximum deviation
uint256 private constant MAX_PRICE_DEVIATION = 200
MIN_BLOCKS_BETWEEN_UPDATES
Minimum number of blocks required between price updates for deviation checks
Prevents manipulation within the same block
uint256 private constant MIN_BLOCKS_BETWEEN_UPDATES = 1
qeuro
QEURO token contract for minting and burning
Used for all QEURO minting and burning operations
Should be the official QEURO token contract
IQEUROToken public qeuro
usdc
USDC token used as collateral
Used for all collateral deposits, withdrawals, and fee payments
Should be the official USDC contract on the target network
IERC20 public usdc
oracle
Chainlink oracle contract for EUR/USD price feeds
Provides real-time EUR/USD exchange rates for minting and redemption
Used for price calculations in swap operations
IChainlinkOracle public oracle
hedgerPool
HedgerPool contract for collateralization checks
Used to verify protocol has sufficient hedging positions before minting QEURO
Ensures protocol is properly collateralized by hedgers
IHedgerPool public hedgerPool
userPool
UserPool contract for user deposit tracking
Used to get total user deposits for collateralization ratio calculations
Required for accurate protocol collateralization assessment
IUserPool public userPool
treasury
Treasury address for ETH recovery
SECURITY: Only this address can receive ETH from recoverETH function
address public treasury
feeCollector
Fee collector contract for protocol fees
Centralized fee collection and distribution
address public feeCollector
mintFee
Protocol fee charged on minting QEURO (in basis points)
Example: 10 = 0.1% minting fee
Revenue source for the protocol
uint256 public mintFee
redemptionFee
Protocol fee charged on redeeming QEURO (in basis points)
Example: 10 = 0.1% redemption fee
Revenue source for the protocol
uint256 public redemptionFee
minCollateralizationRatioForMinting
Minimum collateralization ratio required for minting QEURO (in basis points)
Example: 10500 = 105% collateralization ratio required for minting
When protocol collateralization >= this threshold, minting is allowed
When protocol collateralization < this threshold, minting is halted
Can be updated by governance to adjust protocol risk parameters
uint256 public minCollateralizationRatioForMinting
criticalCollateralizationRatio
Critical collateralization ratio that triggers liquidation (in basis points)
Example: 10100 = 101% collateralization ratio triggers liquidation
When protocol collateralization < this threshold, hedgers start being liquidated
Emergency threshold to protect protocol solvency
Can be updated by governance to adjust liquidation triggers
uint256 public criticalCollateralizationRatio
totalUsdcHeld
Total USDC held in the vault
Used for vault analytics and risk management
uint256 public totalUsdcHeld
totalMinted
Total QEURO in circulation (minted by this vault)
uint256 public totalMinted
lastValidEurUsdPrice
Last valid EUR/USD price used in operations
Used for price deviation checks to prevent manipulation
uint256 private lastValidEurUsdPrice
lastPriceUpdateBlock
Block number of the last price update
Used to ensure minimum blocks between updates for deviation checks
uint256 private lastPriceUpdateBlock
lastPriceUpdateTime
Variable to store the timestamp of the last valid price update
uint256 private lastPriceUpdateTime
Functions
flashLoanProtection
Modifier to protect against flash loan attacks
Uses the FlashLoanProtectionLibrary to check USDC balance consistency
modifier flashLoanProtection() ;
constructor
Constructor for QuantillonVault contract
Disables initializers for security
Notes:
-
security: Disables initializers for security
-
validation: No validation needed
-
state-changes: Disables initializers
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
-
oz-upgrades-unsafe-allow: constructor
constructor() ;
initialize
Initializes the vault with contracts and parameters
This function configures:
- Access roles
- References to external contracts
- Default protocol parameters
- Security (pause, reentrancy, upgrades)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Initializes all contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(
address admin,
address _qeuro,
address _usdc,
address _oracle,
address _hedgerPool,
address _userPool,
address _timelock,
address _feeCollector
) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address with administrator privileges |
_qeuro | address | Address of the QEURO token contract |
_usdc | address | Address of the USDC token contract |
_oracle | address | Address of the Oracle contract |
_hedgerPool | address | Address of the HedgerPool contract |
_userPool | address | Address of the UserPool contract |
_timelock | address | Address of the timelock contract |
_feeCollector | address | Address of the fee collector contract |
mintQEURO
Mints QEURO tokens by swapping USDC
Minting process:
- Fetch EUR/USD price from oracle
- Calculate amount of QEURO to mint
- Transfer USDC from user
- Update vault balances
- Mint QEURO to user
Example: 1100 USDC → ~1000 QEURO (if EUR/USD = 1.10) Simple swap with protocol fee applied
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: No access restrictions
-
oracle: Requires fresh oracle price data
function mintQEURO(uint256 usdcAmount, uint256 minQeuroOut)
external
nonReentrant
whenNotPaused
flashLoanProtection;
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC to swap for QEURO |
minQeuroOut | uint256 | Minimum amount of QEURO expected (slippage protection) |
redeemQEURO
Redeems QEURO for USDC
Redeem process:
- Calculate USDC to return based on EUR/USD price
- Apply protocol fees
- Burn QEURO
- Update vault balances
- Transfer USDC to user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: No access restrictions
-
oracle: Requires fresh oracle price data
-
security: No flash loan protection needed - legitimate redemption operation
function redeemQEURO(uint256 qeuroAmount, uint256 minUsdcOut) external nonReentrant whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to swap for USDC |
minUsdcOut | uint256 | Minimum amount of USDC expected |
getVaultMetrics
Retrieves the vault's global metrics
Returns comprehensive vault metrics for monitoring and analytics
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function getVaultMetrics() external returns (uint256 totalUsdcHeld_, uint256 totalMinted_, uint256 totalDebtValue);
Returns
| Name | Type | Description |
|---|---|---|
totalUsdcHeld_ | uint256 | Total USDC held in the vault |
totalMinted_ | uint256 | Total QEURO minted |
totalDebtValue | uint256 | Total debt value in USD |
calculateMintAmount
Calculates the amount of QEURO that can be minted for a given USDC amount
Calculates mint amount based on current oracle price and protocol fees
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: Requires fresh oracle price data
function calculateMintAmount(uint256 usdcAmount) external returns (uint256 qeuroAmount, uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC to swap |
Returns
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO that will be minted (after fees) |
fee | uint256 | Protocol fee |
calculateRedeemAmount
Calculates the amount of USDC received for a QEURO redemption
Calculates redeem amount based on current oracle price and protocol fees
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: Requires fresh oracle price data
function calculateRedeemAmount(uint256 qeuroAmount) external returns (uint256 usdcAmount, uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to redeem |
Returns
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | USDC received (after fees) |
fee | uint256 | Protocol fee |
isProtocolCollateralized
Checks if the protocol is properly collateralized by hedgers
Public view function to check collateralization status
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check collateralization status
-
oracle: No oracle dependencies
function isProtocolCollateralized() external view returns (bool isCollateralized, uint256 totalMargin);
Returns
| Name | Type | Description |
|---|---|---|
isCollateralized | bool | True if protocol has active hedging positions |
totalMargin | uint256 | Total margin in HedgerPool (0 if not set) |
updateParameters
Updates the vault parameters (governance only)
Safety constraints:
- Fees <= 5% (user protection)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateParameters(uint256 _mintFee, uint256 _redemptionFee) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_mintFee | uint256 | New minting fee |
_redemptionFee | uint256 | New redemption fee |
updateCollateralizationThresholds
Updates the collateralization thresholds (governance only)
Safety constraints:
- minCollateralizationRatioForMinting >= 10100 (101% minimum)
- criticalCollateralizationRatio <= minCollateralizationRatioForMinting
- criticalCollateralizationRatio >= 10000 (100% minimum)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateCollateralizationThresholds(
uint256 _minCollateralizationRatioForMinting,
uint256 _criticalCollateralizationRatio
) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_minCollateralizationRatioForMinting | uint256 | New minimum collateralization ratio for minting (in basis points) |
_criticalCollateralizationRatio | uint256 | New critical collateralization ratio for liquidation (in basis points) |
updateOracle
Updates the oracle address
Updates the oracle contract address for price feeds
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateOracle(address _oracle) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_oracle | address | New oracle address |
updateHedgerPool
Updates the HedgerPool address
Updates the HedgerPool contract address for collateralization checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateHedgerPool(address _hedgerPool) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_hedgerPool | address | New HedgerPool address |
updateUserPool
Updates the UserPool address
Updates the UserPool contract address for user deposit tracking
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateUserPool(address _userPool) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_userPool | address | New UserPool address |
updateFeeCollector
Updates the fee collector address
Only governance role can update the fee collector address
Notes:
-
security: Validates address is not zero before updating
-
validation: Ensures _feeCollector is not address(0)
-
state-changes: Updates feeCollector state variable
-
events: Emits ParametersUpdated event
-
errors: Reverts if _feeCollector is address(0)
-
reentrancy: No reentrancy risk, simple state update
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateFeeCollector(address _feeCollector) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_feeCollector | address | New fee collector address |
updatePriceProtectionParams
Updates price deviation protection parameters
Only governance can update these security parameters
Note: This function requires converting constants to state variables for full implementation. Currently a placeholder for future governance control.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updatePriceProtectionParams(uint256 _maxPriceDeviation, uint256 _minBlocksBetweenUpdates)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_maxPriceDeviation | uint256 | New maximum price deviation in basis points |
_minBlocksBetweenUpdates | uint256 | New minimum blocks between updates |
withdrawProtocolFees
Withdraws accumulated protocol fees
Fees accumulate during minting and redemptions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function withdrawProtocolFees(address to) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Destination address for the fees |
addHedgerDeposit
Adds hedger USDC deposit to vault's total USDC reserves
Called by HedgerPool when hedgers open positions to unify USDC liquidity
Notes:
-
security: Validates caller is HedgerPool contract and amount is positive
-
validation: Validates amount > 0 and caller is authorized HedgerPool
-
state-changes: Updates totalUsdcHeld with hedger deposit amount
-
events: Emits HedgerDepositAdded with deposit details
-
errors: Throws "Vault: Only HedgerPool can call" if caller is not HedgerPool
-
errors: Throws "Vault: Amount must be positive" if amount is zero
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to HedgerPool contract only
-
oracle: No oracle dependencies
function addHedgerDeposit(uint256 usdcAmount) external nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC deposited by hedger (6 decimals) |
withdrawHedgerDeposit
Withdraws hedger USDC deposit from vault's reserves
Called by HedgerPool when hedgers close positions to return their deposits
Notes:
-
security: Validates caller is HedgerPool, amount is positive, and sufficient reserves
-
validation: Validates amount > 0, caller is authorized, and totalUsdcHeld >= amount
-
state-changes: Updates totalUsdcHeld and transfers USDC to hedger
-
events: Emits HedgerDepositWithdrawn with withdrawal details
-
errors: Throws "Vault: Only HedgerPool can call" if caller is not HedgerPool
-
errors: Throws "Vault: Amount must be positive" if amount is zero
-
errors: Throws "Vault: Insufficient USDC reserves" if not enough USDC available
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to HedgerPool contract only
-
oracle: No oracle dependencies
function withdrawHedgerDeposit(address hedger, uint256 usdcAmount) external nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger receiving the USDC |
usdcAmount | uint256 | Amount of USDC to withdraw (6 decimals) |
getTotalUsdcAvailable
Gets the total USDC available for hedger deposits
Returns the current total USDC held in the vault for transparency
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public access - anyone can query total USDC held
-
oracle: No oracle dependencies
function getTotalUsdcAvailable() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total USDC held in vault (6 decimals) |
_updatePriceTimestamp
Updates the last valid price timestamp when a valid price is fetched
Internal function to track price update timing for monitoring
Notes:
-
security: Updates timestamp only for valid price fetches
-
validation: No input validation required
-
state-changes: Updates lastPriceUpdateTime if price is valid
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _updatePriceTimestamp(bool isValid) internal;
Parameters
| Name | Type | Description |
|---|---|---|
isValid | bool | Whether the current price fetch was valid |
getProtocolCollateralizationRatio
Calculates the current protocol collateralization ratio
Formula: ((A + B) / A) * 100 where A = user deposits, B = hedger deposits
Returns ratio in basis points (e.g., 10500 = 105%)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes - view function
-
events: No events emitted - view function
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check collateralization ratio
-
oracle: No oracle dependencies
function getProtocolCollateralizationRatio() public returns (uint256 ratio);
Returns
| Name | Type | Description |
|---|---|---|
ratio | uint256 | Current collateralization ratio in basis points |
canMint
Checks if minting is allowed based on current collateralization ratio
Returns true if collateralization ratio >= minCollateralizationRatioForMinting
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes - view function
-
events: No events emitted - view function
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check minting status
-
oracle: No oracle dependencies
function canMint() public returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | canMint Whether minting is currently allowed |
shouldTriggerLiquidation
Checks if liquidation should be triggered based on current collateralization ratio
Returns true if collateralization ratio < criticalCollateralizationRatio
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: No state changes - view function
-
events: No events emitted - view function
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check liquidation status
-
oracle: No oracle dependencies
function shouldTriggerLiquidation() public returns (bool shouldLiquidate);
Returns
| Name | Type | Description |
|---|---|---|
shouldLiquidate | bool | Whether liquidation should be triggered |
getPriceProtectionStatus
Returns the current price protection status
Useful for monitoring and debugging price protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPriceProtectionStatus()
external
view
returns (uint256 lastValidPrice, uint256 lastUpdateBlock, uint256 maxDeviation, uint256 minBlocks);
Returns
| Name | Type | Description |
|---|---|---|
lastValidPrice | uint256 | Last valid EUR/USD price used |
lastUpdateBlock | uint256 | Block number of last price update |
maxDeviation | uint256 | Maximum allowed price deviation in basis points |
minBlocks | uint256 | Minimum blocks required between updates |
pause
Pauses all vault operations
When paused:
- No mint/redeem possible
- Read functions still active
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external onlyRole(EMERGENCY_ROLE);
unpause
Unpauses and resumes operations
Resumes all vault operations after emergency pause
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external onlyRole(EMERGENCY_ROLE);
recoverToken
Recovers tokens accidentally sent to the vault to treasury only
Protections:
- Cannot recover own vault tokens
- Tokens are sent to treasury address only
- Only third-party tokens can be recovered
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function recoverToken(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token contract address |
amount | uint256 | Amount to recover |
recoverETH
Recover ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Security considerations:
- Only DEFAULT_ADMIN_ROLE can recover
- Prevents sending to zero address
- Validates balance before attempting transfer
- Uses call() for reliable ETH transfers to any contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
Events
QEUROminted
Emitted when QEURO is minted
event QEUROminted(address indexed user, uint256 usdcAmount, uint256 qeuroAmount);
QEURORedeemed
Emitted when QEURO is redeemed
event QEURORedeemed(address indexed user, uint256 qeuroAmount, uint256 usdcAmount);
HedgerDepositAdded
Emitted when hedger deposits USDC to vault for unified liquidity
event HedgerDepositAdded(address indexed hedgerPool, uint256 usdcAmount, uint256 totalUsdcHeld);
Parameters
| Name | Type | Description |
|---|---|---|
hedgerPool | address | Address of the HedgerPool contract that made the deposit |
usdcAmount | uint256 | Amount of USDC deposited (6 decimals) |
totalUsdcHeld | uint256 | New total USDC held in vault after deposit (6 decimals) |
HedgerDepositWithdrawn
Emitted when hedger withdraws USDC from vault
event HedgerDepositWithdrawn(address indexed hedger, uint256 usdcAmount, uint256 totalUsdcHeld);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger receiving the USDC |
usdcAmount | uint256 | Amount of USDC withdrawn (6 decimals) |
totalUsdcHeld | uint256 | New total USDC held in vault after withdrawal (6 decimals) |
ParametersUpdated
Emitted when parameters are changed
OPTIMIZED: Indexed parameter type for efficient filtering
event ParametersUpdated(string indexed parameterType, uint256 mintFee, uint256 redemptionFee);
CollateralizationThresholdsUpdated
Emitted when price deviation protection is triggered
Emitted when collateralization thresholds are updated by governance
Helps monitor potential flash loan attacks
event CollateralizationThresholdsUpdated(
uint256 indexed minCollateralizationRatioForMinting,
uint256 indexed criticalCollateralizationRatio,
address indexed caller
);
Parameters
| Name | Type | Description |
|---|---|---|
minCollateralizationRatioForMinting | uint256 | New minimum collateralization ratio for minting (in basis points) |
criticalCollateralizationRatio | uint256 | New critical collateralization ratio for liquidation (in basis points) |
caller | address | Address of the governance role holder who updated the thresholds |
CollateralizationStatusChanged
Emitted when protocol collateralization status changes
event CollateralizationStatusChanged(
uint256 indexed currentRatio, bool indexed canMint, bool indexed shouldLiquidate
);
Parameters
| Name | Type | Description |
|---|---|---|
currentRatio | uint256 | Current protocol collateralization ratio (in basis points) |
canMint | bool | Whether minting is currently allowed based on collateralization |
shouldLiquidate | bool | Whether liquidation should be triggered based on collateralization |
PriceDeviationDetected
event PriceDeviationDetected(
uint256 currentPrice, uint256 lastValidPrice, uint256 deviationBps, uint256 blockNumber
);
SecureUpgradeable
Inherits: UUPSUpgradeable, AccessControlUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Secure base contract for upgradeable contracts with timelock protection
Replaces UUPSUpgradeable with timelock and multi-sig requirements
Note: security-contact: team@quantillon.money
State Variables
UPGRADER_ROLE
Role for upgrade operations
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE")
timelock
Timelock contract for secure upgrades
ITimelockUpgradeable public timelock
secureUpgradesEnabled
Whether the contract is using secure upgrades
bool public secureUpgradesEnabled
Functions
onlyTimelock
modifier onlyTimelock() ;
__SecureUpgradeable_init
Initializes the SecureUpgradeable contract
Sets up the secure upgrade system with timelock protection
Notes:
-
security: Validates timelock address and initializes secure upgrade system
-
validation: Validates _timelock is not address(0)
-
state-changes: Initializes timelock, enables secure upgrades, sets up access control
-
events: Emits TimelockSet and SecureUpgradesToggled events
-
errors: Throws "SecureUpgradeable: Invalid timelock" if _timelock is address(0)
-
reentrancy: Protected by onlyInitializing modifier
-
access: Internal function - only callable during initialization
-
oracle: No oracle dependencies
function __SecureUpgradeable_init(address _timelock) internal onlyInitializing;
Parameters
| Name | Type | Description |
|---|---|---|
_timelock | address | Address of the timelock contract |
setTimelock
Set the timelock contract
Configures the timelock contract for secure upgrade management
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setTimelock(address _timelock) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_timelock | address | Address of the timelock contract |
toggleSecureUpgrades
Toggle secure upgrades
Enables or disables the secure upgrade mechanism
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function toggleSecureUpgrades(bool enabled) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable secure upgrades |
proposeUpgrade
Propose an upgrade through the timelock
Initiates a secure upgrade proposal with timelock delay and multi-sig requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function proposeUpgrade(address newImplementation, string calldata description, uint256 customDelay)
external
onlyRole(UPGRADER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the upgrade |
customDelay | uint256 | Optional custom delay |
executeUpgrade
Execute an upgrade through the timelock
Executes a previously proposed upgrade after timelock delay
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function executeUpgrade(address newImplementation) external onlyTimelock;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
emergencyUpgrade
Emergency upgrade (bypasses timelock, requires emergency mode)
Allows emergency upgrades when secure upgrades are disabled or timelock is unavailable
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyUpgrade(address newImplementation, string calldata description) external onlyRole(UPGRADER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the emergency upgrade |
_authorizeUpgrade
Authorize upgrade (overrides UUPSUpgradeable)
Internal function that determines upgrade authorization based on secure upgrade settings
function _authorizeUpgrade(address newImplementation) internal view override;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
isUpgradePending
Check if an upgrade is pending
Checks if there is a pending upgrade for the specified implementation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isUpgradePending(address implementation) external view returns (bool isPending);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
isPending | bool | Whether the upgrade is pending |
getPendingUpgrade
Get pending upgrade details
Returns detailed information about a pending upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPendingUpgrade(address implementation)
external
view
returns (ITimelockUpgradeable.PendingUpgrade memory upgrade);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
upgrade | ITimelockUpgradeable.PendingUpgrade | Pending upgrade details |
canExecuteUpgrade
Check if an upgrade can be executed
Checks if a pending upgrade has passed the timelock delay and can be executed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function canExecuteUpgrade(address implementation) external view returns (bool canExecute);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
canExecute | bool | Whether the upgrade can be executed |
getUpgradeSecurityStatus
Get upgrade security status
Returns the current security configuration for upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUpgradeSecurityStatus()
external
view
returns (address timelockAddress, bool secureUpgradesEnabled_, bool hasTimelock);
Returns
| Name | Type | Description |
|---|---|---|
timelockAddress | address | Address of the timelock contract |
secureUpgradesEnabled_ | bool | Whether secure upgrades are enabled |
hasTimelock | bool | Whether timelock is set |
emergencyDisableSecureUpgrades
Disable secure upgrades in emergency
Disables secure upgrades for emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyDisableSecureUpgrades() external onlyRole(DEFAULT_ADMIN_ROLE);
enableSecureUpgrades
Enable secure upgrades after emergency
Re-enables secure upgrades after emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function enableSecureUpgrades() external onlyRole(DEFAULT_ADMIN_ROLE);
Events
TimelockSet
event TimelockSet(address indexed timelock);
SecureUpgradesToggled
event SecureUpgradesToggled(bool enabled);
SecureUpgradeAuthorized
event SecureUpgradeAuthorized(address indexed newImplementation, address indexed authorizedBy, string description);
TimelockUpgradeable
Inherits: Initializable, AccessControlUpgradeable, PausableUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Secure upgrade mechanism with timelock and multi-sig requirements
Replaces unrestricted upgrade capability with governance-controlled upgrades
Note: security-contact: team@quantillon.money
State Variables
UPGRADE_DELAY
Minimum delay for upgrades (48 hours)
uint256 public constant UPGRADE_DELAY = 48 hours
MAX_UPGRADE_DELAY
Maximum delay for upgrades (7 days)
uint256 public constant MAX_UPGRADE_DELAY = 7 days
MIN_MULTISIG_APPROVALS
Minimum number of multi-sig approvals required
uint256 public constant MIN_MULTISIG_APPROVALS = 2
MAX_MULTISIG_SIGNERS
Maximum number of multi-sig signers
uint256 public constant MAX_MULTISIG_SIGNERS = 5
UPGRADE_PROPOSER_ROLE
Role for proposing upgrades
bytes32 public constant UPGRADE_PROPOSER_ROLE = keccak256("UPGRADE_PROPOSER_ROLE")
UPGRADE_EXECUTOR_ROLE
Role for executing upgrades after timelock
bytes32 public constant UPGRADE_EXECUTOR_ROLE = keccak256("UPGRADE_EXECUTOR_ROLE")
EMERGENCY_UPGRADER_ROLE
Role for emergency upgrades (bypasses timelock)
bytes32 public constant EMERGENCY_UPGRADER_ROLE = keccak256("EMERGENCY_UPGRADER_ROLE")
MULTISIG_MANAGER_ROLE
Role for managing multi-sig signers
bytes32 public constant MULTISIG_MANAGER_ROLE = keccak256("MULTISIG_MANAGER_ROLE")
pendingUpgrades
Pending upgrades by implementation address
mapping(address => PendingUpgrade) public pendingUpgrades
multisigSigners
Multi-sig signers
mapping(address => bool) public multisigSigners
multisigSignerCount
Number of active multi-sig signers
uint256 public multisigSignerCount
upgradeApprovals
Upgrade approvals by signer
mapping(address => mapping(address => bool)) public upgradeApprovals
upgradeApprovalCount
Number of approvals for each pending upgrade
mapping(address => uint256) public upgradeApprovalCount
emergencyMode
Whether emergency mode is active
bool public emergencyMode
TIME_PROVIDER
TimeProvider contract for centralized time management
Used to replace direct block.timestamp usage for testability and consistency
TimeProvider public immutable TIME_PROVIDER
Functions
onlyMultisigSigner
modifier onlyMultisigSigner() ;
onlyEmergencyUpgrader
modifier onlyEmergencyUpgrader() ;
initialize
Initializes the timelock contract with admin privileges
Sets up access control roles and pausability. Can only be called once.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(address admin) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | The address that will receive admin and upgrade proposer roles |
proposeUpgrade
Propose an upgrade with timelock
Proposes an upgrade with timelock delay and multi-sig approval requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to UPGRADE_PROPOSER_ROLE
-
oracle: No oracle dependencies
function proposeUpgrade(address newImplementation, string calldata description, uint256 customDelay)
external
onlyRole(UPGRADE_PROPOSER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the upgrade |
customDelay | uint256 | Optional custom delay (must be >= UPGRADE_DELAY) |
approveUpgrade
Approve a pending upgrade (multi-sig signer only)
Allows multi-sig signers to approve pending upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to multi-sig signers
-
oracle: No oracle dependencies
function approveUpgrade(address implementation) external onlyMultisigSigner;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to approve |
revokeUpgradeApproval
Revoke approval for a pending upgrade
Allows multi-sig signers to revoke their approval for pending upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to multi-sig signers
-
oracle: No oracle dependencies
function revokeUpgradeApproval(address implementation) external onlyMultisigSigner;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to revoke approval for |
executeUpgrade
Execute an upgrade after timelock and multi-sig approval
Executes an upgrade after timelock delay and sufficient multi-sig approvals
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to UPGRADE_EXECUTOR_ROLE
-
oracle: No oracle dependencies
function executeUpgrade(address implementation) external onlyRole(UPGRADE_EXECUTOR_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to execute |
cancelUpgrade
Cancel a pending upgrade (only proposer or admin)
Allows proposer or admin to cancel pending upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to proposer or admin
-
oracle: No oracle dependencies
function cancelUpgrade(address implementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to cancel |
emergencyUpgrade
Emergency upgrade (bypasses timelock, requires emergency mode)
Performs emergency upgrade bypassing timelock and multi-sig requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to emergency upgrader role
-
oracle: No oracle dependencies
function emergencyUpgrade(address newImplementation, string calldata description) external onlyEmergencyUpgrader;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the emergency upgrade |
addMultisigSigner
Add a multi-sig signer
Adds a new multi-sig signer to the timelock system
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to MULTISIG_MANAGER_ROLE
-
oracle: No oracle dependencies
function addMultisigSigner(address signer) external onlyRole(MULTISIG_MANAGER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer to add |
removeMultisigSigner
Remove a multi-sig signer
Removes a multi-sig signer from the timelock system
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to MULTISIG_MANAGER_ROLE
-
oracle: No oracle dependencies
function removeMultisigSigner(address signer) external onlyRole(MULTISIG_MANAGER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer to remove |
toggleEmergencyMode
Toggle emergency mode
Toggles emergency mode for emergency upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to EMERGENCY_UPGRADER_ROLE
-
oracle: No oracle dependencies
function toggleEmergencyMode(bool enabled, string calldata reason) external onlyRole(EMERGENCY_UPGRADER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable emergency mode |
reason | string | Reason for the emergency mode change |
getPendingUpgrade
Get pending upgrade details
Returns pending upgrade details for a given implementation
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function getPendingUpgrade(address implementation) external view returns (PendingUpgrade memory upgrade);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
upgrade | PendingUpgrade | Pending upgrade details |
canExecuteUpgrade
Check if an upgrade can be executed
Checks if an upgrade can be executed based on timelock and approval requirements
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function canExecuteUpgrade(address implementation) external view returns (bool canExecute);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
canExecute | bool | Whether the upgrade can be executed |
hasUpgradeApproval
Get upgrade approval status for a signer
Returns whether a signer has approved a specific upgrade
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function hasUpgradeApproval(address signer, address implementation) external view returns (bool approved);
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer |
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
approved | bool | Whether the signer has approved the upgrade |
getMultisigSigners
Get all multi-sig signers
Returns array of all multi-sig signer addresses
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: No state changes
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
function getMultisigSigners() external view returns (address[] memory signers);
Returns
| Name | Type | Description |
|---|---|---|
signers | address[] | Array of signer addresses |
_clearUpgradeApprovals
Clear all approvals for an implementation
Clears all approvals for a specific implementation
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: Updates contract state variables
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _clearUpgradeApprovals(address implementation) internal;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
_clearSignerApprovals
Clear all approvals from a specific signer
Clears all approvals from a specific signer
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: Updates contract state variables
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _clearSignerApprovals(address signer) internal;
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer |
_addMultisigSigner
Add a multisig signer (internal)
Adds a multisig signer internally
Notes:
-
security: No security checks needed
-
validation: No validation needed
-
state-changes: Updates contract state variables
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: No reentrancy protection needed
-
access: Internal function
-
oracle: No oracle dependencies
function _addMultisigSigner(address signer) internal;
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer |
pause
Pause the timelock contract
Pauses the timelock contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function pause() external onlyRole(DEFAULT_ADMIN_ROLE);
unpause
Unpause the timelock contract
Unpauses the timelock contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE);
constructor
Constructor for TimelockUpgradeable contract
Sets up the time provider and disables initializers for security
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Disables initializers
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | TimeProvider contract for centralized time management |
Events
UpgradeProposed
event UpgradeProposed(
address indexed implementation,
uint256 proposedAt,
uint256 executableAt,
string description,
address indexed proposer
);
UpgradeApproved
event UpgradeApproved(address indexed implementation, address indexed signer, uint256 approvalCount);
UpgradeExecuted
event UpgradeExecuted(address indexed implementation, address indexed executor, uint256 executedAt);
UpgradeCancelled
event UpgradeCancelled(address indexed implementation, address indexed canceller);
MultisigSignerAdded
event MultisigSignerAdded(address indexed signer);
MultisigSignerRemoved
event MultisigSignerRemoved(address indexed signer);
EmergencyModeToggled
event EmergencyModeToggled(bool enabled, string reason);
Structs
PendingUpgrade
struct PendingUpgrade {
address implementation;
uint256 proposedAt;
uint256 executableAt;
string description;
bool isEmergency;
address proposer;
}
UserPool
Inherits: Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable, PausableUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Manages QEURO user deposits, staking, and yield distribution
Main characteristics:
- User deposit and withdrawal management
- QEURO staking mechanism with rewards
- Yield distribution system
- Fee structure for protocol sustainability
- Emergency pause mechanism for crisis situations
- Upgradeable via UUPS pattern
Deposit mechanics:
- Users deposit USDC to receive QEURO
- QEURO is minted based on current EUR/USD exchange rate
- Deposit fees charged for protocol revenue
- Deposits are tracked per user for analytics
Staking mechanics:
- Users can stake their QEURO for additional rewards
- Staking APY provides yield on staked QEURO
- Unstaking has a cooldown period to prevent abuse
- Rewards are distributed based on staking duration and amount
Withdrawal mechanics:
- Users can withdraw their QEURO back to USDC
- Withdrawal fees charged for protocol revenue
- Withdrawals are processed based on current EUR/USD rate
- Staked QEURO must be unstaked before withdrawal
Yield distribution:
- Yield is distributed to stakers based on their stake amount
- Performance fees charged on yield distributions
- Yield sources include protocol fees and yield shift mechanisms
- Real-time yield tracking and distribution
Fee structure:
- Deposit fees for creating QEURO from USDC
- Withdrawal fees for converting QEURO back to USDC
- Performance fees on yield distributions
- Dynamic fee adjustment based on market conditions
Security features:
- Role-based access control for all critical operations
- Reentrancy protection for all external calls
- Emergency pause mechanism for crisis situations
- Upgradeable architecture for future improvements
- Secure deposit and withdrawal management
- Staking cooldown mechanisms
- Batch size limits to prevent DoS attacks
- Gas optimization through storage read caching
Integration points:
- QEURO token for minting and burning
- USDC for deposits and withdrawals
- QuantillonVault for QEURO minting/burning
- Yield shift mechanism for yield management
- Vault math library for calculations
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
Role for governance operations (parameter updates, emergency actions)
keccak256 hash avoids role collisions with other contracts
Should be assigned to governance multisig or DAO
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
EMERGENCY_ROLE
Role for emergency operations (pause, emergency withdrawals)
keccak256 hash avoids role collisions with other contracts
Should be assigned to emergency multisig
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
qeuro
QEURO token contract for minting and burning
Used for all QEURO minting and burning operations
Should be the official QEURO token contract
IQEUROToken public qeuro
usdc
USDC token contract for deposits and withdrawals
Used for all USDC deposits and withdrawals
Should be the official USDC contract on the target network
IERC20 public usdc
vault
Main Quantillon vault for QEURO operations
Used for QEURO minting and burning operations
Should be the official QuantillonVault contract
IQuantillonVault public vault
oracle
Chainlink Oracle for EUR/USD price feeds
Used for converting QEURO supply to USDC equivalent in analytics
IChainlinkOracle public oracle
yieldShift
Yield shift mechanism for yield management
Handles yield distribution and management
Used for yield calculations and distributions
IYieldShift public yieldShift
treasury
Treasury address for ETH recovery
SECURITY: Only this address can receive ETH from recoverETH function
address public treasury
TIME_PROVIDER
TimeProvider contract for centralized time management
Used to replace direct block.timestamp usage for testability and consistency
TimeProvider public immutable TIME_PROVIDER
stakingAPY
Staking APY in basis points
Example: 500 = 5% staking APY
Used for calculating staking rewards
uint256 public stakingAPY
depositAPY
Base deposit APY in basis points
Example: 200 = 2% base deposit APY
Used for calculating deposit rewards
uint256 public depositAPY
minStakeAmount
Minimum amount required for staking (in QEURO)
Example: 100 * 1e18 = 100 QEURO minimum stake
Prevents dust staking and reduces gas costs
uint256 public minStakeAmount
unstakingCooldown
Cooldown period for unstaking (in seconds)
Example: 7 days = 604,800 seconds
Prevents rapid staking/unstaking cycles
uint256 public unstakingCooldown
depositFee
Fee charged on deposits (in basis points)
Example: 10 = 0.1% deposit fee
Revenue source for the protocol
uint256 public depositFee
withdrawalFee
Fee charged on withdrawals (in basis points)
Example: 10 = 0.1% withdrawal fee
Revenue source for the protocol
uint256 public withdrawalFee
performanceFee
Fee charged on yield distributions (in basis points)
Example: 200 = 2% performance fee
Revenue source for the protocol
uint256 public performanceFee
totalStakes
Total QEURO staked across all users
Sum of all staked QEURO amounts
Used for yield distribution calculations
uint256 public totalStakes
totalUsers
Number of unique users who have deposited
Count of unique addresses that have made deposits
Used for protocol analytics and governance
uint256 public totalUsers
userInfo
User information by address
Maps user addresses to their detailed information
Used to track user deposits, stakes, and rewards
mapping(address => UserInfo) public userInfo
hasDeposited
Whether a user has ever deposited
Maps user addresses to their deposit status
Used to track unique users and prevent double counting
mapping(address => bool) public hasDeposited
accumulatedYieldPerShare
Accumulated yield per staked QEURO share
Used for calculating user rewards based on their stake amount
Increases over time as yield is distributed
uint256 public accumulatedYieldPerShare
lastYieldDistribution
Timestamp of last yield distribution
Used to track when yield was last distributed
Used for yield calculation intervals
uint256 public lastYieldDistribution
totalYieldDistributed
Total yield distributed to users
Sum of all yield distributed to users
Used for protocol analytics and governance
uint256 public totalYieldDistributed
totalUserDeposits
Total USDC deposits across all users (in USDC decimals - 6)
Tracks the sum of all USDC deposits made by users
Used for protocol analytics and collateralization calculations
uint256 public totalUserDeposits
totalUserWithdrawals
Total QEURO withdrawals across all users (in QEURO decimals - 18)
Tracks the sum of all QEURO withdrawals made by users
Used for protocol analytics and supply tracking
uint256 public totalUserWithdrawals
userDeposits
User deposit tracking with oracle ratios
Maps user addresses to their deposit history with oracle ratios
Used for detailed analytics and audit trails
mapping(address => UserDepositInfo[]) public userDeposits
userWithdrawals
User withdrawal tracking with oracle ratios
Maps user addresses to their withdrawal history with oracle ratios
Used for detailed analytics and audit trails
mapping(address => UserWithdrawalInfo[]) public userWithdrawals
userLastRewardBlock
mapping(address => uint256) public userLastRewardBlock
BLOCKS_PER_DAY
uint256 public constant BLOCKS_PER_DAY = 7200
MAX_REWARD_PERIOD
uint256 public constant MAX_REWARD_PERIOD = 365 days
MAX_BATCH_SIZE
Maximum batch size for deposit operations to prevent DoS
Prevents out-of-gas attacks through large arrays
uint256 public constant MAX_BATCH_SIZE = 100
MAX_REWARD_BATCH_SIZE
Maximum batch size for reward claim operations to prevent DoS
Prevents out-of-gas attacks through large user arrays
uint256 public constant MAX_REWARD_BATCH_SIZE = 50
Functions
flashLoanProtection
Modifier to protect against flash loan attacks
Uses the FlashLoanProtectionLibrary to check USDC balance consistency
modifier flashLoanProtection() ;
constructor
Constructor for UserPool contract
Sets up the time provider and disables initializers for security
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Disables initializers
-
events: No events emitted
-
errors: Throws custom errors for invalid conditions
-
reentrancy: No reentrancy protection needed
-
access: No access restrictions
-
oracle: No oracle dependencies
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | TimeProvider contract for centralized time management |
initialize
Initializes the UserPool contract
Initializes the UserPool with all required contracts and default parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Initializes all contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: Requires oracle for analytics functions
function initialize(
address admin,
address _qeuro,
address _usdc,
address _vault,
address _oracle,
address _yieldShift,
address _timelock,
address _treasury
) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address that receives admin and governance roles |
_qeuro | address | Address of the QEURO token contract |
_usdc | address | Address of the USDC token contract |
_vault | address | Address of the QuantillonVault contract |
_oracle | address | Address of the Chainlink Oracle contract |
_yieldShift | address | Address of the YieldShift contract |
_timelock | address | Address of the timelock contract |
_treasury | address | Address of the treasury contract |
deposit
Deposit USDC to mint QEURO (unified single/batch function)
Handles both single deposits and batch deposits in one function
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Public access
-
oracle: No oracle dependencies
function deposit(uint256[] calldata usdcAmounts, uint256[] calldata minQeuroOuts)
external
nonReentrant
whenNotPaused
flashLoanProtection
returns (uint256[] memory qeuroMintedAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmounts | uint256[] | Array of USDC amounts to deposit (6 decimals) - use [amount] for single |
minQeuroOuts | uint256[] | Array of minimum QEURO amounts to receive (18 decimals) - use [amount] for single |
Returns
| Name | Type | Description |
|---|---|---|
qeuroMintedAmounts | uint256[] | Array of QEURO amounts minted (18 decimals) |
_validateAndTransferTokens
Internal function to validate amounts and transfer tokens (unified validation)
Unified validation and transfer function to reduce code duplication
Notes:
-
security: Validates all amounts > 0 before transfer
-
validation: Validates each amount in array is positive
-
state-changes: Transfers tokens from/to msg.sender
-
events: No events emitted - handled by calling function
-
errors: Throws if any amount is 0
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _validateAndTransferTokens(uint256[] calldata amounts, IERC20 token, bool isFromUser)
internal
returns (uint256 totalAmount);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of amounts to validate and transfer |
token | IERC20 | Token to transfer (usdc or qeuro) |
isFromUser | bool | Whether to transfer from user (true) or to user (false) |
Returns
| Name | Type | Description |
|---|---|---|
totalAmount | uint256 | Total amount transferred |
_initializeUserIfNeeded
Internal function to initialize user if needed (consolidated)
Initializes user tracking if they haven't deposited before
Notes:
-
security: Updates hasDeposited mapping and totalUsers counter
-
validation: No input validation required
-
state-changes: Updates hasDeposited[msg.sender] and totalUsers
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _initializeUserIfNeeded() internal;
_calculateNetAmounts
Internal function to calculate net amounts after fees
Calculates net amounts by subtracting deposit fees from each USDC amount
Notes:
-
security: Uses cached depositFee to prevent reentrancy
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _calculateNetAmounts(uint256[] calldata usdcAmounts)
internal
view
returns (uint256[] memory netAmounts, uint256 totalNetAmount);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmounts | uint256[] | Array of USDC amounts (6 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
netAmounts | uint256[] | Array of net amounts after fees (6 decimals) |
totalNetAmount | uint256 | Total net amount (6 decimals) |
_processVaultMinting
Internal function to process vault minting operations
Processes vault minting operations with single vault call to avoid external calls in loop
Notes:
-
security: Uses single approval and single vault call to minimize external calls
-
validation: No input validation required - parameters pre-validated
-
state-changes: Updates qeuroMintedAmounts array with minted amounts
-
events: No events emitted - handled by calling function
-
errors: Throws if vault.mintQEURO fails
-
reentrancy: Protected by nonReentrant modifier on calling function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _processVaultMinting(
uint256[] memory netAmounts,
uint256[] calldata minQeuroOuts,
uint256[] memory qeuroMintedAmounts
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
netAmounts | uint256[] | Array of net amounts to mint (6 decimals) |
minQeuroOuts | uint256[] | Array of minimum QEURO outputs (18 decimals) |
qeuroMintedAmounts | uint256[] | Array to store minted amounts (18 decimals) |
_updateUserAndPoolState
Internal function to update user and pool state
Updates user and pool state before external calls for reentrancy protection
Notes:
-
security: Updates state before external calls (CEI pattern)
-
validation: No input validation required - parameters pre-validated
-
state-changes: Updates user.depositHistory, totalDeposits
-
events: No events emitted - handled by calling function
-
errors: No errors thrown
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _updateUserAndPoolState(
uint256[] calldata usdcAmounts,
uint256[] calldata minQeuroOuts,
uint256 /* totalNetAmount */
)
internal;
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmounts | uint256[] | Array of USDC amounts (6 decimals) |
minQeuroOuts | uint256[] | Array of minimum QEURO outputs (18 decimals) |
<none> | uint256 |
_transferQeuroAndEmitEvents
Internal function to transfer QEURO and emit events
Transfers QEURO to users and emits UserDeposit events
Notes:
-
security: Uses SafeERC20 for secure token transfers
-
validation: No input validation required - parameters pre-validated
-
state-changes: Transfers QEURO tokens to msg.sender
-
events: Emits UserDeposit event for each transfer
-
errors: Throws if QEURO transfer fails
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _transferQeuroAndEmitEvents(
uint256[] calldata usdcAmounts,
uint256[] memory qeuroMintedAmounts,
uint256 currentTime
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmounts | uint256[] | Array of USDC amounts (6 decimals) |
qeuroMintedAmounts | uint256[] | Array of minted QEURO amounts (18 decimals) |
currentTime | uint256 | Current timestamp |
withdraw
Withdraw USDC by burning QEURO (unified single/batch function)
Handles both single withdrawals and batch withdrawals in one function
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Public access
-
oracle: No oracle dependencies
function withdraw(uint256[] calldata qeuroAmounts, uint256[] calldata minUsdcOuts)
external
nonReentrant
whenNotPaused
returns (uint256[] memory usdcReceivedAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts to burn (18 decimals) - use [amount] for single |
minUsdcOuts | uint256[] | Array of minimum USDC amounts to receive (6 decimals) - use [amount] for single |
Returns
| Name | Type | Description |
|---|---|---|
usdcReceivedAmounts | uint256[] | Array of USDC amounts received (6 decimals) |
_validateAndProcessBatchWithdrawal
Validates and processes batch withdrawal
Internal helper to reduce stack depth
Notes:
-
security: Validates amounts and user balances to prevent over-withdrawal
-
validation: Validates all amounts are positive and user has sufficient balance
-
state-changes: Updates user balance and processes withdrawal calculations
-
events: No events emitted - internal helper function
-
errors: Throws "Amount must be positive" if any amount is zero
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _validateAndProcessBatchWithdrawal(
uint256[] calldata qeuroAmounts,
uint256[] calldata minUsdcOuts,
uint256[] memory usdcReceivedAmounts
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts to withdraw |
minUsdcOuts | uint256[] | Array of minimum USDC amounts expected |
usdcReceivedAmounts | uint256[] | Array to store received USDC amounts |
_processVaultRedemptions
Processes vault redemptions for batch withdrawal
Internal helper to reduce stack depth
OPTIMIZATION: Uses single vault call with total amounts to avoid external calls in loop
Notes:
-
security: Validates vault redemption amounts and minimum outputs
-
validation: Validates all amounts are positive and within limits
-
state-changes: Processes vault redemptions and updates received amounts
-
events: No events emitted - internal helper function
-
errors: Throws validation errors if amounts are invalid
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _processVaultRedemptions(
uint256[] calldata qeuroAmounts,
uint256[] calldata minUsdcOuts,
uint256[] memory usdcReceivedAmounts,
uint256 withdrawalFee_
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts to redeem |
minUsdcOuts | uint256[] | Array of minimum USDC amounts expected |
usdcReceivedAmounts | uint256[] | Array to store received USDC amounts |
withdrawalFee_ | uint256 | Cached withdrawal fee percentage |
_executeBatchTransfers
Executes final transfers and emits events for batch withdrawal
Internal helper to reduce stack depth
Notes:
-
security: Executes final token transfers and emits withdrawal events
-
validation: Validates all amounts are positive before transfer
-
state-changes: Burns QEURO tokens and transfers USDC to user
-
events: Emits Withdrawal event for each withdrawal
-
errors: Throws transfer errors if token operations fail
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _executeBatchTransfers(
uint256[] calldata qeuroAmounts,
uint256[] memory usdcReceivedAmounts,
uint256 currentTime
) internal;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts withdrawn |
usdcReceivedAmounts | uint256[] | Array of USDC amounts received |
currentTime | uint256 | Current timestamp for events |
stake
Stakes QEURO tokens (unified single/batch function)
Handles both single stakes and batch stakes in one function
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Public access
-
oracle: No oracle dependencies
function stake(uint256[] calldata qeuroAmounts) external nonReentrant whenNotPaused;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts to stake (18 decimals) - use [amount] for single |
requestUnstake
Requests to unstake QEURO tokens (starts unstaking cooldown period)
Begins the unstaking process with a cooldown period before tokens can be withdrawn
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Public access
-
oracle: No oracle dependencies
function requestUnstake(uint256 qeuroAmount) external nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | The amount of staked QEURO tokens to unstake (18 decimals) |
unstake
Complete unstaking after cooldown period
This function allows users to complete their unstaking request after the cooldown period has passed.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by nonReentrant modifier
-
access: Public access
-
oracle: No oracle dependencies
function unstake() external nonReentrant whenNotPaused;
claimStakingRewards
Claim staking rewards
This function allows users to claim their pending staking rewards. It calculates and transfers the rewards based on their staked amount.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimStakingRewards() external nonReentrant returns (uint256 rewardAmount);
Returns
| Name | Type | Description |
|---|---|---|
rewardAmount | uint256 | Amount of QEURO rewards claimed (18 decimals) |
batchRewardClaim
Batch claim staking rewards for multiple users (admin function)
This function allows admins to claim rewards for multiple users in one transaction. Useful for protocol-wide reward distributions or automated reward processing.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchRewardClaim(address[] calldata users)
external
nonReentrant
onlyRole(GOVERNANCE_ROLE)
returns (uint256[] memory rewardAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
users | address[] | Array of user addresses to claim rewards for |
Returns
| Name | Type | Description |
|---|---|---|
rewardAmounts | uint256[] | Array of reward amounts claimed for each user (18 decimals) |
distributeYield
Distribute yield to stakers (called by YieldShift contract)
This function is deprecated - yield now goes to stQEURO
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function distributeYield(uint256 yieldAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield to distribute (18 decimals) |
_updatePendingRewards
Update pending rewards for a user
This internal function calculates and updates the pending rewards for a given user based on their staked amount and the current APY. Uses block-based calculations to prevent timestamp manipulation.
Notes:
-
security: Uses block-based calculations to prevent timestamp manipulation
-
validation: Validates user has staked amount > 0
-
state-changes: Updates user.pendingRewards, user.lastStakeTime, userLastRewardBlock
-
events: No events emitted - handled by calling function
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _updatePendingRewards(address user, uint256 currentTime) internal;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to update |
currentTime | uint256 | Current timestamp for reward calculations |
getUserInfo
Get comprehensive user information (consolidated view function)
Returns all user-related data in one call to reduce contract size
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getUserInfo(address user)
external
view
returns (
uint256 qeuroBalance,
uint256 stakedAmount,
uint256 pendingRewards,
uint256 depositHistory,
uint256 lastStakeTime,
uint256 unstakeAmount,
uint256 unstakeRequestTime
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to query |
Returns
| Name | Type | Description |
|---|---|---|
qeuroBalance | uint256 | QEURO balance of the user (18 decimals) |
stakedAmount | uint256 | Current staked amount of the user (18 decimals) |
pendingRewards | uint256 | Total pending rewards of the user (18 decimals) |
depositHistory | uint256 | Total historical deposits of the user (6 decimals) |
lastStakeTime | uint256 | Timestamp of the user's last staking action |
unstakeAmount | uint256 | Amount being unstaked (18 decimals) |
unstakeRequestTime | uint256 | Timestamp when unstaking was requested |
getPoolTotals
Get comprehensive pool totals (consolidated view function)
Returns all pool totals in one call to reduce contract size
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getPoolTotals()
external
view
returns (uint256 totalDeposits, uint256 totalWithdrawals, uint256 totalStakes_, uint256 totalUsers_);
Returns
| Name | Type | Description |
|---|---|---|
totalDeposits | uint256 | Total USDC deposits (6 decimals) |
totalWithdrawals | uint256 | Total QEURO withdrawals (18 decimals) |
totalStakes_ | uint256 | Total QEURO staked (18 decimals) |
totalUsers_ | uint256 | Total number of users |
getUserDepositHistory
Get user deposit history with oracle ratios
Used for detailed analytics and audit trails
Returns complete deposit history with oracle ratios
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getUserDepositHistory(address user) external view returns (UserDepositInfo[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user |
Returns
| Name | Type | Description |
|---|---|---|
<none> | UserDepositInfo[] | Array of UserDepositInfo structs containing deposit history |
getUserWithdrawals
Get user withdrawal history with oracle ratios
Used for detailed analytics and audit trails
Returns complete withdrawal history with oracle ratios
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getUserWithdrawals(address user) external view returns (UserWithdrawalInfo[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user |
Returns
| Name | Type | Description |
|---|---|---|
<none> | UserWithdrawalInfo[] | Array of UserWithdrawalInfo structs containing withdrawal history |
_getOracleRatioScaled
Get current oracle ratio scaled by 1e6 for storage efficiency
Used internally for tracking oracle ratios in deposit/withdrawal records
Scaled to fit in uint32 for gas efficiency
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Internal function
-
oracle: Depends on oracle for current EUR/USD rate
function _getOracleRatioScaled() internal returns (uint32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint32 | Oracle ratio scaled by 1e6 (e.g., 1.08 becomes 1080000) |
getTotalStakes
Get the total USDC equivalent withdrawals across all users
Get the total QEURO staked across all users
Used for analytics and cash flow monitoring
Returns the total amount of QEURO currently staked in the pool
Notes:
-
access: Public access
-
oracle: No oracle dependencies
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTotalStakes() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total withdrawals in USDC equivalent (6 decimals) |
getPoolMetrics
Get various metrics about the user pool
Returns comprehensive pool statistics including user count, averages, and ratios
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPoolMetrics()
external
view
returns (uint256 totalUsers_, uint256 averageDeposit, uint256 stakingRatio, uint256 poolTVL);
Returns
| Name | Type | Description |
|---|---|---|
totalUsers_ | uint256 | Number of unique users |
averageDeposit | uint256 | Average deposit amount per user (6 decimals) |
stakingRatio | uint256 | Ratio of total staked QEURO to total deposits (basis points) |
poolTVL | uint256 | Total value locked in the pool (6 decimals) |
getPoolAnalytics
Get comprehensive pool analytics using QEURO total supply
Uses QEURO total supply for accurate analytics instead of misleading USDC tracking
Notes:
-
security: No external calls except oracle, read-only function
-
validation: Oracle price validation with fallback to zero
-
state-changes: No state changes, view-like function
-
events: No events emitted
-
errors: No custom errors, handles oracle failures gracefully
-
reentrancy: No reentrancy risk, read-only operations
-
access: Public access
-
oracle: Requires fresh oracle price data for USDC equivalent
function getPoolAnalytics()
external
returns (
uint256 currentQeuroSupply,
uint256 usdcEquivalentAtCurrentRate,
uint256 totalUsers_,
uint256 totalStakes_
);
Returns
| Name | Type | Description |
|---|---|---|
currentQeuroSupply | uint256 | Current QEURO total supply (net minted QEURO) |
usdcEquivalentAtCurrentRate | uint256 | Current USDC equivalent of QEURO supply |
totalUsers_ | uint256 | Total number of users |
totalStakes_ | uint256 | Total QEURO staked |
getPoolConfiguration
Get comprehensive pool configuration (consolidated view function)
Returns all pool configuration parameters in one call to reduce contract size
Notes:
-
security: No security implications (view function)
-
validation: No validation required
-
state-changes: No state changes (view function)
-
events: No events (view function)
-
errors: No custom errors
-
reentrancy: No external calls, safe
-
access: Public (anyone can call)
-
oracle: No oracle dependencies
function getPoolConfiguration()
external
view
returns (
uint256 stakingAPY_,
uint256 depositAPY_,
uint256 minStakeAmount_,
uint256 unstakingCooldown_,
uint256 depositFee_,
uint256 withdrawalFee_,
uint256 performanceFee_
);
Returns
| Name | Type | Description |
|---|---|---|
stakingAPY_ | uint256 | Current staking APY in basis points |
depositAPY_ | uint256 | Current deposit APY in basis points |
minStakeAmount_ | uint256 | Current minimum stake amount (18 decimals) |
unstakingCooldown_ | uint256 | Current unstaking cooldown period (seconds) |
depositFee_ | uint256 | Current deposit fee (basis points) |
withdrawalFee_ | uint256 | Current withdrawal fee (basis points) |
performanceFee_ | uint256 | Current performance fee (basis points) |
calculateProjectedRewards
Calculate projected rewards for a given QEURO amount and duration
Calculates the expected rewards for staking a specific amount for a given duration
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateProjectedRewards(uint256 qeuroAmount, uint256 duration) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to calculate rewards for (18 decimals) |
duration | uint256 | Duration in seconds |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Calculated rewards (18 decimals) |
updateStakingParameters
Update the parameters for staking (APY, min stake, cooldown)
This function is restricted to governance roles.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateStakingParameters(uint256 newStakingAPY, uint256 newMinStakeAmount, uint256 newUnstakingCooldown)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newStakingAPY | uint256 | New Staking APY in basis points |
newMinStakeAmount | uint256 | New Minimum stake amount (18 decimals) |
newUnstakingCooldown | uint256 | New unstaking cooldown period (seconds) |
setPoolFees
Set the fees for deposits, withdrawals, and performance
This function is restricted to governance roles.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setPoolFees(uint256 _depositFee, uint256 _withdrawalFee, uint256 _performanceFee)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_depositFee | uint256 | New deposit fee in basis points |
_withdrawalFee | uint256 | New withdrawal fee in basis points |
_performanceFee | uint256 | New performance fee in basis points |
updateYieldShift
Updates the YieldShift contract address
Governance-only setter for phased deployment wiring
Notes:
-
security: Validates address and restricts to governance role
-
access: Restricted to GOVERNANCE_ROLE
function updateYieldShift(address _yieldShift) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_yieldShift | address | New YieldShift contract address |
emergencyUnstake
Emergency unstake for a specific user (restricted to emergency roles)
This function is intended for emergency situations where a user's staked QEURO needs to be forcibly unstaked.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyUnstake(address user) external onlyRole(EMERGENCY_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to unstake |
pause
Pause the user pool (restricted to emergency roles)
This function is used to pause critical operations in case of a protocol-wide emergency or vulnerability.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external onlyRole(EMERGENCY_ROLE);
unpause
Unpause the user pool (restricted to emergency roles)
This function is used to re-enable critical operations after an emergency pause.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external onlyRole(EMERGENCY_ROLE);
isPoolActive
Check if the user pool is currently active (not paused)
Returns the current pause status of the pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isPoolActive() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if the pool is active, false otherwise |
recoverToken
Recover accidentally sent tokens to treasury only
Recovers accidentally sent ERC20 tokens to the treasury address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to recover |
recoverETH
Recover ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
Events
UserDeposit
Emitted when a user deposits USDC and receives QEURO
Indexed parameters allow efficient filtering of events
event UserDeposit(address indexed user, uint256 usdcAmount, uint256 qeuroMinted, uint256 timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who deposited |
usdcAmount | uint256 | Amount of USDC deposited (6 decimals) |
qeuroMinted | uint256 | Amount of QEURO minted (18 decimals) |
timestamp | uint256 | Timestamp of the deposit |
UserWithdrawal
Emitted when a user withdraws QEURO and receives USDC
Indexed parameters allow efficient filtering of events
event UserWithdrawal(address indexed user, uint256 qeuroBurned, uint256 usdcReceived, uint256 timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who withdrew |
qeuroBurned | uint256 | Amount of QEURO burned (18 decimals) |
usdcReceived | uint256 | Amount of USDC received (6 decimals) |
timestamp | uint256 | Timestamp of the withdrawal |
UserDepositTracked
Emitted when a user deposit is tracked with oracle ratio
event UserDepositTracked(
address indexed user,
uint256 usdcAmount,
uint256 qeuroReceived,
uint256 oracleRatio,
uint256 timestamp,
uint256 blockNumber
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who deposited |
usdcAmount | uint256 | USDC amount deposited (6 decimals) |
qeuroReceived | uint256 | QEURO amount received (18 decimals) |
oracleRatio | uint256 | Oracle ratio at time of deposit (scaled by 1e6) |
timestamp | uint256 | Block timestamp when deposit was made |
blockNumber | uint256 | Block number when deposit was made |
UserWithdrawalTracked
Emitted when a user withdrawal is tracked with oracle ratio
event UserWithdrawalTracked(
address indexed user,
uint256 qeuroAmount,
uint256 usdcReceived,
uint256 oracleRatio,
uint256 timestamp,
uint256 blockNumber
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who withdrew |
qeuroAmount | uint256 | QEURO amount withdrawn (18 decimals) |
usdcReceived | uint256 | USDC amount received (6 decimals) |
oracleRatio | uint256 | Oracle ratio at time of withdrawal (scaled by 1e6) |
timestamp | uint256 | Block timestamp when withdrawal was made |
blockNumber | uint256 | Block number when withdrawal was made |
QEUROStaked
Emitted when a user stakes QEURO
Indexed parameters allow efficient filtering of events
event QEUROStaked(address indexed user, uint256 qeuroAmount, uint256 timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who staked |
qeuroAmount | uint256 | Amount of QEURO staked (18 decimals) |
timestamp | uint256 | Timestamp of the staking action |
QEUROUnstaked
Emitted when a user unstakes QEURO
Indexed parameters allow efficient filtering of events
event QEUROUnstaked(address indexed user, uint256 qeuroAmount, uint256 timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who unstaked |
qeuroAmount | uint256 | Amount of QEURO unstaked (18 decimals) |
timestamp | uint256 | Timestamp of the unstaking action |
StakingRewardsClaimed
Emitted when staking rewards are claimed by a user
Indexed parameters allow efficient filtering of events
event StakingRewardsClaimed(address indexed user, uint256 rewardAmount, uint256 timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who claimed rewards |
rewardAmount | uint256 | Amount of QEURO rewards claimed (18 decimals) |
timestamp | uint256 | Timestamp of the reward claim |
YieldDistributed
Emitted when yield is distributed to stakers
OPTIMIZED: Indexed timestamp for efficient time-based filtering
event YieldDistributed(uint256 totalYield, uint256 yieldPerShare, uint256 indexed timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
totalYield | uint256 | Total amount of yield distributed (18 decimals) |
yieldPerShare | uint256 | Amount of yield per staked QEURO share (18 decimals) |
timestamp | uint256 | Timestamp of the yield distribution |
PoolParameterUpdated
Emitted when pool parameters are updated
OPTIMIZED: Indexed parameter name for efficient filtering by parameter type
event PoolParameterUpdated(string indexed parameter, uint256 oldValue, uint256 newValue);
Parameters
| Name | Type | Description |
|---|---|---|
parameter | string | Name of the parameter updated |
oldValue | uint256 | Original value of the parameter |
newValue | uint256 | New value of the parameter |
ETHRecovered
Emitted when ETH is recovered to the treasury
event ETHRecovered(address indexed to, uint256 indexed amount);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Recipient address |
amount | uint256 | Amount of ETH recovered |
Structs
UserInfo
User information data structure
Stores all information about a user's deposits, stakes, and rewards
Used for user management and reward calculations
OPTIMIZED: Timestamps and amounts packed for gas efficiency
struct UserInfo {
uint128 qeuroBalance; // QEURO balance from deposits (18 decimals, max ~340B)
uint128 stakedAmount; // QEURO amount currently staked (18 decimals, max ~340B)
uint128 pendingRewards; // Pending staking rewards in QEURO (18 decimals, max ~340B)
uint128 unstakeAmount; // Amount being unstaked (18 decimals, max ~340B)
uint96 depositHistory; // Total historical deposits in USDC (6 decimals, max ~79B USDC)
uint64 lastStakeTime; // Timestamp of last staking action (until year 2554)
uint64 unstakeRequestTime; // Timestamp when unstaking was requested (until year 2554)
}
UserDepositInfo
User deposit information with oracle ratio tracking
Stores individual deposit records with oracle ratios for detailed analytics
Used for audit trails and historical analysis
struct UserDepositInfo {
uint128 usdcAmount; // USDC amount deposited (6 decimals, max ~340B USDC)
uint128 qeuroReceived; // QEURO amount received (18 decimals, max ~340B QEURO)
uint64 timestamp; // Block timestamp when deposit was made (until year 2554)
uint32 oracleRatio; // Oracle ratio at time of deposit (scaled by 1e6, max ~4.2B)
uint32 blockNumber; // Block number when deposit was made (until year 2106)
}
UserWithdrawalInfo
User withdrawal information with oracle ratio tracking
Stores individual withdrawal records with oracle ratios for detailed analytics
Used for audit trails and historical analysis
struct UserWithdrawalInfo {
uint128 qeuroAmount; // QEURO amount withdrawn (18 decimals, max ~340B QEURO)
uint128 usdcReceived; // USDC amount received (6 decimals, max ~340B USDC)
uint64 timestamp; // Block timestamp when withdrawal was made (until year 2554)
uint32 oracleRatio; // Oracle ratio at time of withdrawal (scaled by 1e6, max ~4.2B)
uint32 blockNumber; // Block number when withdrawal was made (until year 2106)
}
stQEUROToken
Inherits: Initializable, ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, SecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Yield-bearing wrapper for QEURO tokens (yield accrual mechanism)
Main characteristics:
- Yield-bearing wrapper token for QEURO
- Exchange rate increases over time as yield accrues
- Similar to stETH (Lido's staked ETH token)
- Automatic yield distribution to all stQEURO holders
- Fee structure for protocol sustainability
- Emergency pause mechanism for crisis situations
- Upgradeable via UUPS pattern
Staking mechanics:
- Users stake QEURO to receive stQEURO
- Exchange rate starts at 1:1 and increases over time
- Yield is distributed proportionally to all stQEURO holders
- Users can unstake at any time to receive QEURO + accrued yield
- No lock-up period or cooldown requirements
Yield distribution:
- Yield is distributed from protocol fees and yield shift mechanisms
- Exchange rate increases as yield accrues
- All stQEURO holders benefit from yield automatically
- Yield fees charged for protocol sustainability
- Real-time yield tracking and distribution
Exchange rate mechanism:
- Exchange rate = (totalUnderlying + totalYieldEarned) / totalSupply
- Increases over time as yield is earned
- Updated periodically or when yield is distributed
- Minimum yield threshold prevents frequent updates
- Maximum update frequency prevents excessive gas costs
Fee structure:
- Yield fees on distributed yield
- Treasury receives fees for protocol sustainability
- Dynamic fee adjustment based on market conditions
- Transparent fee structure for users
Security features:
- Role-based access control for all critical operations
- Reentrancy protection for all external calls
- Emergency pause mechanism for crisis situations
- Upgradeable architecture for future improvements
- Secure yield distribution mechanisms
- Exchange rate validation
Integration points:
- QEURO token for staking and unstaking
- USDC for yield payments
- Yield shift mechanism for yield management
- Treasury for fee collection
- Vault math library for calculations
Note: security-contact: team@quantillon.money
State Variables
GOVERNANCE_ROLE
Role for governance operations (parameter updates, emergency actions)
keccak256 hash avoids role collisions with other contracts
Should be assigned to governance multisig or DAO
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
YIELD_MANAGER_ROLE
Role for yield management operations (distribution, updates)
keccak256 hash avoids role collisions with other contracts
Should be assigned to yield management system or governance
bytes32 public constant YIELD_MANAGER_ROLE = keccak256("YIELD_MANAGER_ROLE")
EMERGENCY_ROLE
Role for emergency operations (pause, emergency actions)
keccak256 hash avoids role collisions with other contracts
Should be assigned to emergency multisig
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
qeuro
Role for performing contract upgrades via UUPS pattern
QEURO token contract for staking and unstaking
Used for all QEURO staking and unstaking operations
Should be the official QEURO token contract
IQEUROToken public qeuro
yieldShift
YieldShift contract for yield distribution
Handles yield distribution and management
Used for yield calculations and distributions
IYieldShift public yieldShift
usdc
USDC token for yield payments
Used for yield distributions to stQEURO holders
Should be the official USDC contract on the target network
IERC20 public usdc
treasury
Treasury address for fee collection
Receives yield fees for protocol sustainability
Should be a secure multisig or DAO treasury
address public treasury
TIME_PROVIDER
TimeProvider contract for centralized time management
Used to replace direct block.timestamp usage for testability and consistency
TimeProvider public immutable TIME_PROVIDER
exchangeRate
Exchange rate between QEURO and stQEURO (18 decimals)
Increases over time as yield accrues (like stETH)
Formula: (totalUnderlying + totalYieldEarned) / totalSupply
uint256 public exchangeRate
lastUpdateTime
Timestamp of last exchange rate update
Used to track when exchange rate was last updated
Used for yield calculation intervals
uint256 public lastUpdateTime
totalUnderlying
Total QEURO underlying the stQEURO supply
Sum of all QEURO staked by users
Used for exchange rate calculations
uint256 public totalUnderlying
totalYieldEarned
Total yield earned by stQEURO holders
Sum of all yield distributed to stQEURO holders
Used for exchange rate calculations and analytics
uint256 public totalYieldEarned
yieldFee
Fee charged on yield distributions (in basis points)
Example: 200 = 2% yield fee
Revenue source for the protocol
uint256 public yieldFee
minYieldThreshold
Minimum yield amount to trigger exchange rate update
Prevents frequent updates for small yield amounts
Reduces gas costs and improves efficiency
uint256 public minYieldThreshold
maxUpdateFrequency
Maximum time between exchange rate updates (in seconds)
Ensures regular updates even with low yield
Example: 1 day = 86400 seconds
uint256 public maxUpdateFrequency
VIRTUAL_SHARES
Virtual shares to prevent exchange rate manipulation
Prevents donation attacks by maintaining minimum share value
uint256 private constant VIRTUAL_SHARES = 1e8
VIRTUAL_ASSETS
Virtual assets to prevent exchange rate manipulation
Prevents donation attacks by maintaining minimum asset value
uint256 private constant VIRTUAL_ASSETS = 1e8
MAX_BATCH_SIZE
Maximum batch size for staking operations to prevent DoS
Prevents out-of-gas attacks through large arrays
uint256 public constant MAX_BATCH_SIZE = 100
Functions
flashLoanProtection
Modifier to protect against flash loan attacks
Checks that the contract's total underlying QEURO doesn't decrease during execution
This prevents flash loans that would drain QEURO from the contract
modifier flashLoanProtection() ;
constructor
Constructor for stQEURO token implementation
Initializes the time provider and disables initialization on implementation
Notes:
-
security: Disables initialization on implementation for security
-
validation: Validates time provider is not zero address
-
state-changes: Sets TIME_PROVIDER and disables initializers
-
events: No events emitted
-
errors: Throws ZeroAddress if time provider is zero
-
reentrancy: Not protected - constructor only
-
access: Public constructor
-
oracle: No oracle dependencies
-
oz-upgrades-unsafe-allow: constructor
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | Address of the time provider contract |
initialize
Initialize the stQEURO token contract
Sets up the contract with all required addresses and roles
Notes:
-
security: Validates all addresses are not zero
-
validation: Validates all input addresses
-
state-changes: Initializes ERC20, AccessControl, and Pausable
-
events: Emits initialization events
-
errors: Throws if any address is zero
-
reentrancy: Protected by initializer modifier
-
access: Public initializer
-
oracle: No oracle dependencies
function initialize(
address admin,
address _qeuro,
address _yieldShift,
address _usdc,
address _treasury,
address _timelock
) public initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address of the admin role |
_qeuro | address | Address of the QEURO token contract |
_yieldShift | address | Address of the YieldShift contract |
_usdc | address | Address of the USDC token contract |
_treasury | address | Address of the treasury |
_timelock | address | Address of the timelock contract |
stake
Stake QEURO to receive stQEURO
Converts QEURO to stQEURO at current exchange rate
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function stake(uint256 qeuroAmount)
external
nonReentrant
whenNotPaused
flashLoanProtection
returns (uint256 stQEUROAmount);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to stake |
Returns
| Name | Type | Description |
|---|---|---|
stQEUROAmount | uint256 | Amount of stQEURO received |
unstake
Unstake QEURO by burning stQEURO
Burns stQEURO tokens and returns QEURO at current exchange rate
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unstake(uint256 stQEUROAmount) external nonReentrant whenNotPaused returns (uint256 qeuroAmount);
Parameters
| Name | Type | Description |
|---|---|---|
stQEUROAmount | uint256 | Amount of stQEURO to burn |
Returns
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO received |
batchStake
Batch stake QEURO to receive stQEURO for multiple amounts
Processes multiple staking operations in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchStake(uint256[] calldata qeuroAmounts)
external
nonReentrant
whenNotPaused
returns (uint256[] memory stQEUROAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts to stake |
Returns
| Name | Type | Description |
|---|---|---|
stQEUROAmounts | uint256[] | Array of stQEURO amounts received |
batchUnstake
Batch unstake QEURO by burning stQEURO for multiple amounts
Processes multiple unstaking operations in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchUnstake(uint256[] calldata stQEUROAmounts)
external
nonReentrant
whenNotPaused
returns (uint256[] memory qeuroAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
stQEUROAmounts | uint256[] | Array of stQEURO amounts to burn |
Returns
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts received |
batchTransfer
Batch transfer stQEURO tokens to multiple addresses
Transfers stQEURO tokens to multiple recipients in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts)
external
whenNotPaused
returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of recipient addresses |
amounts | uint256[] | Array of amounts to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool Always returns true if successful |
distributeYield
Distribute yield to stQEURO holders (increases exchange rate)
Distributes USDC yield to stQEURO holders by increasing the exchange rate
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function distributeYield(uint256 yieldAmount) external onlyRole(YIELD_MANAGER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield in USDC |
claimYield
Claim accumulated yield for a user (in USDC)
In yield accrual model, yield is claimed by unstaking - kept for compatibility
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimYield() public returns (uint256 yieldAmount);
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield claimed (always 0 in this model) |
getPendingYield
Get pending yield for a user (in USDC)
In yield accrual model, yield is distributed via exchange rate increases
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPendingYield(address user) public view returns (uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Pending yield amount |
getExchangeRate
Get current exchange rate between QEURO and stQEURO
Returns the current exchange rate calculated with yield accrual
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getExchangeRate() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Current exchange rate (18 decimals) |
getTVL
Get total value locked in stQEURO
Returns the total amount of QEURO underlying all stQEURO tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTVL() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total value locked in QEURO (18 decimals) |
getQEUROEquivalent
Get user's QEURO equivalent balance
Calculates the QEURO equivalent of a user's stQEURO balance
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getQEUROEquivalent(address user) external view returns (uint256 qeuroEquivalent);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
qeuroEquivalent | uint256 | QEURO equivalent of stQEURO balance |
getStakingStats
Get staking statistics
Returns comprehensive staking statistics including supply, TVL, and yield
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getStakingStats()
external
view
returns (
uint256 totalStQEUROSupply,
uint256 totalQEUROUnderlying,
uint256 currentExchangeRate,
uint256 totalYieldEarned_,
uint256 apy
);
Returns
| Name | Type | Description |
|---|---|---|
totalStQEUROSupply | uint256 | Total supply of stQEURO tokens |
totalQEUROUnderlying | uint256 | Total QEURO underlying all stQEURO |
currentExchangeRate | uint256 | Current exchange rate between QEURO and stQEURO |
totalYieldEarned_ | uint256 | Total yield earned by all stakers |
apy | uint256 | Annual percentage yield (calculated off-chain) |
_updateExchangeRate
Update exchange rate based on time elapsed and yield accrual
Internal function to update exchange rate when conditions are met
Notes:
-
security: Calculates new rate with bounds checking to prevent manipulation
-
validation: No input validation required
-
state-changes: Updates exchangeRate and lastUpdateTime if rate changes
-
events: Emits ExchangeRateUpdated if rate changes
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _updateExchangeRate() internal;
_calculateCurrentExchangeRate
Calculate current exchange rate including accrued yield
Returns the stored exchange rate which is updated via distributeYield()
Notes:
-
security: Uses minimum supply threshold to prevent manipulation
-
validation: No input validation required
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _calculateCurrentExchangeRate() internal view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current exchange rate (18 decimals) including pending yield |
updateYieldParameters
Update yield parameters
Updates yield fee, minimum threshold, and maximum update frequency
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateYieldParameters(uint256 _yieldFee, uint256 _minYieldThreshold, uint256 _maxUpdateFrequency)
external
onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_yieldFee | uint256 | New yield fee in basis points |
_minYieldThreshold | uint256 | New minimum yield threshold in USDC |
_maxUpdateFrequency | uint256 | New maximum update frequency in seconds |
updateTreasury
Update treasury address
Updates the treasury address for token recovery operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateTreasury(address _treasury) external onlyRole(GOVERNANCE_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
decimals
Returns the number of decimals used by the token
Always returns 18 to match QEURO token standard
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function decimals() public pure override returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | The number of decimals (18) |
pause
Pauses all token transfers and minting/burning operations
Can only be called by addresses with EMERGENCY_ROLE during emergencies
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external onlyRole(EMERGENCY_ROLE);
unpause
Unpauses all token transfers and minting/burning operations
Can only be called by addresses with EMERGENCY_ROLE to resume normal operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external onlyRole(EMERGENCY_ROLE);
emergencyWithdraw
Emergency withdrawal of QEURO (only in emergency)
Emergency function to withdraw QEURO for a specific user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyWithdraw(address user) external onlyRole(EMERGENCY_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to withdraw for |
recoverToken
Recover accidentally sent tokens to treasury only
Recovers accidentally sent ERC20 tokens to the treasury address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to recover |
recoverETH
Recover ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
getVirtualProtectionStatus
Returns the current virtual protection status
Useful for monitoring and debugging virtual protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getVirtualProtectionStatus()
external
view
returns (uint256 virtualShares, uint256 virtualAssets, uint256 effectiveSupply, uint256 effectiveAssets);
Returns
| Name | Type | Description |
|---|---|---|
virtualShares | uint256 | Current virtual shares amount |
virtualAssets | uint256 | Current virtual assets amount |
effectiveSupply | uint256 | Effective supply including virtual shares |
effectiveAssets | uint256 | Effective assets including virtual assets |
Events
QEUROStaked
Emitted when QEURO is staked to receive stQEURO
Indexed parameters allow efficient filtering of events
event QEUROStaked(address indexed user, uint256 qeuroAmount, uint256 stQEUROAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who staked |
qeuroAmount | uint256 | Amount of QEURO staked (18 decimals) |
stQEUROAmount | uint256 | Amount of stQEURO received (18 decimals) |
QEUROUnstaked
Emitted when stQEURO is unstaked to receive QEURO
Indexed parameters allow efficient filtering of events
event QEUROUnstaked(address indexed user, uint256 stQEUROAmount, uint256 qeuroAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who unstaked |
stQEUROAmount | uint256 | Amount of stQEURO burned (18 decimals) |
qeuroAmount | uint256 | Amount of QEURO received (18 decimals) |
ExchangeRateUpdated
Emitted when exchange rate is updated
Used to track exchange rate changes over time
event ExchangeRateUpdated(uint256 oldRate, uint256 newRate, uint256 timestamp);
Parameters
| Name | Type | Description |
|---|---|---|
oldRate | uint256 | Previous exchange rate (18 decimals) |
newRate | uint256 | New exchange rate (18 decimals) |
timestamp | uint256 | Timestamp of the update |
YieldDistributed
Emitted when yield is distributed to stQEURO holders
Used to track yield distributions and their impact
OPTIMIZED: Indexed exchange rate for efficient filtering
event YieldDistributed(uint256 yieldAmount, uint256 indexed newExchangeRate);
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield distributed (18 decimals) |
newExchangeRate | uint256 | New exchange rate after distribution (18 decimals) |
YieldClaimed
Emitted when a user claims yield
Indexed parameters allow efficient filtering of events
event YieldClaimed(address indexed user, uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user who claimed yield |
yieldAmount | uint256 | Amount of yield claimed (18 decimals) |
YieldParametersUpdated
Emitted when yield parameters are updated
Used to track parameter changes by governance
OPTIMIZED: Indexed parameter type for efficient filtering
event YieldParametersUpdated(
string indexed parameterType, uint256 yieldFee, uint256 minYieldThreshold, uint256 maxUpdateFrequency
);
Parameters
| Name | Type | Description |
|---|---|---|
parameterType | string | |
yieldFee | uint256 | New yield fee in basis points |
minYieldThreshold | uint256 | New minimum yield threshold |
maxUpdateFrequency | uint256 | New maximum update frequency |
ETHRecovered
Emitted when ETH is recovered to the treasury
event ETHRecovered(address indexed to, uint256 indexed amount);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address to which ETH was recovered |
amount | uint256 | Amount of ETH recovered |
Contents
- IAaveVault
- IChainlinkOracle
- IHedgerPool
- IQEUROToken
- IQTIToken
- IQuantillonVault
- ISecureUpgradeable
- ITimelockUpgradeable
- IUserPool
- IYieldShift
- IstQEURO
IAaveVault
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the AaveVault (Aave V3 USDC yield vault)
Mirrors the external/public API of src/core/vaults/AaveVault.sol
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the Aave vault
Initializes the AaveVault contract with required addresses
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(
address admin,
address _usdc,
address _aaveProvider,
address _rewardsController,
address _yieldShift,
address _timelock,
address _treasury
) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address |
_usdc | address | USDC token address |
_aaveProvider | address | Aave PoolAddressesProvider |
_rewardsController | address | Aave RewardsController address |
_yieldShift | address | YieldShift contract address |
_timelock | address | Timelock contract address |
_treasury | address | Treasury address |
deployToAave
Deploy USDC to Aave V3 pool to earn yield
Deploys USDC to Aave V3 pool to earn yield
Notes:
-
security: Validates oracle price freshness, enforces exposure limits
-
validation: Validates amount > 0, checks max exposure limits
-
state-changes: Updates principalDeposited, transfers USDC, receives aUSDC
-
events: Emits DeployedToAave with operation details
-
errors: Throws WouldExceedLimit if exceeds maxAaveExposure
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to VAULT_MANAGER_ROLE
-
oracle: Requires fresh EUR/USD price for health validation
function deployToAave(uint256 amount) external returns (uint256 aTokensReceived);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | USDC amount to supply (6 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
aTokensReceived | uint256 | Amount of aUSDC received (6 decimals) |
withdrawFromAave
Withdraw USDC from Aave V3 pool
Withdraws USDC from Aave V3 pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function withdrawFromAave(uint256 amount) external returns (uint256 usdcWithdrawn);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of aUSDC to withdraw (use type(uint256).max for all) |
Returns
| Name | Type | Description |
|---|---|---|
usdcWithdrawn | uint256 | Amount of USDC actually withdrawn |
claimAaveRewards
Claim Aave rewards (if any)
Claims Aave rewards if any are available
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimAaveRewards() external returns (uint256 rewardsClaimed);
Returns
| Name | Type | Description |
|---|---|---|
rewardsClaimed | uint256 | Claimed reward amount |
harvestAaveYield
Harvest Aave yield and distribute via YieldShift
This function calls YieldShift.harvestAndDistributeAaveYield() to handle distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function harvestAaveYield() external returns (uint256 yieldHarvested);
Returns
| Name | Type | Description |
|---|---|---|
yieldHarvested | uint256 | Amount harvested |
getAvailableYield
Calculate available yield for harvest
Calculates the amount of yield available for harvest
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAvailableYield() external view returns (uint256 available);
Returns
| Name | Type | Description |
|---|---|---|
available | uint256 | Amount of yield available |
getYieldDistribution
Get yield distribution breakdown for current state
Returns the breakdown of yield distribution for current state
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldDistribution()
external
view
returns (uint256 protocolYield, uint256 userYield, uint256 hedgerYield);
Returns
| Name | Type | Description |
|---|---|---|
protocolYield | uint256 | Protocol fee portion |
userYield | uint256 | Allocation to users |
hedgerYield | uint256 | Allocation to hedgers |
getAaveBalance
Current aUSDC balance of the vault
Returns the current aUSDC balance of the vault
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveBalance() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The current aUSDC balance |
getAccruedInterest
Accrued interest (same as available yield)
Returns the accrued interest (same as available yield)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAccruedInterest() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The accrued interest amount |
getAaveAPY
Current Aave APY in basis points
Returns the current Aave APY in basis points
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveAPY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Current APY in basis points |
getAavePositionDetails
Aave position details snapshot
Returns a snapshot of Aave position details
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAavePositionDetails()
external
view
returns (uint256 principalDeposited_, uint256 currentBalance, uint256 aTokenBalance, uint256 lastUpdateTime);
Returns
| Name | Type | Description |
|---|---|---|
principalDeposited_ | uint256 | Principal USDC supplied |
currentBalance | uint256 | Current aUSDC balance (1:1 underlying + interest) |
aTokenBalance | uint256 | Alias for aUSDC balance |
lastUpdateTime | uint256 | Timestamp of last harvest |
getAaveMarketData
Aave market data snapshot
Returns Aave market data snapshot
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveMarketData()
external
view
returns (uint256 supplyRate, uint256 utilizationRate, uint256 totalSupply, uint256 availableLiquidity);
Returns
| Name | Type | Description |
|---|---|---|
supplyRate | uint256 | Current supply rate (bps) |
utilizationRate | uint256 | Utilization rate (bps) |
totalSupply | uint256 | USDC total supply |
availableLiquidity | uint256 | Available USDC liquidity in Aave pool |
checkAaveHealth
Basic Aave pool health and pause state
Returns basic Aave pool health and pause state
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function checkAaveHealth() external view returns (bool isHealthy, bool pauseStatus, uint256 lastUpdate);
Returns
| Name | Type | Description |
|---|---|---|
isHealthy | bool | True if pool considered healthy |
pauseStatus | bool | Whether vault is paused |
lastUpdate | uint256 | Last harvest time |
autoRebalance
Attempt auto-rebalancing allocation
Automatically rebalances allocation based on current market conditions and yield opportunities
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function autoRebalance() external returns (bool rebalanced, uint256 newAllocation);
Returns
| Name | Type | Description |
|---|---|---|
rebalanced | bool | Whether a rebalance decision was made |
newAllocation | uint256 | New target allocation (bps) |
calculateOptimalAllocation
Compute optimal allocation and expected yield
Calculates the optimal allocation percentage and expected yield based on current market conditions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateOptimalAllocation() external view returns (uint256 optimalAllocation, uint256 expectedYield);
Returns
| Name | Type | Description |
|---|---|---|
optimalAllocation | uint256 | Target allocation (bps) |
expectedYield | uint256 | Expected yield proxy |
setMaxAaveExposure
Update max exposure to Aave
Sets the maximum USDC exposure limit for Aave protocol interactions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setMaxAaveExposure(uint256 _maxExposure) external;
Parameters
| Name | Type | Description |
|---|---|---|
_maxExposure | uint256 | New max USDC exposure |
emergencyWithdrawFromAave
Emergency: withdraw all from Aave
Emergency function to withdraw all funds from Aave protocol in case of emergency
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyWithdrawFromAave() external returns (uint256 amountWithdrawn);
Returns
| Name | Type | Description |
|---|---|---|
amountWithdrawn | uint256 | Amount withdrawn |
getRiskMetrics
Risk metrics snapshot
Returns current risk metrics including exposure ratio and risk scores
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRiskMetrics()
external
view
returns (uint256 exposureRatio, uint256 concentrationRisk, uint256 liquidityRisk);
Returns
| Name | Type | Description |
|---|---|---|
exposureRatio | uint256 | % of assets in Aave (bps) |
concentrationRisk | uint256 | Heuristic risk score (1-3) |
liquidityRisk | uint256 | Heuristic risk score (1-3) |
updateAaveParameters
Update vault parameters
Updates key vault parameters including harvest threshold, yield fee, and rebalance threshold
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateAaveParameters(uint256 newHarvestThreshold, uint256 newYieldFee, uint256 newRebalanceThreshold)
external;
Parameters
| Name | Type | Description |
|---|---|---|
newHarvestThreshold | uint256 | Min yield to harvest |
newYieldFee | uint256 | Protocol fee on yield (bps) |
newRebalanceThreshold | uint256 | Rebalance threshold (bps) |
getAaveConfig
Aave config snapshot
Returns current Aave configuration including pool address, token address, and key parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getAaveConfig()
external
view
returns (address aavePool_, address aUSDC_, uint256 harvestThreshold_, uint256 yieldFee_, uint256 maxExposure_);
Returns
| Name | Type | Description |
|---|---|---|
aavePool_ | address | Aave Pool address |
aUSDC_ | address | aUSDC token address |
harvestThreshold_ | uint256 | Current harvest threshold |
yieldFee_ | uint256 | Current yield fee (bps) |
maxExposure_ | uint256 | Max Aave exposure |
toggleEmergencyMode
Toggle emergency mode
Enables or disables emergency mode with a reason for the action
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function toggleEmergencyMode(bool enabled, string calldata reason) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | New emergency flag |
reason | string | Reason string |
pause
Pause the vault
Pauses all vault operations for emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpause the vault
Resumes vault operations after being paused
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
recoverToken
Recover ERC20 tokens sent by mistake
Allows recovery of ERC20 tokens accidentally sent to the contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address |
amount | uint256 | Amount to transfer |
recoverETH
Recover ETH sent by mistake
Allows recovery of ETH accidentally sent to the contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
hasRole
Check if an account has a specific role
Returns true if the account has the specified role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if the account has the role, false otherwise |
getRoleAdmin
Get the admin role for a specific role
Returns the admin role that controls the specified role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to get the admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The admin role |
grantRole
Grant a role to an account
Grants the specified role to the account
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revoke a role from an account
Revokes the specified role from the account
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounce a role
Renounces the specified role from the caller
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | Confirmation that the caller is renouncing the role |
paused
Check if the contract is paused
Returns true if the contract is paused, false otherwise
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if paused, false otherwise |
upgradeTo
Upgrade the contract implementation
Upgrades the contract to a new implementation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
upgradeToAndCall
Upgrade the contract implementation and call a function
Upgrades the contract to a new implementation and calls a function
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
data | bytes | Data to call on the new implementation |
GOVERNANCE_ROLE
Get the governance role identifier
Returns the governance role identifier
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function GOVERNANCE_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The governance role identifier |
VAULT_MANAGER_ROLE
Get the vault manager role identifier
Returns the vault manager role identifier
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function VAULT_MANAGER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The vault manager role identifier |
EMERGENCY_ROLE
Get the emergency role identifier
Returns the emergency role identifier
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function EMERGENCY_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The emergency role identifier |
UPGRADER_ROLE
Get the upgrader role identifier
Returns the upgrader role identifier
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The upgrader role identifier |
usdc
Get the USDC token address
Returns the address of the USDC token contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function usdc() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address The USDC token address |
aUSDC
Get the aUSDC token address
Returns the address of the aUSDC token contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function aUSDC() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address The aUSDC token address |
aavePool
Get the Aave pool address
Returns the address of the Aave pool contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function aavePool() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address The Aave pool address |
aaveProvider
Get the Aave provider address
Returns the address of the Aave provider contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function aaveProvider() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address The Aave provider address |
rewardsController
Get the rewards controller address
Returns the address of the rewards controller contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function rewardsController() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address The rewards controller address |
yieldShift
Get the yield shift address
Returns the address of the yield shift contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function yieldShift() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address The yield shift address |
maxAaveExposure
Get the maximum Aave exposure
Returns the maximum amount that can be deposited to Aave
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function maxAaveExposure() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The maximum Aave exposure |
harvestThreshold
Get the harvest threshold
Returns the minimum amount required to trigger a harvest
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function harvestThreshold() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The harvest threshold |
yieldFee
Get the yield fee
Returns the fee percentage charged on harvested yield
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function yieldFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The yield fee in basis points |
rebalanceThreshold
Get the rebalance threshold
Returns the threshold for triggering rebalancing
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function rebalanceThreshold() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The rebalance threshold |
principalDeposited
Get the principal deposited amount
Returns the total amount of principal deposited to Aave
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function principalDeposited() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The principal deposited amount |
lastHarvestTime
Get the last harvest time
Returns the timestamp of the last harvest
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function lastHarvestTime() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The last harvest time |
totalYieldHarvested
Get the total yield harvested
Returns the total amount of yield harvested from Aave
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalYieldHarvested() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The total yield harvested |
totalFeesCollected
Get the total fees collected
Returns the total amount of fees collected
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalFeesCollected() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The total fees collected |
utilizationLimit
Get the utilization limit
Returns the maximum utilization rate allowed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function utilizationLimit() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The utilization limit |
emergencyExitThreshold
Get the emergency exit threshold
Returns the threshold for triggering emergency exit
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyExitThreshold() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 The emergency exit threshold |
emergencyMode
Get the emergency mode status
Returns true if the contract is in emergency mode
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyMode() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if in emergency mode, false otherwise |
IChainlinkOracle
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the Quantillon Chainlink-based oracle
Exposes read methods for prices and health, plus admin/emergency controls
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the oracle with admin and feed addresses
Sets up the oracle with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(address admin, address _eurUsdPriceFeed, address _usdcUsdPriceFeed, address _treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address that receives admin and manager roles |
_eurUsdPriceFeed | address | Chainlink EUR/USD feed address |
_usdcUsdPriceFeed | address | Chainlink USDC/USD feed address |
_treasury | address | Treasury address |
getEurUsdPrice
Gets the current EUR/USD price with validation
Retrieves and validates EUR/USD price from Chainlink feed with freshness checks
Notes:
-
security: Validates timestamp freshness, circuit breaker status, price bounds
-
validation: Checks price > 0, timestamp < 1 hour old, within min/max bounds
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - returns fallback price if invalid
-
reentrancy: Not applicable - view function
-
access: Public - no access restrictions
-
oracle: Requires fresh Chainlink EUR/USD price feed data
function getEurUsdPrice() external returns (uint256 price, bool isValid);
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | EUR/USD price in 18 decimals |
isValid | bool | True if fresh and within acceptable bounds |
getUsdcUsdPrice
Gets the current USDC/USD price with validation
Retrieves and validates USDC/USD price from Chainlink feed with tolerance checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUsdcUsdPrice() external view returns (uint256 price, bool isValid);
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | USDC/USD price in 18 decimals (should be ~1e18) |
isValid | bool | True if fresh and within tolerance |
getOracleHealth
Returns overall oracle health signals
Checks the health status of both price feeds and overall oracle state
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getOracleHealth() external returns (bool isHealthy, bool eurUsdFresh, bool usdcUsdFresh);
Returns
| Name | Type | Description |
|---|---|---|
isHealthy | bool | True if both feeds are fresh, circuit breaker is off, and not paused |
eurUsdFresh | bool | True if EUR/USD feed is fresh |
usdcUsdFresh | bool | True if USDC/USD feed is fresh |
getEurUsdDetails
Detailed information about the EUR/USD price
Provides comprehensive EUR/USD price information including validation status
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getEurUsdDetails()
external
returns (uint256 currentPrice, uint256 lastValidPrice, uint256 lastUpdate, bool isStale, bool withinBounds);
Returns
| Name | Type | Description |
|---|---|---|
currentPrice | uint256 | Current price (may be fallback) |
lastValidPrice | uint256 | Last validated price stored |
lastUpdate | uint256 | Timestamp of last successful update |
isStale | bool | True if the feed data is stale |
withinBounds | bool | True if within configured min/max bounds |
getOracleConfig
Current configuration and circuit breaker state
Returns current oracle configuration parameters and circuit breaker status
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getOracleConfig()
external
view
returns (
uint256 minPrice,
uint256 maxPrice,
uint256 maxStaleness,
uint256 usdcTolerance,
bool circuitBreakerActive
);
Returns
| Name | Type | Description |
|---|---|---|
minPrice | uint256 | Minimum accepted EUR/USD price |
maxPrice | uint256 | Maximum accepted EUR/USD price |
maxStaleness | uint256 | Maximum allowed staleness in seconds |
usdcTolerance | uint256 | USDC tolerance in basis points |
circuitBreakerActive | bool | True if circuit breaker is triggered |
getPriceFeedAddresses
Addresses and decimals of the underlying feeds
Returns the addresses and decimal precision of both Chainlink price feeds
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPriceFeedAddresses()
external
view
returns (address eurUsdFeedAddress, address usdcUsdFeedAddress, uint8 eurUsdDecimals, uint8 usdcUsdDecimals);
Returns
| Name | Type | Description |
|---|---|---|
eurUsdFeedAddress | address | EUR/USD feed address |
usdcUsdFeedAddress | address | USDC/USD feed address |
eurUsdDecimals | uint8 | EUR/USD feed decimals |
usdcUsdDecimals | uint8 | USDC/USD feed decimals |
checkPriceFeedConnectivity
Connectivity check for both feeds
Tests connectivity to both Chainlink price feeds and returns latest round information
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function checkPriceFeedConnectivity()
external
view
returns (bool eurUsdConnected, bool usdcUsdConnected, uint80 eurUsdLatestRound, uint80 usdcUsdLatestRound);
Returns
| Name | Type | Description |
|---|---|---|
eurUsdConnected | bool | True if EUR/USD feed responds |
usdcUsdConnected | bool | True if USDC/USD feed responds |
eurUsdLatestRound | uint80 | Latest round ID for EUR/USD |
usdcUsdLatestRound | uint80 | Latest round ID for USDC/USD |
updatePriceBounds
Updates EUR/USD min and max acceptable prices
Updates the price bounds for EUR/USD validation with security checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updatePriceBounds(uint256 _minPrice, uint256 _maxPrice) external;
Parameters
| Name | Type | Description |
|---|---|---|
_minPrice | uint256 | New minimum price (18 decimals) |
_maxPrice | uint256 | New maximum price (18 decimals) |
updateUsdcTolerance
Updates the allowed USDC deviation from $1.00 in basis points
Updates the USDC price tolerance for validation with security checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateUsdcTolerance(uint256 newToleranceBps) external;
Parameters
| Name | Type | Description |
|---|---|---|
newToleranceBps | uint256 | New tolerance (e.g., 200 = 2%) |
updatePriceFeeds
Updates Chainlink feed addresses
Updates the addresses of both Chainlink price feeds with validation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updatePriceFeeds(address _eurUsdFeed, address _usdcUsdFeed) external;
Parameters
| Name | Type | Description |
|---|---|---|
_eurUsdFeed | address | New EUR/USD feed |
_usdcUsdFeed | address | New USDC/USD feed |
resetCircuitBreaker
Clears circuit breaker and attempts to resume live prices
Resets the circuit breaker state to allow normal price operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function resetCircuitBreaker() external;
triggerCircuitBreaker
Manually triggers circuit breaker to use fallback prices
Activates circuit breaker to switch to fallback price mode for safety
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function triggerCircuitBreaker() external;
pause
Pauses all oracle operations
Pauses the oracle contract to halt all price operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpauses oracle operations
Resumes oracle operations after being paused
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
recoverToken
Recovers ERC20 tokens sent to the oracle contract by mistake
Allows recovery of ERC20 tokens accidentally sent to the oracle contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to transfer |
recoverETH
Recovers ETH sent to the oracle contract by mistake
Allows recovery of ETH accidentally sent to the oracle contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
IHedgerPool
Interface for the Quantillon HedgerPool contract
Provides EUR/USD hedging functionality with leverage and margin management
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the HedgerPool with contracts and parameters
Sets up the HedgerPool with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Initializes all contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by initializer modifier
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(
address admin,
address _usdc,
address _oracle,
address _yieldShift,
address _timelock,
address _treasury,
address _vault
) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address receiving roles |
_usdc | address | USDC token address |
_oracle | address | Oracle contract address |
_yieldShift | address | YieldShift contract address |
_timelock | address | Timelock contract address |
_treasury | address | Treasury address |
_vault | address | QuantillonVault contract address |
enterHedgePosition
Opens a new hedge position with specified USDC amount and leverage
Creates a new hedge position with margin requirements and leverage validation
Notes:
-
security: Validates oracle price freshness, enforces margin ratios and leverage limits
-
validation: Validates usdcAmount > 0, leverage <= maxLeverage, position count limits
-
state-changes: Creates new HedgePosition, updates hedger totals, increments position counters
-
events: Emits HedgePositionOpened with position details
-
errors: Throws InvalidAmount if amount is 0, LeverageTooHigh if exceeds max
-
reentrancy: Protected by secureNonReentrant modifier
-
access: Public - no access restrictions
-
oracle: Requires fresh EUR/USD price for position entry
function enterHedgePosition(uint256 usdcAmount, uint256 leverage) external returns (uint256 positionId);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | The amount of USDC to use for the position (6 decimals) |
leverage | uint256 | The leverage multiplier for the position (e.g., 5 for 5x leverage) |
Returns
| Name | Type | Description |
|---|---|---|
positionId | uint256 | The unique ID of the created position |
exitHedgePosition
Closes an existing hedge position
Closes a hedge position and calculates PnL based on current EUR/USD price
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function exitHedgePosition(uint256 positionId) external returns (int256 pnl);
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | The ID of the position to close |
Returns
| Name | Type | Description |
|---|---|---|
pnl | int256 | The profit or loss from the position (positive for profit, negative for loss) |
addMargin
Adds additional margin to an existing position
Adds USDC margin to an existing hedge position to improve margin ratio
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function addMargin(uint256 positionId, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | The ID of the position to add margin to |
amount | uint256 | The amount of USDC to add as margin |
removeMargin
Removes margin from an existing position
Removes USDC margin from an existing hedge position, subject to minimum margin requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function removeMargin(uint256 positionId, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | The ID of the position to remove margin from |
amount | uint256 | The amount of USDC margin to remove |
commitLiquidation
Commits to liquidating a position (first step of two-phase liquidation)
Commits to liquidating an undercollateralized position using a two-phase commit-reveal scheme
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function commitLiquidation(address hedger, uint256 positionId, bytes32 salt) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | The address of the hedger whose position will be liquidated |
positionId | uint256 | The ID of the position to liquidate |
salt | bytes32 | A random value to prevent front-running |
liquidateHedger
Executes the liquidation of a position (second step of two-phase liquidation)
Executes liquidation after valid commitment, transfers rewards and remaining margin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function liquidateHedger(address hedger, uint256 positionId, bytes32 salt)
external
returns (uint256 liquidationReward);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | The address of the hedger whose position is being liquidated |
positionId | uint256 | The ID of the position to liquidate |
salt | bytes32 | The same salt value used in the commitment |
Returns
| Name | Type | Description |
|---|---|---|
liquidationReward | uint256 | The reward paid to the liquidator |
hasPendingLiquidationCommitment
Checks if there's a pending liquidation commitment for a position
Used to prevent margin operations during liquidation process
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasPendingLiquidationCommitment(address hedger, uint256 positionId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | The address of the hedger |
positionId | uint256 | The ID of the position |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if there's a pending liquidation commitment |
clearExpiredLiquidationCommitment
Clears expired liquidation commitments
Removes liquidation commitments that have expired beyond the commitment window
Notes:
-
security: Validates liquidator role and commitment expiration
-
validation: Validates commitment exists and has expired
-
state-changes: Removes expired liquidation commitment
-
events: No events emitted for commitment clearing
-
errors: Throws CommitmentNotFound if commitment doesn't exist
-
reentrancy: Not protected - no external calls
-
access: Restricted to LIQUIDATOR_ROLE
-
oracle: No oracle dependencies
function clearExpiredLiquidationCommitment(address hedger, uint256 positionId) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | The address of the hedger |
positionId | uint256 | The ID of the position |
cancelLiquidationCommitment
Cancels a pending liquidation commitment
Allows hedgers to cancel their liquidation commitment before execution
Notes:
-
security: Validates liquidator role and commitment exists
-
validation: Validates commitment hash matches stored commitment
-
state-changes: Deletes liquidation commitment and pending liquidation flag
-
events: No events emitted for commitment cancellation
-
errors: Throws CommitmentNotFound if commitment doesn't exist
-
reentrancy: Not protected - no external calls
-
access: Restricted to LIQUIDATOR_ROLE
-
oracle: No oracle dependencies
function cancelLiquidationCommitment(address hedger, uint256 positionId, bytes32 salt) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | The hedger address |
positionId | uint256 | The position ID to cancel liquidation for |
salt | bytes32 | Same salt used in commitLiquidation for commitment verification |
claimHedgingRewards
Claims accumulated hedging rewards for the caller
Combines interest rate differential rewards and yield shift rewards
Notes:
-
security: Validates hedger has active positions, updates reward calculations
-
validation: Validates hedger exists and has pending rewards
-
state-changes: Resets pending rewards, updates last claim timestamp
-
events: Emits HedgingRewardsClaimed with reward breakdown
-
errors: Throws YieldClaimFailed if yield shift claim fails
-
reentrancy: Protected by nonReentrant modifier
-
access: Public - any hedger can claim their rewards
-
oracle: No oracle dependencies for reward claiming
function claimHedgingRewards()
external
returns (uint256 interestDifferential, uint256 yieldShiftRewards, uint256 totalRewards);
Returns
| Name | Type | Description |
|---|---|---|
interestDifferential | uint256 | USDC rewards from interest rate differential (6 decimals) |
yieldShiftRewards | uint256 | USDC rewards from yield shift mechanism (6 decimals) |
totalRewards | uint256 | Total USDC rewards claimed (6 decimals) |
getHedgerPosition
Returns detailed information about a specific hedge position
Provides comprehensive position data including current market price
Notes:
-
security: Validates position ownership and oracle price validity
-
validation: Validates hedger owns the position
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws InvalidHedger, InvalidOraclePrice
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query position data
-
oracle: Requires fresh EUR/USD price from Chainlink oracle
function getHedgerPosition(address hedger, uint256 positionId)
external
view
returns (
uint256 positionSize,
uint256 margin,
uint256 entryPrice,
uint256 currentPrice,
uint256 leverage,
uint256 lastUpdateTime
);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | Unique identifier of the position to query |
Returns
| Name | Type | Description |
|---|---|---|
positionSize | uint256 | Total position size in USD equivalent |
margin | uint256 | Current margin amount in USDC (6 decimals) |
entryPrice | uint256 | EUR/USD price when position was opened |
currentPrice | uint256 | Current EUR/USD price from oracle |
leverage | uint256 | Leverage multiplier used for the position |
lastUpdateTime | uint256 | Timestamp of last position update |
getHedgerMarginRatio
Returns the current margin ratio for a specific hedge position
Calculates margin ratio as (margin / positionSize) * 10000 (in basis points)
Notes:
-
security: Validates position ownership
-
validation: Validates hedger owns the position
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws InvalidHedger if hedger doesn't own position
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query margin ratio
-
oracle: No oracle dependencies for margin ratio calculation
function getHedgerMarginRatio(address hedger, uint256 positionId) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | Unique identifier of the position to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | marginRatio Current margin ratio in basis points (10000 = 100%) |
isHedgerLiquidatable
Checks if a hedge position is eligible for liquidation
Determines if position margin ratio is below liquidation threshold
Notes:
-
security: Validates position ownership and oracle price validity
-
validation: Validates hedger owns the position
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws InvalidHedger if hedger doesn't own position
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check liquidation status
-
oracle: Requires fresh EUR/USD price for liquidation calculation
function isHedgerLiquidatable(address hedger, uint256 positionId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionId | uint256 | Unique identifier of the position to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | liquidatable True if position can be liquidated, false otherwise |
getTotalHedgeExposure
Returns the total hedge exposure across all active positions
Calculates sum of all active position sizes in USD equivalent
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total exposure
-
oracle: No oracle dependencies for exposure calculation
function getTotalHedgeExposure() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | totalExposure Total exposure across all hedge positions in USD |
updateHedgingParameters
Updates core hedging parameters for risk management
Allows governance to adjust risk parameters based on market conditions
Notes:
-
security: Validates governance role and parameter constraints
-
validation: Validates minMarginRatio >= 500, liquidationThreshold < minMarginRatio, maxLeverage <= 20, liquidationPenalty <= 1000
-
state-changes: Updates all hedging parameter state variables
-
events: No events emitted for parameter updates
-
errors: Throws ConfigValueTooLow, ConfigInvalid, ConfigValueTooHigh
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies for parameter updates
function updateHedgingParameters(
uint256 newMinMarginRatio,
uint256 newLiquidationThreshold,
uint256 newMaxLeverage,
uint256 newLiquidationPenalty
) external;
Parameters
| Name | Type | Description |
|---|---|---|
newMinMarginRatio | uint256 | New minimum margin ratio in basis points (e.g., 500 = 5%) |
newLiquidationThreshold | uint256 | New liquidation threshold in basis points (e.g., 100 = 1%) |
newMaxLeverage | uint256 | New maximum leverage multiplier (e.g., 20 = 20x) |
newLiquidationPenalty | uint256 | New liquidation penalty in basis points (e.g., 200 = 2%) |
updateInterestRates
Updates interest rates for EUR and USD
Allows governance to adjust interest rates for reward calculations
Notes:
-
security: Validates governance role and rate constraints
-
validation: Validates rates are within reasonable bounds (0-10000 basis points)
-
state-changes: Updates eurInterestRate and usdInterestRate
-
events: No events emitted for rate updates
-
errors: Throws ConfigValueTooHigh if rates exceed maximum limits
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies for rate updates
function updateInterestRates(uint256 newEurRate, uint256 newUsdRate) external;
Parameters
| Name | Type | Description |
|---|---|---|
newEurRate | uint256 | New EUR interest rate in basis points (e.g., 350 = 3.5%) |
newUsdRate | uint256 | New USD interest rate in basis points (e.g., 450 = 4.5%) |
setHedgingFees
Updates hedging fee parameters for protocol revenue
Allows governance to adjust fees based on market conditions and protocol needs
Notes:
-
security: Validates governance role and fee constraints
-
validation: Validates entryFee <= 100, exitFee <= 100, marginFee <= 50
-
state-changes: Updates entryFee, exitFee, and marginFee state variables
-
events: No events emitted for fee updates
-
errors: Throws ConfigValueTooHigh if fees exceed maximum limits
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies for fee updates
function setHedgingFees(uint256 _entryFee, uint256 _exitFee, uint256 _marginFee) external;
Parameters
| Name | Type | Description |
|---|---|---|
_entryFee | uint256 | New entry fee in basis points (e.g., 20 = 0.2%, max 100 = 1%) |
_exitFee | uint256 | New exit fee in basis points (e.g., 20 = 0.2%, max 100 = 1%) |
_marginFee | uint256 | New margin fee in basis points (e.g., 10 = 0.1%, max 50 = 0.5%) |
getHedgingConfig
Get hedging configuration parameters
Returns all key hedging configuration parameters for risk management
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedging configuration
-
oracle: No oracle dependencies
function getHedgingConfig()
external
view
returns (
uint256 _minMarginRatio,
uint256 _liquidationThreshold,
uint256 _maxLeverage,
uint256 _liquidationPenalty,
uint256 _entryFee,
uint256 _exitFee
);
Returns
| Name | Type | Description |
|---|---|---|
_minMarginRatio | uint256 | Minimum margin ratio in basis points |
_liquidationThreshold | uint256 | Liquidation threshold in basis points |
_maxLeverage | uint256 | Maximum leverage multiplier |
_liquidationPenalty | uint256 | Liquidation penalty in basis points |
_entryFee | uint256 | Entry fee in basis points |
_exitFee | uint256 | Exit fee in basis points |
emergencyClosePosition
Emergency close position function
Allows emergency role to force close a position in emergency situations
Notes:
-
security: Validates emergency role authorization
-
validation: Validates position exists and is active
-
state-changes: Closes position, transfers remaining margin to hedger
-
events: Emits HedgePositionClosed event
-
errors: Throws InvalidPosition if position doesn't exist
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to EMERGENCY_ROLE
-
oracle: Requires fresh EUR/USD price for PnL calculation
function emergencyClosePosition(address hedger, uint256 positionId) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position to close |
positionId | uint256 | ID of the position to close |
pause
Pauses all hedging operations
Emergency function to pause the hedger pool in case of critical issues
Notes:
-
security: Validates emergency role authorization
-
validation: No input validation required
-
state-changes: Sets pause state, stops all hedging operations
-
events: Emits Paused event from OpenZeppelin
-
errors: No errors thrown - safe pause operation
-
reentrancy: Not protected - no external calls
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies for pause
function pause() external;
unpause
Unpauses hedging operations
Allows emergency role to unpause the hedger pool after resolving issues
Notes:
-
security: Validates emergency role authorization
-
validation: No input validation required
-
state-changes: Removes pause state, resumes hedging operations
-
events: Emits Unpaused event from OpenZeppelin
-
errors: No errors thrown - safe unpause operation
-
reentrancy: Not protected - no external calls
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies for unpause
function unpause() external;
isHedgingActive
Checks if hedging is currently active
Returns true if the hedger pool is not paused and operational
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check hedging status
-
oracle: No oracle dependencies
function isHedgingActive() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isActive True if hedging is active, false if paused |
recoverToken
Recovers tokens accidentally sent to the contract
Emergency function to recover ERC20 tokens that are not part of normal operations
Notes:
-
security: Validates admin role and uses secure recovery library
-
validation: No input validation required - library handles validation
-
state-changes: Transfers tokens from contract to treasury
-
events: Emits TokenRecovered event
-
errors: No errors thrown - library handles error cases
-
reentrancy: Not protected - library handles reentrancy
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies for token recovery
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Address of the token to recover |
amount | uint256 | Amount of tokens to recover |
recoverETH
Recovers ETH accidentally sent to the contract
Emergency function to recover ETH that was accidentally sent to the contract
Notes:
-
security: Validates admin role and emits recovery event
-
validation: No input validation required - transfers all ETH
-
state-changes: Transfers all contract ETH balance to treasury
-
events: Emits ETHRecovered with amount and treasury address
-
errors: No errors thrown - safe ETH transfer
-
reentrancy: Not protected - no external calls
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function recoverETH() external;
usdc
Returns the USDC token contract interface
USDC token used for margin deposits and withdrawals (6 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query USDC contract
-
oracle: No oracle dependencies
function usdc() external view returns (IERC20);
Returns
| Name | Type | Description |
|---|---|---|
<none> | IERC20 | IERC20 USDC token contract interface |
oracle
Returns the oracle contract address
Chainlink oracle for EUR/USD price feeds
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query oracle address
-
oracle: No oracle dependencies
function oracle() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address Oracle contract address |
yieldShift
Returns the yield shift contract address
YieldShift contract for reward distribution
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query yield shift address
-
oracle: No oracle dependencies
function yieldShift() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address YieldShift contract address |
minMarginRatio
Returns the minimum margin ratio in basis points
Minimum margin ratio required for positions (e.g., 1000 = 10%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query minimum margin ratio
-
oracle: No oracle dependencies
function minMarginRatio() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Minimum margin ratio in basis points |
liquidationThreshold
Returns the liquidation threshold in basis points
Margin ratio below which positions can be liquidated (e.g., 100 = 1%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query liquidation threshold
-
oracle: No oracle dependencies
function liquidationThreshold() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Liquidation threshold in basis points |
maxLeverage
Returns the maximum leverage multiplier
Maximum leverage allowed for hedge positions (e.g., 10 = 10x)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum leverage
-
oracle: No oracle dependencies
function maxLeverage() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum leverage multiplier |
liquidationPenalty
Returns the liquidation penalty in basis points
Penalty applied to liquidated positions (e.g., 200 = 2%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query liquidation penalty
-
oracle: No oracle dependencies
function liquidationPenalty() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Liquidation penalty in basis points |
entryFee
Returns the entry fee in basis points
Fee charged when opening hedge positions (e.g., 20 = 0.2%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query entry fee
-
oracle: No oracle dependencies
function entryFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Entry fee in basis points |
exitFee
Returns the exit fee in basis points
Fee charged when closing hedge positions (e.g., 20 = 0.2%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query exit fee
-
oracle: No oracle dependencies
function exitFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Exit fee in basis points |
marginFee
Returns the margin fee in basis points
Fee charged when adding/removing margin (e.g., 10 = 0.1%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query margin fee
-
oracle: No oracle dependencies
function marginFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Margin fee in basis points |
totalMargin
Returns the total margin across all positions
Total USDC margin held across all active hedge positions (6 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total margin
-
oracle: No oracle dependencies
function totalMargin() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total margin in USDC |
totalExposure
Returns the total exposure across all positions
Total USD exposure across all active hedge positions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total exposure
-
oracle: No oracle dependencies
function totalExposure() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total exposure in USD |
activeHedgers
Returns the number of active hedgers
Count of unique addresses with active hedge positions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query active hedger count
-
oracle: No oracle dependencies
function activeHedgers() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Number of active hedgers |
nextPositionId
Returns the next position ID to be assigned
Counter for generating unique position IDs
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query next position ID
-
oracle: No oracle dependencies
function nextPositionId() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Next position ID |
eurInterestRate
Returns the EUR interest rate in basis points
Interest rate for EUR-denominated positions (e.g., 350 = 3.5%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query EUR interest rate
-
oracle: No oracle dependencies
function eurInterestRate() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 EUR interest rate in basis points |
usdInterestRate
Returns the USD interest rate in basis points
Interest rate for USD-denominated positions (e.g., 450 = 4.5%)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query USD interest rate
-
oracle: No oracle dependencies
function usdInterestRate() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 USD interest rate in basis points |
totalYieldEarned
Returns the total yield earned across all positions
Total yield earned from interest rate differentials (6 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total yield earned
-
oracle: No oracle dependencies
function totalYieldEarned() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total yield earned in USDC |
interestDifferentialPool
Returns the interest differential pool balance
Pool of funds available for interest rate differential rewards (6 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query interest differential pool
-
oracle: No oracle dependencies
function interestDifferentialPool() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Interest differential pool balance in USDC |
activePositionCount
Returns the active position count for a hedger
Number of active positions owned by a specific hedger
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query position count
-
oracle: No oracle dependencies
function activePositionCount(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Number of active positions for the hedger |
positions
Returns position details by position ID
Returns comprehensive position information for a specific position ID
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query position details
-
oracle: No oracle dependencies for position data
function positions(uint256 positionId)
external
view
returns (
address hedger,
uint256 positionSize,
uint256 margin,
uint256 entryPrice,
uint256 leverage,
uint256 entryTime,
uint256 lastUpdateTime,
int256 unrealizedPnL,
bool isActive
);
Parameters
| Name | Type | Description |
|---|---|---|
positionId | uint256 | The ID of the position to query |
Returns
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger who owns the position |
positionSize | uint256 | Total position size in USD equivalent |
margin | uint256 | Current margin amount in USDC (6 decimals) |
entryPrice | uint256 | EUR/USD price when position was opened |
leverage | uint256 | Leverage multiplier used for the position |
entryTime | uint256 | Timestamp when position was opened |
lastUpdateTime | uint256 | Timestamp of last position update |
unrealizedPnL | int256 | Current unrealized profit or loss |
isActive | bool | Whether the position is currently active |
hedgers
Get hedger information
Returns comprehensive information about a hedger's positions and rewards
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger information
-
oracle: No oracle dependencies
function hedgers(address hedger)
external
view
returns (
uint256[] memory positionIds,
uint256 _totalMargin,
uint256 _totalExposure,
uint256 pendingRewards,
uint256 lastRewardClaim,
bool isActive
);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
positionIds | uint256[] | Array of position IDs owned by the hedger |
_totalMargin | uint256 | Total margin across all positions (6 decimals) |
_totalExposure | uint256 | Total exposure across all positions in USD |
pendingRewards | uint256 | Pending rewards available for claim (6 decimals) |
lastRewardClaim | uint256 | Timestamp of last reward claim |
isActive | bool | Whether hedger has active positions |
hedgerPositions
Returns array of position IDs for a hedger
Returns all position IDs owned by a specific hedger
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger positions
-
oracle: No oracle dependencies
function hedgerPositions(address hedger) external view returns (uint256[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256[] | uint256[] Array of position IDs owned by the hedger |
userPendingYield
Returns pending yield for a user
Returns pending yield rewards for a specific user address
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query user pending yield
-
oracle: No oracle dependencies
function userPendingYield(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Pending yield amount in USDC (6 decimals) |
hedgerPendingYield
Returns pending yield for a hedger
Returns pending yield rewards for a specific hedger address
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger pending yield
-
oracle: No oracle dependencies
function hedgerPendingYield(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Pending yield amount in USDC (6 decimals) |
userLastClaim
Returns last claim time for a user
Returns timestamp of last yield claim for a specific user
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query user last claim time
-
oracle: No oracle dependencies
function userLastClaim(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Timestamp of last yield claim |
hedgerLastClaim
Returns last claim time for a hedger
Returns timestamp of last yield claim for a specific hedger
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger last claim time
-
oracle: No oracle dependencies
function hedgerLastClaim(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Timestamp of last yield claim |
hedgerLastRewardBlock
Returns last reward block for a hedger
Returns block number of last reward calculation for a specific hedger
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger last reward block
-
oracle: No oracle dependencies
function hedgerLastRewardBlock(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Block number of last reward calculation |
liquidationCommitments
Returns liquidation commitment status
Returns whether a specific liquidation commitment exists
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query commitment status
-
oracle: No oracle dependencies
function liquidationCommitments(bytes32 commitment) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
commitment | bytes32 | Hash of the liquidation commitment |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if commitment exists, false otherwise |
liquidationCommitmentTimes
Returns liquidation commitment timestamp
Returns block number when liquidation commitment was created
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query commitment timestamp
-
oracle: No oracle dependencies
function liquidationCommitmentTimes(bytes32 commitment) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
commitment | bytes32 | Hash of the liquidation commitment |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Block number when commitment was created |
lastLiquidationAttempt
Returns last liquidation attempt block
Returns block number of last liquidation attempt for a hedger
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query last liquidation attempt
-
oracle: No oracle dependencies
function lastLiquidationAttempt(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Block number of last liquidation attempt |
hasPendingLiquidation
Returns pending liquidation status
Returns whether a position has a pending liquidation commitment
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query pending liquidation status
-
oracle: No oracle dependencies
function hasPendingLiquidation(address hedger, uint256 positionId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger |
positionId | uint256 | ID of the position |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if liquidation is pending, false otherwise |
MAX_POSITIONS_PER_HEDGER
Returns the maximum positions per hedger
Maximum number of positions a single hedger can have open simultaneously
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum positions per hedger
-
oracle: No oracle dependencies
function MAX_POSITIONS_PER_HEDGER() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum positions per hedger |
BLOCKS_PER_DAY
Returns the number of blocks per day
Used for time-based calculations and reward periods
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query blocks per day
-
oracle: No oracle dependencies
function BLOCKS_PER_DAY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Number of blocks per day |
MAX_REWARD_PERIOD
Returns the maximum reward period
Maximum time period for reward calculations in blocks
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum reward period
-
oracle: No oracle dependencies
function MAX_REWARD_PERIOD() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum reward period in blocks |
LIQUIDATION_COOLDOWN
Returns the liquidation cooldown period
Minimum blocks between liquidation attempts for the same hedger
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query liquidation cooldown
-
oracle: No oracle dependencies
function LIQUIDATION_COOLDOWN() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Liquidation cooldown in blocks |
whitelistHedger
Whitelists a hedger address
Allows the specified address to open hedge positions when whitelist is enabled
Notes:
-
security: Validates governance role and hedger address
-
validation: Validates hedger is not address(0) and not already whitelisted
-
state-changes: Updates isWhitelistedHedger mapping and grants HEDGER_ROLE
-
events: Emits HedgerWhitelisted with hedger and caller addresses
-
errors: Throws ZeroAddress if hedger is address(0), AlreadyWhitelisted if already whitelisted
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function whitelistHedger(address hedger) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address to whitelist as a hedger |
removeHedger
Removes a hedger from the whitelist
Prevents the specified address from opening new hedge positions
Notes:
-
security: Validates governance role and hedger address
-
validation: Validates hedger is not address(0) and is currently whitelisted
-
state-changes: Updates isWhitelistedHedger mapping and revokes HEDGER_ROLE
-
events: Emits HedgerRemoved with hedger and caller addresses
-
errors: Throws ZeroAddress if hedger is address(0), NotWhitelisted if not whitelisted
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function removeHedger(address hedger) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address to remove from hedger whitelist |
toggleHedgerWhitelistMode
Toggles hedger whitelist mode
When enabled, only whitelisted addresses can open hedge positions
Notes:
-
security: Validates governance role
-
validation: No input validation required - boolean parameter
-
state-changes: Updates hedgerWhitelistEnabled state variable
-
events: Emits HedgerWhitelistModeToggled with enabled status and caller
-
errors: No errors thrown - safe boolean toggle
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function toggleHedgerWhitelistMode(bool enabled) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable hedger whitelist mode |
isWhitelistedHedger
Check if an address is whitelisted as a hedger
Returns true if the address is on the hedger whitelist
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger whitelist status
-
oracle: No oracle dependencies
function isWhitelistedHedger(address hedger) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isWhitelisted True if the address is whitelisted as a hedger |
hedgerWhitelistEnabled
Check if hedger whitelist mode is enabled
Returns true if hedger whitelist mode is active
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query hedger whitelist mode status
-
oracle: No oracle dependencies
function hedgerWhitelistEnabled() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | enabled True if hedger whitelist mode is enabled |
Events
HedgePositionOpened
event HedgePositionOpened(
address indexed hedger,
uint256 indexed positionId,
uint256 positionSize,
uint256 margin,
uint256 leverage,
uint256 entryPrice
);
HedgePositionClosed
event HedgePositionClosed(
address indexed hedger, uint256 indexed positionId, uint256 exitPrice, int256 pnl, uint256 timestamp
);
MarginAdded
event MarginAdded(address indexed hedger, uint256 indexed positionId, uint256 marginAdded, uint256 newMarginRatio);
MarginRemoved
event MarginRemoved(
address indexed hedger, uint256 indexed positionId, uint256 marginRemoved, uint256 newMarginRatio
);
HedgerLiquidated
event HedgerLiquidated(
address indexed hedger,
uint256 indexed positionId,
address indexed liquidator,
uint256 liquidationReward,
uint256 remainingMargin
);
HedgingRewardsClaimed
event HedgingRewardsClaimed(
address indexed hedger, uint256 interestDifferential, uint256 yieldShiftRewards, uint256 totalRewards
);
HedgerWhitelisted
event HedgerWhitelisted(address indexed hedger, address indexed caller);
HedgerRemoved
event HedgerRemoved(address indexed hedger, address indexed caller);
HedgerWhitelistModeToggled
event HedgerWhitelistModeToggled(bool enabled, address indexed caller);
IQEUROToken
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Read-only interface for the QEURO token
Exposes ERC20 metadata and helper views used by integrators
Note: security-contact: team@quantillon.money
Functions
name
Token name
Returns the name of the QEURO token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function name() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | name The token name string |
symbol
Token symbol
Returns the symbol of the QEURO token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function symbol() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | symbol The token symbol string |
decimals
Token decimals (always 18)
Returns the number of decimals used by the token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function decimals() external view returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | decimals The number of decimals (always 18) |
totalSupply
Total token supply
Returns the total supply of QEURO tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalSupply() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | totalSupply The total supply (18 decimals) |
balanceOf
Balance of an account
Returns the token balance of the specified account
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function balanceOf(address account) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | balance The token balance (18 decimals) |
isMinter
Whether an address has the minter role
Checks if the specified account has the MINTER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isMinter(address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isMinter True if the account has the minter role |
isBurner
Whether an address has the burner role
Checks if the specified account has the BURNER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isBurner(address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isBurner True if the account has the burner role |
getSupplyUtilization
Percentage of max supply utilized (basis points)
Returns the percentage of maximum supply currently in circulation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getSupplyUtilization() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | utilization Percentage of max supply utilized (basis points) |
getTokenInfo
Aggregated token information snapshot
Returns comprehensive token information in a single call
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTokenInfo()
external
view
returns (
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 totalSupply_,
uint256 maxSupply_,
bool isPaused_,
bool whitelistEnabled_,
uint256 mintRateLimit_,
uint256 burnRateLimit_
);
Returns
| Name | Type | Description |
|---|---|---|
name_ | string | Token name |
symbol_ | string | Token symbol |
decimals_ | uint8 | Token decimals |
totalSupply_ | uint256 | Current total supply |
maxSupply_ | uint256 | Maximum supply cap |
isPaused_ | bool | Whether the token is paused |
whitelistEnabled_ | bool | Whether whitelist mode is active |
mintRateLimit_ | uint256 | Current mint rate limit per hour |
burnRateLimit_ | uint256 | Current burn rate limit per hour |
initialize
Initialize the QEURO token contract
Sets up initial roles and configuration for the token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(address admin, address vault, address timelock, address treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address of the admin role |
vault | address | Address of the vault contract |
timelock | address | Address of the timelock contract |
treasury | address | Treasury address |
mint
Mint new QEURO tokens to an address
Creates new tokens and adds them to the specified address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function mint(address to, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address to receive the minted tokens |
amount | uint256 | Amount of tokens to mint (18 decimals) |
burn
Burn QEURO tokens from an address
Destroys tokens from the specified address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function burn(address from, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Address to burn tokens from |
amount | uint256 | Amount of tokens to burn (18 decimals) |
batchMint
Mint new QEURO tokens to multiple addresses
Creates new tokens and distributes them to multiple recipients
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchMint(address[] calldata recipients, uint256[] calldata amounts) external;
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of addresses to receive the minted tokens |
amounts | uint256[] | Array of amounts to mint for each recipient (18 decimals) |
batchBurn
Burn QEURO tokens from multiple addresses
Destroys tokens from multiple addresses
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchBurn(address[] calldata froms, uint256[] calldata amounts) external;
Parameters
| Name | Type | Description |
|---|---|---|
froms | address[] | Array of addresses to burn tokens from |
amounts | uint256[] | Array of amounts to burn from each address (18 decimals) |
batchTransfer
Transfer QEURO tokens to multiple addresses
Transfers tokens from the caller to multiple recipients
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of addresses to receive the tokens |
amounts | uint256[] | Array of amounts to transfer to each recipient (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if all transfers were successful |
updateRateLimits
Update rate limits for minting and burning operations
Modifies the maximum amount of tokens that can be minted or burned per hour
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateRateLimits(uint256 newMintLimit, uint256 newBurnLimit) external;
Parameters
| Name | Type | Description |
|---|---|---|
newMintLimit | uint256 | New maximum amount of tokens that can be minted per hour (18 decimals) |
newBurnLimit | uint256 | New maximum amount of tokens that can be burned per hour (18 decimals) |
blacklistAddress
Add an address to the blacklist with a reason
Prevents the specified address from participating in token operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function blacklistAddress(address account, string memory reason) external;
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to blacklist |
reason | string | Reason for blacklisting the address |
unblacklistAddress
Remove an address from the blacklist
Allows the specified address to participate in token operations again
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unblacklistAddress(address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to remove from blacklist |
whitelistAddress
Add an address to the whitelist
Allows the specified address to participate in token operations when whitelist mode is enabled
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function whitelistAddress(address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to whitelist |
unwhitelistAddress
Remove an address from the whitelist
Prevents the specified address from participating in token operations when whitelist mode is enabled
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unwhitelistAddress(address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to remove from whitelist |
toggleWhitelistMode
Toggle whitelist mode on or off
When enabled, only whitelisted addresses can participate in token operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function toggleWhitelistMode(bool enabled) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | True to enable whitelist mode, false to disable |
batchBlacklistAddresses
Add multiple addresses to the blacklist with reasons
Batch operation to blacklist multiple addresses efficiently
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchBlacklistAddresses(address[] calldata accounts, string[] calldata reasons) external;
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to blacklist |
reasons | string[] | Array of reasons for blacklisting each address |
batchUnblacklistAddresses
Remove multiple addresses from the blacklist
Batch operation to unblacklist multiple addresses efficiently
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchUnblacklistAddresses(address[] calldata accounts) external;
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to remove from blacklist |
batchWhitelistAddresses
Add multiple addresses to the whitelist
Batch operation to whitelist multiple addresses efficiently
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchWhitelistAddresses(address[] calldata accounts) external;
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to whitelist |
batchUnwhitelistAddresses
Remove multiple addresses from the whitelist
Batch operation to unwhitelist multiple addresses efficiently
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchUnwhitelistAddresses(address[] calldata accounts) external;
Parameters
| Name | Type | Description |
|---|---|---|
accounts | address[] | Array of addresses to remove from whitelist |
updateMinPricePrecision
Update the minimum price precision for oracle feeds
Sets the minimum number of decimal places required for price feeds
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateMinPricePrecision(uint256 newPrecision) external;
Parameters
| Name | Type | Description |
|---|---|---|
newPrecision | uint256 | New minimum precision value (number of decimal places) |
normalizePrice
Normalize price from different decimal precisions to 18 decimals
Converts price from source feed decimals to standard 18 decimal format
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function normalizePrice(uint256 price, uint8 feedDecimals) external pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
price | uint256 | Price value to normalize |
feedDecimals | uint8 | Number of decimal places in the source feed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | normalizedPrice Price normalized to 18 decimals |
validatePricePrecision
Validate if price precision meets minimum requirements
Checks if the price feed has sufficient decimal precision
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function validatePricePrecision(uint256 price, uint8 feedDecimals) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
price | uint256 | Price value to validate |
feedDecimals | uint8 | Number of decimal places in the price feed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isValid True if precision meets minimum requirements |
pause
Pause all token operations
Emergency function to halt all token transfers, minting, and burning
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpause all token operations
Resumes normal token operations after emergency pause
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
recoverToken
Recover accidentally sent tokens
Allows recovery of ERC20 tokens sent to the contract by mistake
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Address of the token to recover |
amount | uint256 | Amount of tokens to recover |
recoverETH
Recover accidentally sent ETH
Allows recovery of ETH sent to the contract by mistake
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
updateMaxSupply
Update the maximum supply of QEURO tokens
Sets a new maximum supply limit for the token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateMaxSupply(uint256 newMaxSupply) external;
Parameters
| Name | Type | Description |
|---|---|---|
newMaxSupply | uint256 | New maximum supply limit (18 decimals) |
transfer
Transfer QEURO tokens to another address
Standard ERC20 transfer function with compliance checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function transfer(address to, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address to transfer tokens to |
amount | uint256 | Amount of tokens to transfer (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if transfer was successful |
allowance
Get the allowance for a spender
Returns the amount of tokens that a spender is allowed to transfer
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function allowance(address owner, address spender) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
owner | address | Address of the token owner |
spender | address | Address of the spender |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | allowance Amount of tokens the spender can transfer (18 decimals) |
approve
Approve a spender to transfer tokens
Sets the allowance for a spender to transfer tokens on behalf of the caller
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function approve(address spender, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
spender | address | Address of the spender to approve |
amount | uint256 | Amount of tokens to approve (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if approval was successful |
transferFrom
Transfer tokens from one address to another
Standard ERC20 transferFrom function with compliance checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function transferFrom(address from, address to, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Address to transfer tokens from |
to | address | Address to transfer tokens to |
amount | uint256 | Amount of tokens to transfer (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if transfer was successful |
hasRole
Check if an address has a specific role
Returns true if the account has the specified role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role to check for |
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | hasRole True if the account has the role |
getRoleAdmin
Get the admin role for a specific role
Returns the role that is the admin of the given role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role to get admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | adminRole The admin role |
grantRole
Grant a role to an address
Assigns the specified role to the given account
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role to grant |
account | address | Address to grant the role to |
revokeRole
Revoke a role from an address
Removes the specified role from the given account
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role to revoke |
account | address | Address to revoke the role from |
renounceRole
Renounce a role
Removes the specified role from the caller
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | Role to renounce |
callerConfirmation | address | Address of the caller (for security) |
paused
Check if the contract is paused
Returns true if all token operations are paused
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isPaused True if the contract is paused |
upgradeTo
Upgrade the contract implementation
Upgrades to a new implementation address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
upgradeToAndCall
Upgrade the contract implementation and call a function
Upgrades to a new implementation and executes a function call
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
data | bytes | Encoded function call data |
MINTER_ROLE
Get the MINTER_ROLE constant
Returns the role hash for minters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MINTER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | role The MINTER_ROLE bytes32 value |
BURNER_ROLE
Get the BURNER_ROLE constant
Returns the role hash for burners
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function BURNER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | role The BURNER_ROLE bytes32 value |
PAUSER_ROLE
Get the PAUSER_ROLE constant
Returns the role hash for pausers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function PAUSER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | role The PAUSER_ROLE bytes32 value |
UPGRADER_ROLE
Get the UPGRADER_ROLE constant
Returns the role hash for upgraders
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | role The UPGRADER_ROLE bytes32 value |
COMPLIANCE_ROLE
Get the COMPLIANCE_ROLE constant
Returns the role hash for compliance officers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function COMPLIANCE_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | role The COMPLIANCE_ROLE bytes32 value |
DEFAULT_MAX_SUPPLY
Get the DEFAULT_MAX_SUPPLY constant
Returns the default maximum supply limit
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function DEFAULT_MAX_SUPPLY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | maxSupply The default maximum supply (18 decimals) |
MAX_RATE_LIMIT
Get the MAX_RATE_LIMIT constant
Returns the maximum rate limit value
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MAX_RATE_LIMIT() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | maxLimit The maximum rate limit (18 decimals) |
PRECISION
Get the PRECISION constant
Returns the precision value used for calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function PRECISION() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | precision The precision value (18 decimals) |
maxSupply
Get the current maximum supply limit
Returns the maximum number of tokens that can be minted
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function maxSupply() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | maxSupply Current maximum supply limit (18 decimals) |
mintRateLimit
Get the current mint rate limit
Returns the maximum amount of tokens that can be minted per hour
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function mintRateLimit() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | mintLimit Current mint rate limit (18 decimals) |
burnRateLimit
Get the current burn rate limit
Returns the maximum amount of tokens that can be burned per hour
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function burnRateLimit() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | burnLimit Current burn rate limit (18 decimals) |
currentHourMinted
Get the amount minted in the current hour
Returns the total amount of tokens minted in the current rate limit window
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function currentHourMinted() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | minted Current hour minted amount (18 decimals) |
currentHourBurned
Get the amount burned in the current hour
Returns the total amount of tokens burned in the current rate limit window
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function currentHourBurned() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | burned Current hour burned amount (18 decimals) |
lastRateLimitReset
Get the timestamp of the last rate limit reset
Returns when the rate limit counters were last reset
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function lastRateLimitReset() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | resetTime Timestamp of last rate limit reset |
isBlacklisted
Check if an address is blacklisted
Returns true if the address is on the blacklist
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isBlacklisted(address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isBlacklisted True if the address is blacklisted |
isWhitelisted
Check if an address is whitelisted
Returns true if the address is on the whitelist
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isWhitelisted(address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isWhitelisted True if the address is whitelisted |
whitelistEnabled
Check if whitelist mode is enabled
Returns true if whitelist mode is active
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function whitelistEnabled() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | enabled True if whitelist mode is enabled |
minPricePrecision
Get the minimum price precision requirement
Returns the minimum number of decimal places required for price feeds
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function minPricePrecision() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | precision Minimum price precision value |
IQTIToken
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the QTI governance token with vote-escrow mechanics
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the QTI token
Sets up initial roles and configuration for the governance token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(address admin, address _treasury, address timelock) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address |
_treasury | address | Treasury address |
timelock | address | Timelock address |
lock
Lock QTI tokens for voting power
Locks QTI tokens for a specified duration to receive voting power
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function lock(uint256 amount, uint256 lockTime) external returns (uint256 veQTI);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of QTI to lock (18 decimals) |
lockTime | uint256 | Duration to lock (seconds) |
Returns
| Name | Type | Description |
|---|---|---|
veQTI | uint256 | Voting power received (18 decimals) |
unlock
Unlock QTI tokens after lock period expires
Unlocks all expired QTI tokens and returns them to the caller
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unlock() external returns (uint256 amount);
Returns
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of QTI unlocked (18 decimals) |
batchLock
Batch lock QTI tokens for voting power
Locks multiple amounts of QTI tokens with different lock durations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchLock(uint256[] calldata amounts, uint256[] calldata lockTimes)
external
returns (uint256[] memory veQTIAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of amounts to lock (18 decimals each) |
lockTimes | uint256[] | Array of corresponding lock durations (seconds each) |
Returns
| Name | Type | Description |
|---|---|---|
veQTIAmounts | uint256[] | Array of voting power received per lock (18 decimals each) |
batchUnlock
Batch unlock QTI tokens for multiple users (admin/governance)
Unlocks expired QTI tokens for multiple users in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchUnlock(address[] calldata users) external returns (uint256[] memory amounts);
Parameters
| Name | Type | Description |
|---|---|---|
users | address[] | Array of user addresses to unlock for |
Returns
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of amounts unlocked per user (18 decimals each) |
getVotingPower
Get voting power for an address
Returns the current voting power for a user based on their locked tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getVotingPower(address user) external view returns (uint256 votingPower);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
votingPower | uint256 | Current voting power (18 decimals) |
updateVotingPower
Update voting power for the caller based on current time
Recalculates and updates voting power based on time decay
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateVotingPower() external returns (uint256 newVotingPower);
Returns
| Name | Type | Description |
|---|---|---|
newVotingPower | uint256 | Updated voting power (18 decimals) |
getLockInfo
Get lock info for an address
Returns comprehensive lock information for a user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getLockInfo(address user)
external
view
returns (
uint256 amount,
uint256 unlockTime,
uint256 votingPower,
uint256 lastClaimTime,
uint256 initialVotingPower,
uint256 lockTime
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
amount | uint256 | Locked amount (18 decimals) |
unlockTime | uint256 | Unlock timestamp |
votingPower | uint256 | Current voting power (18 decimals) |
lastClaimTime | uint256 | Last claim time |
initialVotingPower | uint256 | Initial voting power when locked (18 decimals) |
lockTime | uint256 | Original lock duration (seconds) |
createProposal
Create a new governance proposal
Creates a new governance proposal with specified parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function createProposal(string calldata description, uint256 votingPeriod, bytes calldata data)
external
returns (uint256 proposalId);
Parameters
| Name | Type | Description |
|---|---|---|
description | string | Proposal description |
votingPeriod | uint256 | Voting period in seconds |
data | bytes | Execution data |
Returns
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | New proposal ID |
vote
Vote on a proposal
Casts a vote on a governance proposal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function vote(uint256 proposalId, bool support) external;
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
support | bool | True for yes, false for no |
batchVote
Batch vote on multiple proposals
Casts votes on multiple governance proposals in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchVote(uint256[] calldata proposalIds, bool[] calldata supportVotes) external;
Parameters
| Name | Type | Description |
|---|---|---|
proposalIds | uint256[] | Array of proposal IDs |
supportVotes | bool[] | Array of vote choices (true/false) |
executeProposal
Execute a successful proposal
Executes a proposal that has passed voting requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function executeProposal(uint256 proposalId) external;
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
cancelProposal
Cancel a proposal
Cancels a proposal before execution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function cancelProposal(uint256 proposalId) external;
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
getProposal
Get proposal details
Returns comprehensive information about a governance proposal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getProposal(uint256 proposalId)
external
view
returns (
address proposer,
uint256 startTime,
uint256 endTime,
uint256 forVotes,
uint256 againstVotes,
bool executed,
bool canceled,
string memory description
);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
Returns
| Name | Type | Description |
|---|---|---|
proposer | address | Proposal creator |
startTime | uint256 | Voting start time |
endTime | uint256 | Voting end time |
forVotes | uint256 | Votes in favor (18 decimals) |
againstVotes | uint256 | Votes against (18 decimals) |
executed | bool | Whether executed |
canceled | bool | Whether canceled |
description | string | Proposal description |
getReceipt
Get voting receipt for a user
Returns voting information for a specific user and proposal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getReceipt(uint256 proposalId, address voter)
external
view
returns (bool hasVoted, bool support, uint256 votes);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | Proposal ID |
voter | address | Voter address |
Returns
| Name | Type | Description |
|---|---|---|
hasVoted | bool | Whether user voted |
support | bool | Vote direction |
votes | uint256 | Number of votes cast (18 decimals) |
getProposalExecutionInfo
Gets proposal execution information
Returns execution details for a specific proposal
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public access - anyone can query proposal execution info
-
oracle: No oracle dependencies
function getProposalExecutionInfo(uint256 proposalId)
external
view
returns (bytes32 executionHash, uint256 executionTime, address executor);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | ID of the proposal |
Returns
| Name | Type | Description |
|---|---|---|
executionHash | bytes32 | Hash of the execution data |
executionTime | uint256 | Time when proposal was executed |
executor | address | Address that executed the proposal |
getProposalExecutionHash
Gets proposal execution hash
Returns the execution hash for a specific proposal
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public access - anyone can query proposal execution hash
-
oracle: No oracle dependencies
function getProposalExecutionHash(uint256 proposalId) external view returns (bytes32 executionHash);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | ID of the proposal |
Returns
| Name | Type | Description |
|---|---|---|
executionHash | bytes32 | Hash of the execution data |
updateGovernanceParameters
Update governance parameters
Updates key governance parameters for the protocol
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateGovernanceParameters(uint256 _proposalThreshold, uint256 _minVotingPeriod, uint256 _quorumVotes)
external;
Parameters
| Name | Type | Description |
|---|---|---|
_proposalThreshold | uint256 | New proposal threshold (18 decimals) |
_minVotingPeriod | uint256 | New minimum voting period (seconds) |
_quorumVotes | uint256 | New quorum requirement (18 decimals) |
updateTreasury
Update treasury address
Updates the treasury address for protocol fees and rewards
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateTreasury(address _treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
updateDecentralizationLevel
Update decentralization level
Updates the decentralization level based on current protocol state
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateDecentralizationLevel() external;
pause
Pause the contract
Pauses all contract operations for emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpause the contract
Resumes all contract operations after emergency pause
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
getGovernanceInfo
Get governance information
Returns comprehensive governance information in a single call
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getGovernanceInfo()
external
view
returns (
uint256 _totalLocked,
uint256 _totalVotingPower,
uint256 _proposalThreshold,
uint256 _quorumVotes,
uint256 _currentDecentralizationLevel
);
Returns
| Name | Type | Description |
|---|---|---|
_totalLocked | uint256 | Total locked QTI (18 decimals) |
_totalVotingPower | uint256 | Total voting power (18 decimals) |
_proposalThreshold | uint256 | Proposal threshold (18 decimals) |
_quorumVotes | uint256 | Quorum requirement (18 decimals) |
_currentDecentralizationLevel | uint256 | Current decentralization level |
name
Get the token name
Returns the name of the QTI token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function name() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | name The token name string |
symbol
Get the token symbol
Returns the symbol of the QTI token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function symbol() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | symbol The token symbol string |
decimals
Get the token decimals
Returns the number of decimals used by the token
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function decimals() external view returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | decimals The number of decimals (always 18) |
totalSupply
Get the total token supply
Returns the total supply of QTI tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalSupply() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | totalSupply The total supply (18 decimals) |
balanceOf
Get the balance of an account
Returns the token balance of the specified account
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function balanceOf(address account) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | balance The token balance (18 decimals) |
transfer
Transfer QTI tokens to another address
Standard ERC20 transfer function
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function transfer(address to, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address to transfer tokens to |
amount | uint256 | Amount of tokens to transfer (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if transfer was successful |
allowance
Get the allowance for a spender
Returns the amount of tokens that a spender is allowed to transfer
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function allowance(address owner, address spender) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
owner | address | Address of the token owner |
spender | address | Address of the spender |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | allowance Amount of tokens the spender can transfer (18 decimals) |
approve
Approve a spender to transfer tokens
Sets the allowance for a spender to transfer tokens on behalf of the caller
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function approve(address spender, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
spender | address | Address of the spender to approve |
amount | uint256 | Amount of tokens to approve (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if approval was successful |
transferFrom
Transfer tokens from one address to another
Standard ERC20 transferFrom function
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function transferFrom(address from, address to, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Address to transfer tokens from |
to | address | Address to transfer tokens to |
amount | uint256 | Amount of tokens to transfer (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if transfer was successful |
hasRole
Check if an account has a specific role
Returns true if the account has the specified role
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check roles
-
oracle: No oracle dependencies
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if account has the role, false otherwise |
getRoleAdmin
Get the admin role for a specific role
Returns the admin role that can grant/revoke the specified role
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role admin
-
oracle: No oracle dependencies
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to get admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The admin role |
grantRole
Grant a role to an account
Grants the specified role to the account
Notes:
-
security: Validates caller has admin role for the specified role
-
validation: Validates account is not address(0)
-
state-changes: Grants role to account
-
events: Emits RoleGranted event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to role admin
-
oracle: No oracle dependencies
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revoke a role from an account
Revokes the specified role from the account
Notes:
-
security: Validates caller has admin role for the specified role
-
validation: Validates account is not address(0)
-
state-changes: Revokes role from account
-
events: Emits RoleRevoked event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to role admin
-
oracle: No oracle dependencies
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounce a role
Allows an account to renounce their own role
Notes:
-
security: Validates caller is renouncing their own role
-
validation: Validates callerConfirmation matches msg.sender
-
state-changes: Revokes role from caller
-
events: Emits RoleRevoked event
-
errors: Throws AccessControlBadConfirmation if callerConfirmation != msg.sender
-
reentrancy: Not protected - no external calls
-
access: Public - anyone can renounce their own roles
-
oracle: No oracle dependencies
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | The caller's address for confirmation |
paused
Check if the contract is paused
Returns true if the contract is currently paused
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check pause status
-
oracle: No oracle dependencies
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if paused, false if not paused |
upgradeTo
Upgrade the contract implementation
Upgrades the contract to a new implementation
Notes:
-
security: Validates caller has UPGRADER_ROLE
-
validation: Validates newImplementation is not address(0)
-
state-changes: Updates implementation address
-
events: Emits Upgraded event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks UPGRADER_ROLE
-
reentrancy: Not protected - no external calls
-
access: Restricted to UPGRADER_ROLE
-
oracle: No oracle dependencies
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
upgradeToAndCall
Upgrade the contract implementation with initialization
Upgrades the contract to a new implementation and calls initialization function
Notes:
-
security: Validates caller has UPGRADER_ROLE
-
validation: Validates newImplementation is not address(0)
-
state-changes: Updates implementation address and calls initialization
-
events: Emits Upgraded event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks UPGRADER_ROLE
-
reentrancy: Not protected - no external calls
-
access: Restricted to UPGRADER_ROLE
-
oracle: No oracle dependencies
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
data | bytes | Initialization data to call on new implementation |
GOVERNANCE_ROLE
Returns the governance role identifier
Role required for governance operations
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query governance role
-
oracle: No oracle dependencies
function GOVERNANCE_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The governance role identifier |
EMERGENCY_ROLE
Returns the emergency role identifier
Role required for emergency operations
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query emergency role
-
oracle: No oracle dependencies
function EMERGENCY_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The emergency role identifier |
UPGRADER_ROLE
Returns the upgrader role identifier
Role required for contract upgrades
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query upgrader role
-
oracle: No oracle dependencies
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 The upgrader role identifier |
MAX_LOCK_TIME
Returns the maximum lock time
Maximum duration tokens can be locked for (seconds)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum lock time
-
oracle: No oracle dependencies
function MAX_LOCK_TIME() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum lock time in seconds |
MIN_LOCK_TIME
Returns the minimum lock time
Minimum duration tokens must be locked for (seconds)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query minimum lock time
-
oracle: No oracle dependencies
function MIN_LOCK_TIME() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Minimum lock time in seconds |
WEEK
Returns the week duration
Duration of one week in seconds
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query week duration
-
oracle: No oracle dependencies
function WEEK() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Week duration in seconds |
MAX_VE_QTI_MULTIPLIER
Returns the maximum veQTI multiplier
Maximum voting power multiplier for locked tokens
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum veQTI multiplier
-
oracle: No oracle dependencies
function MAX_VE_QTI_MULTIPLIER() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum veQTI multiplier |
MAX_TIME_ELAPSED
Returns the maximum time elapsed
Maximum time that can elapse for calculations
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum time elapsed
-
oracle: No oracle dependencies
function MAX_TIME_ELAPSED() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum time elapsed in seconds |
TOTAL_SUPPLY_CAP
Returns the total supply cap
Maximum total supply of QTI tokens (18 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total supply cap
-
oracle: No oracle dependencies
function TOTAL_SUPPLY_CAP() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total supply cap in QTI tokens |
locks
Returns lock information for an address
Returns comprehensive lock information for a user
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query lock information
-
oracle: No oracle dependencies
function locks(address user)
external
view
returns (
uint256 amount,
uint256 unlockTime,
uint256 votingPower,
uint256 lastClaimTime,
uint256 initialVotingPower,
uint256 lockTime
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user to query |
Returns
| Name | Type | Description |
|---|---|---|
amount | uint256 | Locked amount (18 decimals) |
unlockTime | uint256 | Unlock timestamp |
votingPower | uint256 | Current voting power (18 decimals) |
lastClaimTime | uint256 | Last claim time |
initialVotingPower | uint256 | Initial voting power when locked (18 decimals) |
lockTime | uint256 | Original lock duration (seconds) |
totalLocked
Returns total locked QTI tokens
Total amount of QTI tokens locked across all users (18 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total locked
-
oracle: No oracle dependencies
function totalLocked() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total locked QTI tokens |
totalVotingPower
Returns total voting power
Total voting power across all locked tokens (18 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total voting power
-
oracle: No oracle dependencies
function totalVotingPower() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total voting power |
proposals
Returns proposal information by ID
Returns comprehensive proposal information
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query proposal information
-
oracle: No oracle dependencies
function proposals(uint256 proposalId)
external
view
returns (
address proposer,
uint256 startTime,
uint256 endTime,
uint256 forVotes,
uint256 againstVotes,
bool executed,
bool canceled,
string memory description
);
Parameters
| Name | Type | Description |
|---|---|---|
proposalId | uint256 | ID of the proposal to query |
Returns
| Name | Type | Description |
|---|---|---|
proposer | address | Proposal creator address |
startTime | uint256 | Voting start timestamp |
endTime | uint256 | Voting end timestamp |
forVotes | uint256 | Votes in favor (18 decimals) |
againstVotes | uint256 | Votes against (18 decimals) |
executed | bool | Whether proposal was executed |
canceled | bool | Whether proposal was canceled |
description | string | Proposal description |
nextProposalId
Returns the next proposal ID
Counter for generating unique proposal IDs
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query next proposal ID
-
oracle: No oracle dependencies
function nextProposalId() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Next proposal ID |
proposalThreshold
Returns the proposal threshold
Minimum voting power required to create proposals (18 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query proposal threshold
-
oracle: No oracle dependencies
function proposalThreshold() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Proposal threshold in QTI tokens |
minVotingPeriod
Returns the minimum voting period
Minimum duration for proposal voting (seconds)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query minimum voting period
-
oracle: No oracle dependencies
function minVotingPeriod() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Minimum voting period in seconds |
maxVotingPeriod
Returns the maximum voting period
Maximum duration for proposal voting (seconds)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum voting period
-
oracle: No oracle dependencies
function maxVotingPeriod() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Maximum voting period in seconds |
quorumVotes
Returns the quorum votes requirement
Minimum votes required for proposal execution (18 decimals)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query quorum votes
-
oracle: No oracle dependencies
function quorumVotes() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Quorum votes requirement in QTI tokens |
treasury
Returns the treasury address
Address where protocol fees and rewards are sent
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query treasury address
-
oracle: No oracle dependencies
function treasury() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | address Treasury address |
decentralizationStartTime
Returns the decentralization start time
Timestamp when decentralization process began
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query decentralization start time
-
oracle: No oracle dependencies
function decentralizationStartTime() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Decentralization start timestamp |
decentralizationDuration
Returns the decentralization duration
Duration of the decentralization process (seconds)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query decentralization duration
-
oracle: No oracle dependencies
function decentralizationDuration() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Decentralization duration in seconds |
currentDecentralizationLevel
Returns the current decentralization level
Current level of protocol decentralization (0-100)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query current decentralization level
-
oracle: No oracle dependencies
function currentDecentralizationLevel() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Current decentralization level |
recoverToken
Recovers tokens accidentally sent to the contract
Emergency function to recover ERC20 tokens that are not part of normal operations
Notes:
-
security: Validates admin role and uses secure recovery library
-
validation: No input validation required - library handles validation
-
state-changes: Transfers tokens from contract to treasury
-
events: Emits TokenRecovered event
-
errors: No errors thrown - library handles error cases
-
reentrancy: Not protected - library handles reentrancy
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies for token recovery
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Address of the token to recover |
amount | uint256 | Amount of tokens to recover |
recoverETH
Recovers ETH accidentally sent to the contract
Emergency function to recover ETH that was accidentally sent to the contract
Notes:
-
security: Validates admin role and emits recovery event
-
validation: No input validation required - transfers all ETH
-
state-changes: Transfers all contract ETH balance to treasury
-
events: Emits ETHRecovered with amount and treasury address
-
errors: No errors thrown - safe ETH transfer
-
reentrancy: Not protected - no external calls
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies
function recoverETH() external;
IQuantillonVault
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the Quantillon vault managing QEURO mint/redeem against USDC
Exposes core swap functions, views, governance, emergency, and recovery
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the vault
Sets up the vault with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(
address admin,
address _qeuro,
address _usdc,
address _oracle,
address _hedgerPool,
address _userPool,
address _timelock
) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address receiving roles |
_qeuro | address | QEURO token address |
_usdc | address | USDC token address |
_oracle | address | Oracle contract address |
_hedgerPool | address | HedgerPool contract address |
_userPool | address | UserPool contract address |
_timelock | address | Timelock contract address |
mintQEURO
Mints QEURO by swapping USDC
Converts USDC to QEURO using current oracle price with slippage protection
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function mintQEURO(uint256 usdcAmount, uint256 minQeuroOut) external;
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC to swap |
minQeuroOut | uint256 | Minimum QEURO expected (slippage protection) |
redeemQEURO
Redeems QEURO for USDC
Converts QEURO (18 decimals) to USDC (6 decimals) using oracle price
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function redeemQEURO(uint256 qeuroAmount, uint256 minUsdcOut) external;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to swap |
minUsdcOut | uint256 | Minimum USDC expected |
getVaultMetrics
Retrieves the vault's global metrics
Provides comprehensive vault statistics for monitoring and analysis
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getVaultMetrics()
external
view
returns (uint256 totalUsdcHeld_, uint256 totalMinted_, uint256 totalDebtValue);
Returns
| Name | Type | Description |
|---|---|---|
totalUsdcHeld_ | uint256 | Total USDC held in the vault |
totalMinted_ | uint256 | Total QEURO minted |
totalDebtValue | uint256 | Total debt value in USD |
calculateMintAmount
Computes QEURO mint amount for a USDC swap
Uses current oracle price to calculate QEURO equivalent without executing swap
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateMintAmount(uint256 usdcAmount) external view returns (uint256 qeuroAmount, uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | USDC to swap |
Returns
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Expected QEURO to mint (after fees) |
fee | uint256 | Protocol fee |
calculateRedeemAmount
Computes USDC redemption amount for a QEURO swap
Uses current oracle price to calculate USDC equivalent without executing swap
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateRedeemAmount(uint256 qeuroAmount) external view returns (uint256 usdcAmount, uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | QEURO to swap |
Returns
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | USDC returned after fees |
fee | uint256 | Protocol fee |
updateParameters
Updates vault parameters
Allows governance to update fee parameters for minting and redemption
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateParameters(uint256 _mintFee, uint256 _redemptionFee) external;
Parameters
| Name | Type | Description |
|---|---|---|
_mintFee | uint256 | New minting fee |
_redemptionFee | uint256 | New redemption fee |
updateOracle
Updates the oracle address
Allows governance to update the price oracle used for conversions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateOracle(address _oracle) external;
Parameters
| Name | Type | Description |
|---|---|---|
_oracle | address | New oracle address |
withdrawProtocolFees
Withdraws accumulated protocol fees
Allows governance to withdraw accumulated fees to specified address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function withdrawProtocolFees(address to) external;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Recipient address |
pause
Pauses the vault
Emergency function to pause all vault operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpauses the vault
Resumes all vault operations after emergency pause
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
recoverToken
Recovers ERC20 tokens sent by mistake
Allows governance to recover accidentally sent ERC20 tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, address to, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address |
to | address | Recipient |
amount | uint256 | Amount to transfer |
recoverETH
Recovers ETH sent by mistake
Allows governance to recover accidentally sent ETH
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
hasRole
Checks if an account has a specific role
Returns true if the account has been granted the role
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check roles
-
oracle: No oracle dependencies
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the account has the role |
getRoleAdmin
Gets the admin role for a given role
Returns the role that is the admin of the given role
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role admin
-
oracle: No oracle dependencies
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to get admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The admin role |
grantRole
Grants a role to an account
Can only be called by an account with the admin role
Notes:
-
security: Validates caller has admin role for the specified role
-
validation: Validates account is not address(0)
-
state-changes: Grants role to account
-
events: Emits RoleGranted event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to role admin
-
oracle: No oracle dependencies
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revokes a role from an account
Can only be called by an account with the admin role
Notes:
-
security: Validates caller has admin role for the specified role
-
validation: Validates account is not address(0)
-
state-changes: Revokes role from account
-
events: Emits RoleRevoked event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to role admin
-
oracle: No oracle dependencies
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounces a role from the caller
The caller gives up their own role
Notes:
-
security: Validates caller is renouncing their own role
-
validation: Validates callerConfirmation matches msg.sender
-
state-changes: Revokes role from caller
-
events: Emits RoleRevoked event
-
errors: Throws AccessControlBadConfirmation if callerConfirmation != msg.sender
-
reentrancy: Not protected - no external calls
-
access: Public - anyone can renounce their own roles
-
oracle: No oracle dependencies
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | Confirmation that the caller is renouncing their own role |
paused
Checks if the contract is paused
Returns true if the contract is currently paused
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check pause status
-
oracle: No oracle dependencies
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if paused, false otherwise |
upgradeTo
Upgrades the contract to a new implementation
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates caller has UPGRADER_ROLE
-
validation: Validates newImplementation is not address(0)
-
state-changes: Updates implementation address
-
events: Emits Upgraded event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks UPGRADER_ROLE
-
reentrancy: Not protected - no external calls
-
access: Restricted to UPGRADER_ROLE
-
oracle: No oracle dependencies
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
upgradeToAndCall
Upgrades the contract to a new implementation and calls a function
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates caller has UPGRADER_ROLE
-
validation: Validates newImplementation is not address(0)
-
state-changes: Updates implementation address and calls initialization
-
events: Emits Upgraded event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks UPGRADER_ROLE
-
reentrancy: Not protected - no external calls
-
access: Restricted to UPGRADER_ROLE
-
oracle: No oracle dependencies
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
data | bytes | Encoded function call data |
GOVERNANCE_ROLE
Returns the governance role identifier
Role that can update vault parameters and governance functions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function GOVERNANCE_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The governance role bytes32 identifier |
EMERGENCY_ROLE
Returns the emergency role identifier
Role that can pause the vault and perform emergency operations
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function EMERGENCY_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The emergency role bytes32 identifier |
UPGRADER_ROLE
Returns the upgrader role identifier
Role that can upgrade the contract implementation
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The upgrader role bytes32 identifier |
qeuro
Returns the QEURO token address
The euro-pegged stablecoin token managed by this vault
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token address
-
oracle: No oracle dependencies
function qeuro() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the QEURO token contract |
usdc
Returns the USDC token address
The collateral token used for minting QEURO
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token address
-
oracle: No oracle dependencies
function usdc() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the USDC token contract |
oracle
Returns the oracle contract address
The price oracle used for EUR/USD conversions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query oracle address
-
oracle: No oracle dependencies
function oracle() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the oracle contract |
mintFee
Returns the current minting fee
Fee charged when minting QEURO with USDC (in basis points)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query minting fee
-
oracle: No oracle dependencies
function mintFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The minting fee in basis points |
redemptionFee
Returns the current redemption fee
Fee charged when redeeming QEURO for USDC (in basis points)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query redemption fee
-
oracle: No oracle dependencies
function redemptionFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The redemption fee in basis points |
totalUsdcHeld
Returns the total USDC held in the vault
Total amount of USDC collateral backing QEURO
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total USDC held
-
oracle: No oracle dependencies
function totalUsdcHeld() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total USDC amount (6 decimals) |
totalMinted
Returns the total QEURO minted
Total amount of QEURO tokens in circulation
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total QEURO minted
-
oracle: No oracle dependencies
function totalMinted() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total QEURO amount (18 decimals) |
isProtocolCollateralized
Checks if the protocol is properly collateralized by hedgers
Public view function to check collateralization status
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check collateralization status
-
oracle: No oracle dependencies
function isProtocolCollateralized() external view returns (bool isCollateralized, uint256 totalMargin);
Returns
| Name | Type | Description |
|---|---|---|
isCollateralized | bool | True if protocol has active hedging positions |
totalMargin | uint256 | Total margin in HedgerPool (0 if not set) |
minCollateralizationRatioForMinting
Returns the minimum collateralization ratio for minting
Minimum ratio required for QEURO minting (in basis points)
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query minimum ratio
-
oracle: No oracle dependencies
function minCollateralizationRatioForMinting() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The minimum collateralization ratio in basis points |
userPool
Returns the UserPool contract address
The user pool contract managing user deposits
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query user pool address
-
oracle: No oracle dependencies
function userPool() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the UserPool contract |
addHedgerDeposit
Adds hedger USDC deposit to vault's total USDC reserves
Called by HedgerPool when hedgers open positions to unify USDC liquidity
Notes:
-
security: Validates caller is HedgerPool contract and amount is positive
-
validation: Validates amount > 0 and caller is authorized HedgerPool
-
state-changes: Updates totalUsdcHeld with hedger deposit amount
-
events: Emits HedgerDepositAdded with deposit details
-
errors: Throws "Vault: Only HedgerPool can call" if caller is not HedgerPool
-
errors: Throws "Vault: Amount must be positive" if amount is zero
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to HedgerPool contract only
-
oracle: No oracle dependencies
function addHedgerDeposit(uint256 usdcAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC deposited by hedger (6 decimals) |
withdrawHedgerDeposit
Withdraws hedger USDC deposit from vault's reserves
Called by HedgerPool when hedgers close positions to return their deposits
Notes:
-
security: Validates caller is HedgerPool, amount is positive, and sufficient reserves
-
validation: Validates amount > 0, caller is authorized, and totalUsdcHeld >= amount
-
state-changes: Updates totalUsdcHeld and transfers USDC to hedger
-
events: Emits HedgerDepositWithdrawn with withdrawal details
-
errors: Throws "Vault: Only HedgerPool can call" if caller is not HedgerPool
-
errors: Throws "Vault: Amount must be positive" if amount is zero
-
errors: Throws "Vault: Insufficient USDC reserves" if not enough USDC available
-
reentrancy: Protected by nonReentrant modifier
-
access: Restricted to HedgerPool contract only
-
oracle: No oracle dependencies
function withdrawHedgerDeposit(address hedger, uint256 usdcAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger receiving the USDC |
usdcAmount | uint256 | Amount of USDC to withdraw (6 decimals) |
getTotalUsdcAvailable
Gets the total USDC available for hedger deposits
Returns the current total USDC held in the vault for transparency
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public access - anyone can query total USDC held
-
oracle: No oracle dependencies
function getTotalUsdcAvailable() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | uint256 Total USDC held in vault (6 decimals) |
updateHedgerPool
Updates the HedgerPool address
Updates the HedgerPool contract address for hedger operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateHedgerPool(address _hedgerPool) external;
Parameters
| Name | Type | Description |
|---|---|---|
_hedgerPool | address | New HedgerPool address |
updateUserPool
Updates the UserPool address
Updates the UserPool contract address for user deposit tracking
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function updateUserPool(address _userPool) external;
Parameters
| Name | Type | Description |
|---|---|---|
_userPool | address | New UserPool address |
getPriceProtectionStatus
Gets the price protection status and parameters
Returns price protection configuration for monitoring
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public access - anyone can query price protection status
-
oracle: No oracle dependencies
function getPriceProtectionStatus()
external
view
returns (uint256 lastValidPrice, uint256 lastUpdateBlock, uint256 maxDeviation, uint256 minBlocks);
Returns
| Name | Type | Description |
|---|---|---|
lastValidPrice | uint256 | Last valid EUR/USD price |
lastUpdateBlock | uint256 | Block number of last price update |
maxDeviation | uint256 | Maximum allowed price deviation |
minBlocks | uint256 | Minimum blocks between price updates |
ISecureUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the SecureUpgradeable base contract
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the secure upgradeable contract
Sets up the secure upgradeable with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(address admin) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address that receives admin roles |
setTimelock
Set the timelock contract
Configures the timelock contract for secure upgrade management
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setTimelock(address _timelock) external;
Parameters
| Name | Type | Description |
|---|---|---|
_timelock | address | Address of the timelock contract |
toggleSecureUpgrades
Toggle secure upgrades
Enables or disables the secure upgrade mechanism
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function toggleSecureUpgrades(bool enabled) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable secure upgrades |
proposeUpgrade
Propose an upgrade through the timelock
Initiates a secure upgrade proposal with timelock delay
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function proposeUpgrade(address newImplementation, string calldata description, uint256 customDelay) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the upgrade |
customDelay | uint256 | Optional custom delay |
executeUpgrade
Execute an upgrade through the timelock
Executes a previously proposed upgrade after timelock delay
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function executeUpgrade(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
emergencyUpgrade
Emergency upgrade (bypasses timelock, requires emergency mode)
Performs immediate upgrade in emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyUpgrade(address newImplementation, string calldata description) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the emergency upgrade |
isUpgradePending
Check if an upgrade is pending
Checks if there's a pending upgrade for the given implementation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isUpgradePending(address implementation) external view returns (bool isPending);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
isPending | bool | Whether the upgrade is pending |
getPendingUpgrade
Get pending upgrade details
Returns detailed information about a pending upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPendingUpgrade(address implementation)
external
view
returns (ITimelockUpgradeable.PendingUpgrade memory upgrade);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
upgrade | ITimelockUpgradeable.PendingUpgrade | Pending upgrade details |
canExecuteUpgrade
Check if an upgrade can be executed
Checks if the timelock delay has passed and upgrade can be executed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function canExecuteUpgrade(address implementation) external view returns (bool canExecute);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
canExecute | bool | Whether the upgrade can be executed |
getUpgradeSecurityStatus
Get upgrade security status
Returns current security configuration for upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUpgradeSecurityStatus()
external
view
returns (address timelockAddress, bool secureUpgradesEnabled_, bool hasTimelock);
Returns
| Name | Type | Description |
|---|---|---|
timelockAddress | address | Address of the timelock contract |
secureUpgradesEnabled_ | bool | Whether secure upgrades are enabled |
hasTimelock | bool | Whether timelock is set |
emergencyDisableSecureUpgrades
Disable secure upgrades in emergency
Emergency function to disable secure upgrade mechanism
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyDisableSecureUpgrades() external;
enableSecureUpgrades
Enable secure upgrades after emergency
Re-enables secure upgrade mechanism after emergency
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function enableSecureUpgrades() external;
timelock
Returns the timelock contract address
Returns the ITimelockUpgradeable contract instance
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function timelock() external view returns (ITimelockUpgradeable);
Returns
| Name | Type | Description |
|---|---|---|
<none> | ITimelockUpgradeable | The timelock contract |
secureUpgradesEnabled
Returns whether secure upgrades are enabled
Indicates if the secure upgrade mechanism is active
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function secureUpgradesEnabled() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if secure upgrades are enabled |
UPGRADER_ROLE
Returns the upgrader role identifier
Role that can perform upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The upgrader role bytes32 identifier |
hasRole
Checks if an account has a specific role
Returns true if the account has been granted the role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the account has the role |
getRoleAdmin
Gets the admin role for a given role
Returns the role that is the admin of the given role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to get admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The admin role |
grantRole
Grants a role to an account
Can only be called by an account with the admin role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revokes a role from an account
Can only be called by an account with the admin role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounces a role from the caller
The caller gives up their own role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | Confirmation that the caller is renouncing their own role |
upgradeTo
Upgrades the contract to a new implementation
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
upgradeToAndCall
Upgrades the contract to a new implementation and calls a function
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
data | bytes | Encoded function call data |
ITimelockUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the secure upgrade mechanism with timelock and multi-sig requirements
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the timelock upgradeable contract
Sets up the timelock with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to initializer modifier
-
oracle: No oracle dependencies
function initialize(address admin) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address that receives admin and upgrade proposer roles |
proposeUpgrade
Propose an upgrade with timelock
Initiates a secure upgrade proposal with timelock delay and multi-sig requirements
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function proposeUpgrade(address newImplementation, string calldata description, uint256 customDelay) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the upgrade |
customDelay | uint256 | Optional custom delay (must be >= UPGRADE_DELAY) |
approveUpgrade
Approve a pending upgrade (multi-sig signer only)
Allows multi-sig signers to approve pending upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function approveUpgrade(address implementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to approve |
revokeUpgradeApproval
Revoke approval for a pending upgrade
Allows multi-sig signers to revoke their approval for pending upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeUpgradeApproval(address implementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to revoke approval for |
executeUpgrade
Execute an upgrade after timelock and multi-sig approval
Executes a previously approved upgrade after timelock delay
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function executeUpgrade(address implementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to execute |
cancelUpgrade
Cancel a pending upgrade (only proposer or admin)
Allows proposer or admin to cancel a pending upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function cancelUpgrade(address implementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation to cancel |
emergencyUpgrade
Emergency upgrade (bypasses timelock, requires emergency mode)
Performs immediate upgrade in emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyUpgrade(address newImplementation, string calldata description) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
description | string | Description of the emergency upgrade |
addMultisigSigner
Add a multi-sig signer
Adds a new multi-sig signer to the approval process
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function addMultisigSigner(address signer) external;
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer to add |
removeMultisigSigner
Remove a multi-sig signer
Removes a multi-sig signer from the approval process
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function removeMultisigSigner(address signer) external;
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer to remove |
toggleEmergencyMode
Toggle emergency mode
Enables or disables emergency mode for immediate upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function toggleEmergencyMode(bool enabled, string calldata reason) external;
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable emergency mode |
reason | string | Reason for the emergency mode change |
getPendingUpgrade
Get pending upgrade details
Returns detailed information about a pending upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPendingUpgrade(address implementation) external view returns (PendingUpgrade memory upgrade);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
upgrade | PendingUpgrade | Pending upgrade details |
canExecuteUpgrade
Check if an upgrade can be executed
Checks if the timelock delay has passed and upgrade can be executed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function canExecuteUpgrade(address implementation) external view returns (bool canExecute);
Parameters
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
canExecute | bool | Whether the upgrade can be executed |
hasUpgradeApproval
Get upgrade approval status for a signer
Checks if a specific signer has approved a specific upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasUpgradeApproval(address signer, address implementation) external view returns (bool approved);
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | Address of the signer |
implementation | address | Address of the implementation |
Returns
| Name | Type | Description |
|---|---|---|
approved | bool | Whether the signer has approved the upgrade |
getMultisigSigners
Get all multi-sig signers
Returns array of all authorized multi-sig signers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getMultisigSigners() external view returns (address[] memory signers);
Returns
| Name | Type | Description |
|---|---|---|
signers | address[] | Array of signer addresses |
pendingUpgrades
Returns pending upgrade details for an implementation
Maps implementation address to pending upgrade information
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pendingUpgrades(address)
external
view
returns (
address implementation,
uint256 proposedAt,
uint256 executableAt,
string memory description,
bool isEmergency,
address proposer
);
Parameters
| Name | Type | Description |
|---|---|---|
<none> | address |
Returns
| Name | Type | Description |
|---|---|---|
implementation | address | Address of the new implementation |
proposedAt | uint256 | Timestamp when upgrade was proposed |
executableAt | uint256 | Timestamp when upgrade can be executed |
description | string | Description of the upgrade |
isEmergency | bool | Whether this is an emergency upgrade |
proposer | address | Address of the proposer |
multisigSigners
Checks if an address is a multi-sig signer
Returns true if the address is authorized as a multi-sig signer
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function multisigSigners(address signer) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | The address to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the address is a multi-sig signer |
multisigSignerCount
Returns the total number of multi-sig signers
Returns the count of authorized multi-sig signers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function multisigSignerCount() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total number of multi-sig signers |
upgradeApprovals
Checks if a signer has approved an upgrade
Returns true if the signer has approved the specific upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeApprovals(address signer, address newImplementation) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
signer | address | The address of the signer |
newImplementation | address | The address of the new implementation |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the signer has approved the upgrade |
upgradeApprovalCount
Returns the number of approvals for an upgrade
Returns the count of approvals for a specific upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeApprovalCount(address newImplementation) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | The address of the new implementation |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Number of approvals for the upgrade |
emergencyMode
Returns whether emergency mode is enabled
Indicates if emergency mode is currently active
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyMode() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if emergency mode is enabled |
UPGRADE_DELAY
Returns the default upgrade delay
Minimum delay required for upgrades (in seconds)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADE_DELAY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Default upgrade delay in seconds |
MAX_UPGRADE_DELAY
Returns the maximum allowed upgrade delay
Maximum delay that can be set for upgrades (in seconds)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MAX_UPGRADE_DELAY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Maximum upgrade delay in seconds |
MIN_MULTISIG_APPROVALS
Returns the minimum required multi-sig approvals
Minimum number of approvals required to execute an upgrade
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MIN_MULTISIG_APPROVALS() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Minimum number of required approvals |
MAX_MULTISIG_SIGNERS
Returns the maximum allowed multi-sig signers
Maximum number of multi-sig signers that can be added
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MAX_MULTISIG_SIGNERS() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Maximum number of multi-sig signers |
UPGRADE_PROPOSER_ROLE
Returns the upgrade proposer role identifier
Role that can propose upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADE_PROPOSER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The upgrade proposer role bytes32 identifier |
UPGRADE_EXECUTOR_ROLE
Returns the upgrade executor role identifier
Role that can execute upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADE_EXECUTOR_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The upgrade executor role bytes32 identifier |
EMERGENCY_UPGRADER_ROLE
Returns the emergency upgrader role identifier
Role that can perform emergency upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function EMERGENCY_UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The emergency upgrader role bytes32 identifier |
MULTISIG_MANAGER_ROLE
Returns the multi-sig manager role identifier
Role that can manage multi-sig signers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MULTISIG_MANAGER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The multi-sig manager role bytes32 identifier |
Events
UpgradeProposed
event UpgradeProposed(
address indexed implementation,
uint256 proposedAt,
uint256 executableAt,
string description,
address indexed proposer
);
UpgradeApproved
event UpgradeApproved(address indexed implementation, address indexed signer, uint256 approvalCount);
UpgradeExecuted
event UpgradeExecuted(address indexed implementation, address indexed executor, uint256 executedAt);
UpgradeCancelled
event UpgradeCancelled(address indexed implementation, address indexed canceller);
MultisigSignerAdded
event MultisigSignerAdded(address indexed signer);
MultisigSignerRemoved
event MultisigSignerRemoved(address indexed signer);
EmergencyModeToggled
event EmergencyModeToggled(bool enabled, string reason);
Structs
PendingUpgrade
struct PendingUpgrade {
address implementation;
uint256 proposedAt;
uint256 executableAt;
string description;
bool isEmergency;
address proposer;
}
IUserPool
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the UserPool managing deposits, staking, and yield
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the user pool
Sets up the user pool with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(
address admin,
address _qeuro,
address _usdc,
address _vault,
address _yieldShift,
address _timelock,
address _treasury
) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address |
_qeuro | address | QEURO token address |
_usdc | address | USDC token address |
_vault | address | Vault contract address |
_yieldShift | address | YieldShift contract address |
_timelock | address | Timelock contract address |
_treasury | address | Treasury address |
deposit
Deposit USDC to mint QEURO and join the pool
Converts USDC to QEURO and adds user to the pool for yield distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function deposit(uint256 usdcAmount, uint256 minQeuroOut) external returns (uint256 qeuroMinted);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC to deposit |
minQeuroOut | uint256 | Minimum QEURO expected (slippage protection) |
Returns
| Name | Type | Description |
|---|---|---|
qeuroMinted | uint256 | Amount of QEURO minted to user |
withdraw
Withdraw USDC by burning QEURO
Converts QEURO back to USDC and removes user from the pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function withdraw(uint256 qeuroAmount, uint256 minUsdcOut) external returns (uint256 usdcReceived);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to burn |
minUsdcOut | uint256 | Minimum USDC expected |
Returns
| Name | Type | Description |
|---|---|---|
usdcReceived | uint256 | USDC received by user |
stake
Stake QEURO to earn staking rewards
Locks QEURO tokens to earn staking rewards with cooldown period
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function stake(uint256 qeuroAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to stake |
requestUnstake
Request to unstake staked QEURO (starts cooldown)
Initiates unstaking process with cooldown period before final withdrawal
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function requestUnstake(uint256 qeuroAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount to unstake |
unstake
Finalize unstake after cooldown
Completes the unstaking process after cooldown period has passed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unstake() external;
claimStakingRewards
Claim accumulated staking rewards
Claims all accumulated staking rewards for the caller
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimStakingRewards() external returns (uint256 rewardAmount);
Returns
| Name | Type | Description |
|---|---|---|
rewardAmount | uint256 | Amount of rewards claimed |
distributeYield
Distribute new yield to the user pool
Distributes yield to all pool participants based on their share
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function distributeYield(uint256 yieldAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield in USDC equivalent |
getUserDeposits
Get a user's total deposits (USDC equivalent)
Returns the total USDC equivalent value of user's deposits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserDeposits(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total deposits in USDC equivalent |
getUserStakes
Get a user's total staked QEURO
Returns the total amount of QEURO staked by the user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserStakes(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total staked QEURO amount |
getUserPendingRewards
Get a user's pending staking rewards
Returns the amount of staking rewards available to claim
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserPendingRewards(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Pending staking rewards amount |
getUserInfo
Get detailed user info
Returns comprehensive user information including balances and staking data
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserInfo(address user)
external
view
returns (
uint256 qeuroBalance,
uint256 stakedAmount,
uint256 pendingRewards,
uint256 depositHistory,
uint256 lastStakeTime,
uint256 unstakeRequestTime,
uint256 unstakeAmount
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address to query |
Returns
| Name | Type | Description |
|---|---|---|
qeuroBalance | uint256 | QEURO balance from deposits |
stakedAmount | uint256 | QEURO amount staked |
pendingRewards | uint256 | Pending staking rewards |
depositHistory | uint256 | Total historical deposits |
lastStakeTime | uint256 | Timestamp of last stake |
unstakeRequestTime | uint256 | Timestamp of unstake request |
unstakeAmount | uint256 | Amount currently requested to unstake |
getTotalDeposits
Total USDC-equivalent deposits in the pool
Returns the total value of all deposits in the pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTotalDeposits() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total deposits in USDC equivalent |
getTotalStakes
Total QEURO staked in the pool
Returns the total amount of QEURO staked by all users
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTotalStakes() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total staked QEURO amount |
getPoolMetrics
Summary pool metrics
Returns comprehensive pool statistics and metrics
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPoolMetrics()
external
view
returns (uint256 totalUsers_, uint256 averageDeposit, uint256 stakingRatio, uint256 poolTVL);
Returns
| Name | Type | Description |
|---|---|---|
totalUsers_ | uint256 | Number of users |
averageDeposit | uint256 | Average deposit per user |
stakingRatio | uint256 | Staking ratio (bps) |
poolTVL | uint256 | Total value locked |
getStakingAPY
Current staking APY (bps)
Returns the current annual percentage yield for staking
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getStakingAPY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current staking APY in basis points |
getDepositAPY
Current base deposit APY (bps)
Returns the current annual percentage yield for deposits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getDepositAPY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current deposit APY in basis points |
calculateProjectedRewards
Calculate projected rewards for a staking duration
Calculates expected rewards for a given staking amount and duration
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateProjectedRewards(uint256 qeuroAmount, uint256 duration)
external
view
returns (uint256 projectedRewards);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | QEURO amount |
duration | uint256 | Duration in seconds |
Returns
| Name | Type | Description |
|---|---|---|
projectedRewards | uint256 | Expected rewards amount |
updateStakingParameters
Update staking parameters
Allows governance to update staking configuration parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateStakingParameters(
uint256 _stakingAPY,
uint256 _depositAPY,
uint256 _minStakeAmount,
uint256 _unstakingCooldown
) external;
Parameters
| Name | Type | Description |
|---|---|---|
_stakingAPY | uint256 | New staking APY (bps) |
_depositAPY | uint256 | New base deposit APY (bps) |
_minStakeAmount | uint256 | Minimum stake amount |
_unstakingCooldown | uint256 | Unstaking cooldown in seconds |
setPoolFees
Set pool fees
Allows governance to update fee parameters for the pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setPoolFees(uint256 _depositFee, uint256 _withdrawalFee, uint256 _performanceFee) external;
Parameters
| Name | Type | Description |
|---|---|---|
_depositFee | uint256 | Deposit fee (bps) |
_withdrawalFee | uint256 | Withdrawal fee (bps) |
_performanceFee | uint256 | Performance fee (bps) |
emergencyUnstake
Emergency unstake for a user by admin
Allows admin to emergency unstake for a user bypassing cooldown
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyUnstake(address user) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
pause
Pause user pool operations
Emergency function to pause all pool operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpause user pool operations
Resumes all pool operations after emergency pause
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
getPoolConfig
Pool configuration snapshot
Returns current pool configuration parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPoolConfig()
external
view
returns (
uint256 _stakingAPY,
uint256 _depositAPY,
uint256 _minStakeAmount,
uint256 _unstakingCooldown,
uint256 _depositFee,
uint256 _withdrawalFee,
uint256 _performanceFee
);
Returns
| Name | Type | Description |
|---|---|---|
_stakingAPY | uint256 | Staking APY (bps) |
_depositAPY | uint256 | Deposit APY (bps) |
_minStakeAmount | uint256 | Minimum stake amount |
_unstakingCooldown | uint256 | Unstaking cooldown seconds |
_depositFee | uint256 | Deposit fee (bps) |
_withdrawalFee | uint256 | Withdrawal fee (bps) |
_performanceFee | uint256 | Performance fee (bps) |
isPoolActive
Whether the pool operations are active (not paused)
Returns true if the pool is not paused and operations are active
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isPoolActive() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if pool operations are active |
hasRole
Checks if an account has a specific role
Returns true if the account has been granted the role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the account has the role |
getRoleAdmin
Gets the admin role for a given role
Returns the role that is the admin of the given role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to get admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The admin role |
grantRole
Grants a role to an account
Can only be called by an account with the admin role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revokes a role from an account
Can only be called by an account with the admin role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounces a role from the caller
The caller gives up their own role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | Confirmation that the caller is renouncing their own role |
paused
Checks if the contract is paused
Returns true if the contract is currently paused
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if paused, false otherwise |
upgradeTo
Upgrades the contract to a new implementation
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
upgradeToAndCall
Upgrades the contract to a new implementation and calls a function
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
data | bytes | Encoded function call data |
GOVERNANCE_ROLE
Returns the governance role identifier
Role that can update pool parameters and governance functions
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function GOVERNANCE_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The governance role bytes32 identifier |
EMERGENCY_ROLE
Returns the emergency role identifier
Role that can pause the pool and perform emergency operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function EMERGENCY_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The emergency role bytes32 identifier |
UPGRADER_ROLE
Returns the upgrader role identifier
Role that can upgrade the contract implementation
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The upgrader role bytes32 identifier |
BLOCKS_PER_DAY
Returns the number of blocks per day
Used for reward calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function BLOCKS_PER_DAY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Number of blocks per day |
MAX_REWARD_PERIOD
Returns the maximum reward period
Maximum duration for reward calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function MAX_REWARD_PERIOD() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Maximum reward period in seconds |
qeuro
Returns the QEURO token address
The euro-pegged stablecoin token used in the pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function qeuro() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the QEURO token contract |
usdc
Returns the USDC token address
The collateral token used for deposits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function usdc() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the USDC token contract |
vault
Returns the vault contract address
The vault contract used for minting/burning QEURO
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function vault() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the vault contract |
yieldShift
Returns the yield shift contract address
The contract managing yield distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function yieldShift() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | Address of the yield shift contract |
stakingAPY
Returns the current staking APY
Annual percentage yield for staking (in basis points)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function stakingAPY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current staking APY in basis points |
depositAPY
Returns the current deposit APY
Annual percentage yield for deposits (in basis points)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function depositAPY() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current deposit APY in basis points |
minStakeAmount
Returns the minimum stake amount
Minimum amount of QEURO required to stake
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function minStakeAmount() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Minimum stake amount in QEURO |
unstakingCooldown
Returns the unstaking cooldown period
Time in seconds before unstaking can be completed
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unstakingCooldown() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Unstaking cooldown in seconds |
depositFee
Returns the deposit fee
Fee charged on deposits (in basis points)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function depositFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Deposit fee in basis points |
withdrawalFee
Returns the withdrawal fee
Fee charged on withdrawals (in basis points)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function withdrawalFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Withdrawal fee in basis points |
performanceFee
Returns the performance fee
Fee charged on performance (in basis points)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function performanceFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Performance fee in basis points |
totalDeposits
Returns the total deposits
Total USDC equivalent value of all deposits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalDeposits() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total deposits in USDC equivalent |
totalStakes
Returns the total stakes
Total amount of QEURO staked by all users
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalStakes() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total staked QEURO amount |
totalUsers
Returns the total number of users
Number of users who have deposited or staked
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalUsers() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total number of users |
accumulatedYieldPerShare
Returns the accumulated yield per share
Used for calculating user rewards
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function accumulatedYieldPerShare() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Accumulated yield per share |
lastYieldDistribution
Returns the last yield distribution timestamp
Timestamp of the last yield distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function lastYieldDistribution() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Last yield distribution timestamp |
totalYieldDistributed
Returns the total yield distributed
Total amount of yield distributed to users
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function totalYieldDistributed() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total yield distributed |
userLastRewardBlock
Returns the last reward block for a user
Last block when user rewards were calculated
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function userLastRewardBlock(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Last reward block number |
hasDeposited
Checks if a user has deposited
Returns true if the user has ever deposited
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasDeposited(address user) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if user has deposited |
userInfo
Returns detailed user information
Returns comprehensive user data including balances and staking info
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function userInfo(address user)
external
view
returns (
uint256 qeuroBalance,
uint256 stakedAmount,
uint256 pendingRewards,
uint256 depositHistory,
uint256 lastStakeTime,
uint256 unstakeRequestTime,
uint256 unstakeAmount
);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | The user address |
Returns
| Name | Type | Description |
|---|---|---|
qeuroBalance | uint256 | QEURO balance from deposits |
stakedAmount | uint256 | QEURO amount staked |
pendingRewards | uint256 | Pending staking rewards |
depositHistory | uint256 | Total historical deposits |
lastStakeTime | uint256 | Timestamp of last stake |
unstakeRequestTime | uint256 | Timestamp of unstake request |
unstakeAmount | uint256 | Amount currently requested to unstake |
recoverToken
Recovers ERC20 tokens sent by mistake
Allows governance to recover accidentally sent ERC20 tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address |
amount | uint256 | Amount to transfer |
recoverETH
Recovers ETH sent by mistake
Allows governance to recover accidentally sent ETH
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
IYieldShift
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for YieldShift dynamic yield redistribution
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the YieldShift contract
Sets up the yield shift contract with initial configuration and assigns roles to admin
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function initialize(
address admin,
address _usdc,
address _userPool,
address _hedgerPool,
address _aaveVault,
address _stQEURO,
address _timelock,
address _treasury
) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address |
_usdc | address | USDC token address |
_userPool | address | UserPool address |
_hedgerPool | address | HedgerPool address |
_aaveVault | address | Aave vault address |
_stQEURO | address | stQEURO token address |
_timelock | address | Timelock contract address |
_treasury | address | Treasury address |
updateYieldDistribution
Update yield distribution according to pool balances
Recalculates and updates yield distribution based on current pool balances
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateYieldDistribution() external;
addYield
Add new yield to be distributed
Adds new yield from various sources to the distribution pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function addYield(uint256 yieldAmount, bytes32 source) external;
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Yield amount in USDC equivalent |
source | bytes32 | Source identifier (e.g., "aave", "fees") |
claimUserYield
Claim pending yield for a user
Claims all pending yield for a specific user from the user pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimUserYield(address user) external returns (uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user |
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Yield amount claimed |
claimHedgerYield
Claim pending yield for a hedger
Claims all pending yield for a specific hedger from the hedger pool
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimHedgerYield(address hedger) external returns (uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger |
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Yield amount claimed |
getCurrentYieldShift
Current yield shift percentage (bps)
Returns the current yield shift percentage in basis points
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getCurrentYieldShift() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current yield shift percentage in basis points |
getUserPendingYield
Pending yield amounts
Returns the amount of pending yield for a specific user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getUserPendingYield(address user) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Pending yield amount for the user |
getHedgerPendingYield
Pending yield amounts
Returns the amount of pending yield for a specific hedger
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getHedgerPendingYield(address hedger) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Pending yield amount for the hedger |
getTotalYieldGenerated
Total yield generated to date
Returns the total amount of yield generated since inception
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTotalYieldGenerated() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Total yield generated amount |
getYieldDistributionBreakdown
Yield distribution breakdown
Returns the current yield allocation breakdown between users and hedgers
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldDistributionBreakdown() external view returns (uint256 userAllocation, uint256 hedgerAllocation);
Returns
| Name | Type | Description |
|---|---|---|
userAllocation | uint256 | Current allocation to users |
hedgerAllocation | uint256 | Current allocation to hedgers |
getPoolMetrics
Current pool metrics
Returns current pool size metrics and ratios
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPoolMetrics() external view returns (uint256 userPoolSize, uint256 hedgerPoolSize, uint256 poolRatio);
Returns
| Name | Type | Description |
|---|---|---|
userPoolSize | uint256 | User pool size |
hedgerPoolSize | uint256 | Hedger pool size |
poolRatio | uint256 | Ratio (bps) user/hedger |
calculateOptimalYieldShift
Calculate optimal yield shift based on current metrics
Calculates the optimal yield shift based on current pool metrics
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateOptimalYieldShift() external view returns (uint256 optimalShift, uint256 currentDeviation);
Returns
| Name | Type | Description |
|---|---|---|
optimalShift | uint256 | Optimal shift (bps) |
currentDeviation | uint256 | Current deviation from optimal |
getYieldSources
Yield source amounts
Returns yield amounts from different sources
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldSources()
external
view
returns (uint256 aaveYield, uint256 protocolFees, uint256 interestDifferential, uint256 otherSources);
Returns
| Name | Type | Description |
|---|---|---|
aaveYield | uint256 | Aave yield amount |
protocolFees | uint256 | Protocol fees amount |
interestDifferential | uint256 | Interest differential amount |
otherSources | uint256 | Other sources amount |
getHistoricalYieldShift
Historical yield shift statistics for a period
Returns historical yield shift statistics for a specified time period
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getHistoricalYieldShift(uint256 period)
external
view
returns (uint256 averageShift, uint256 maxShift, uint256 minShift, uint256 volatility);
Parameters
| Name | Type | Description |
|---|---|---|
period | uint256 | Time period in seconds |
Returns
| Name | Type | Description |
|---|---|---|
averageShift | uint256 | Average shift over period |
maxShift | uint256 | Maximum shift over period |
minShift | uint256 | Minimum shift over period |
volatility | uint256 | Volatility measure |
getYieldPerformanceMetrics
Yield performance metrics
Returns comprehensive yield performance metrics
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldPerformanceMetrics()
external
view
returns (
uint256 totalYieldDistributed_,
uint256 averageUserYield,
uint256 averageHedgerYield,
uint256 yieldEfficiency
);
Returns
| Name | Type | Description |
|---|---|---|
totalYieldDistributed_ | uint256 | Total distributed |
averageUserYield | uint256 | Average user yield |
averageHedgerYield | uint256 | Average hedger yield |
yieldEfficiency | uint256 | Yield efficiency percentage |
setYieldShiftParameters
Update yield shift parameters
Allows governance to update yield shift configuration parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setYieldShiftParameters(uint256 _baseYieldShift, uint256 _maxYieldShift, uint256 _adjustmentSpeed) external;
Parameters
| Name | Type | Description |
|---|---|---|
_baseYieldShift | uint256 | Base allocation (bps) |
_maxYieldShift | uint256 | Max allocation (bps) |
_adjustmentSpeed | uint256 | Adjustment speed (bps) |
setTargetPoolRatio
Set the target pool ratio (bps)
Sets the target ratio between user and hedger pools
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function setTargetPoolRatio(uint256 _targetPoolRatio) external;
Parameters
| Name | Type | Description |
|---|---|---|
_targetPoolRatio | uint256 | Target ratio |
authorizeYieldSource
Authorize a yield source for specific yield type
Authorizes a yield source for a specific type of yield
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function authorizeYieldSource(address source, bytes32 yieldType) external;
Parameters
| Name | Type | Description |
|---|---|---|
source | address | Address of the yield source |
yieldType | bytes32 | Type of yield this source is authorized for |
revokeYieldSource
Revoke authorization for a yield source
Revokes authorization for a yield source
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeYieldSource(address source) external;
Parameters
| Name | Type | Description |
|---|---|---|
source | address | Address of the yield source to revoke |
isYieldSourceAuthorized
Check if an address is authorized for a specific yield type
Checks if an address is authorized for a specific yield type
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isYieldSourceAuthorized(address source, bytes32 yieldType) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
source | address | Address to check |
yieldType | bytes32 | Yield type to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if authorized |
updateYieldAllocation
Update yield allocation for a participant
Updates yield allocation for a specific participant
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateYieldAllocation(address user, uint256 amount, bool isUser) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of participant |
amount | uint256 | Amount to add/subtract |
isUser | bool | True if user pool, false if hedger pool |
emergencyYieldDistribution
Emergency manual yield distribution
Performs emergency manual yield distribution bypassing normal logic
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyYieldDistribution(uint256 userAmount, uint256 hedgerAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
userAmount | uint256 | Amount to users |
hedgerAmount | uint256 | Amount to hedgers |
pauseYieldDistribution
Pause yield distribution operations
Emergency function to pause all yield distribution operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pauseYieldDistribution() external;
resumeYieldDistribution
Resume yield distribution operations
Resumes yield distribution operations after emergency pause
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function resumeYieldDistribution() external;
getYieldShiftConfig
YieldShift configuration snapshot
Returns current yield shift configuration parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getYieldShiftConfig()
external
view
returns (uint256 baseShift, uint256 maxShift, uint256 adjustmentSpeed_, uint256 lastUpdate);
Returns
| Name | Type | Description |
|---|---|---|
baseShift | uint256 | Base shift (bps) |
maxShift | uint256 | Max shift (bps) |
adjustmentSpeed_ | uint256 | Adjustment speed (bps) |
lastUpdate | uint256 | Last update timestamp |
isYieldDistributionActive
Whether yield distribution is active (not paused)
Returns true if yield distribution is not paused and operations are active
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isYieldDistributionActive() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if yield distribution is active |
checkAndUpdateYieldDistribution
Check if an update to yield distribution is needed and apply if so
Checks if yield distribution needs updating and applies changes if necessary
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function checkAndUpdateYieldDistribution() external;
updateLastDepositTime
Update the last deposit time for a user (for TWAP calculations)
Updates the last deposit time for a user, called by user pool on deposits
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateLastDepositTime(address user) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | Address of the user |
forceUpdateYieldDistribution
Force update yield distribution (governance only)
This function allows governance to force an update to yield distribution
Only callable by governance role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function forceUpdateYieldDistribution() external;
hasRole
Checks if an account has a specific role
Returns true if the account has been granted the role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the account has the role |
getRoleAdmin
Gets the admin role for a given role
Returns the role that is the admin of the given role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to get admin for |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The admin role |
grantRole
Grants a role to an account
Can only be called by an account with the admin role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revokes a role from an account
Can only be called by an account with the admin role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounces a role from the caller
The caller gives up their own role
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | Confirmation that the caller is renouncing their own role |
paused
Checks if the contract is paused
Returns true if the contract is currently paused
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if paused, false otherwise |
upgradeTo
Upgrades the contract to a new implementation
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
upgradeToAndCall
Upgrades the contract to a new implementation and calls a function
Can only be called by accounts with UPGRADER_ROLE
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation contract |
data | bytes | Encoded function call data |
recoverToken
Recovers ERC20 tokens sent by mistake
Allows governance to recover accidentally sent ERC20 tokens
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address |
amount | uint256 | Amount to transfer |
recoverETH
Recovers ETH sent by mistake
Allows governance to recover accidentally sent ETH
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
IstQEURO
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Interface for the stQEURO yield-bearing wrapper token (yield accrual mechanism)
Note: security-contact: team@quantillon.money
Functions
initialize
Initializes the stQEURO token
Sets up the stQEURO token with initial configuration and assigns roles to admin
Notes:
-
security: Validates all addresses are not zero and initializes roles
-
validation: Validates admin is not address(0), all contract addresses are valid
-
state-changes: Initializes roles, sets contract addresses, enables staking
-
events: Emits role assignment and initialization events
-
errors: Throws InvalidAddress if any address is zero
-
reentrancy: Protected by onlyInitializing modifier
-
access: Internal function - only callable during initialization
-
oracle: No oracle dependencies
function initialize(
address admin,
address _qeuro,
address _yieldShift,
address _usdc,
address _treasury,
address timelock
) external;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address |
_qeuro | address | QEURO token address |
_yieldShift | address | YieldShift contract address |
_usdc | address | USDC token address |
_treasury | address | Treasury address |
timelock | address | Timelock contract address |
stake
Stake QEURO to receive stQEURO
Converts QEURO to stQEURO at current exchange rate with yield accrual
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function stake(uint256 qeuroAmount) external returns (uint256 stQEUROAmount);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO to stake |
Returns
| Name | Type | Description |
|---|---|---|
stQEUROAmount | uint256 | Amount of stQEURO received |
unstake
Unstake QEURO by burning stQEURO
Converts stQEURO back to QEURO at current exchange rate
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unstake(uint256 stQEUROAmount) external returns (uint256 qeuroAmount);
Parameters
| Name | Type | Description |
|---|---|---|
stQEUROAmount | uint256 | Amount of stQEURO to burn |
Returns
| Name | Type | Description |
|---|---|---|
qeuroAmount | uint256 | Amount of QEURO received |
batchStake
Batch stake QEURO amounts
Efficiently stakes multiple QEURO amounts in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchStake(uint256[] calldata qeuroAmounts) external returns (uint256[] memory stQEUROAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO amounts |
Returns
| Name | Type | Description |
|---|---|---|
stQEUROAmounts | uint256[] | Array of stQEURO minted |
batchUnstake
Batch unstake stQEURO amounts
Efficiently unstakes multiple stQEURO amounts in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchUnstake(uint256[] calldata stQEUROAmounts) external returns (uint256[] memory qeuroAmounts);
Parameters
| Name | Type | Description |
|---|---|---|
stQEUROAmounts | uint256[] | Array of stQEURO amounts |
Returns
| Name | Type | Description |
|---|---|---|
qeuroAmounts | uint256[] | Array of QEURO returned |
batchTransfer
Batch transfer stQEURO to multiple recipients
Efficiently transfers stQEURO to multiple recipients in a single transaction
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function batchTransfer(address[] calldata recipients, uint256[] calldata amounts) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
recipients | address[] | Array of recipient addresses |
amounts | uint256[] | Array of amounts to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | success True if all transfers succeeded |
distributeYield
Distribute yield to stQEURO holders (increases exchange rate)
Distributes yield by increasing the exchange rate for all stQEURO holders
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function distributeYield(uint256 yieldAmount) external;
Parameters
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield in USDC |
claimYield
Claim accumulated yield for a user (in USDC)
Claims the user's accumulated yield and transfers it to their address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function claimYield() external returns (uint256 yieldAmount);
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Amount of yield claimed |
getPendingYield
Get pending yield for a user (in USDC)
Returns the amount of yield available for a specific user to claim
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getPendingYield(address user) external view returns (uint256 yieldAmount);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
yieldAmount | uint256 | Pending yield amount |
getExchangeRate
Get current exchange rate between QEURO and stQEURO
Returns the current exchange rate used for staking/unstaking operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getExchangeRate() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | exchangeRate Current exchange rate (18 decimals) |
getTVL
Get total value locked in stQEURO
Returns the total value locked in the stQEURO system
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getTVL() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | tvl Total value locked (18 decimals) |
getQEUROEquivalent
Get user's QEURO equivalent balance
Returns the QEURO equivalent value of a user's stQEURO balance
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getQEUROEquivalent(address user) external view returns (uint256 qeuroEquivalent);
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address |
Returns
| Name | Type | Description |
|---|---|---|
qeuroEquivalent | uint256 | QEURO equivalent of stQEURO balance |
getStakingStats
Get staking statistics
Returns comprehensive staking statistics and metrics
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function getStakingStats()
external
view
returns (
uint256 totalStQEUROSupply,
uint256 totalQEUROUnderlying,
uint256 currentExchangeRate,
uint256 _totalYieldEarned,
uint256 apy
);
Returns
| Name | Type | Description |
|---|---|---|
totalStQEUROSupply | uint256 | Total stQEURO supply |
totalQEUROUnderlying | uint256 | Total QEURO underlying |
currentExchangeRate | uint256 | Current exchange rate |
_totalYieldEarned | uint256 | Total yield earned |
apy | uint256 | Annual percentage yield |
updateYieldParameters
Update yield parameters
Updates yield-related parameters with security checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateYieldParameters(uint256 _yieldFee, uint256 _minYieldThreshold, uint256 _maxUpdateFrequency) external;
Parameters
| Name | Type | Description |
|---|---|---|
_yieldFee | uint256 | New yield fee percentage |
_minYieldThreshold | uint256 | New minimum yield threshold |
_maxUpdateFrequency | uint256 | New maximum update frequency |
updateTreasury
Update treasury address
Updates the treasury address for yield distribution
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateTreasury(address _treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
pause
Pause the contract
Pauses all stQEURO operations for emergency situations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function pause() external;
unpause
Unpause the contract
Resumes all stQEURO operations after being paused
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function unpause() external;
emergencyWithdraw
Emergency withdrawal of QEURO
Allows emergency withdrawal of QEURO for a specific user
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function emergencyWithdraw(address user) external;
Parameters
| Name | Type | Description |
|---|---|---|
user | address | User address to withdraw for |
recoverToken
Recover accidentally sent tokens
Allows recovery of ERC20 tokens accidentally sent to the contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to transfer |
recoverETH
Recover accidentally sent ETH
Allows recovery of ETH accidentally sent to the contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external;
name
Returns the name of the token
Returns the token name for display purposes
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token name
-
oracle: No oracle dependencies
function name() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | The token name |
symbol
Returns the symbol of the token
Returns the token symbol for display purposes
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token symbol
-
oracle: No oracle dependencies
function symbol() external view returns (string memory);
Returns
| Name | Type | Description |
|---|---|---|
<none> | string | The token symbol |
decimals
Returns the decimals of the token
Returns the number of decimals used for token amounts
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token decimals
-
oracle: No oracle dependencies
function decimals() external view returns (uint8);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | The number of decimals |
totalSupply
Returns the total supply of the token
Returns the total amount of tokens in existence
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total supply
-
oracle: No oracle dependencies
function totalSupply() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total supply |
balanceOf
Returns the balance of an account
Returns the token balance of the specified account
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query account balance
-
oracle: No oracle dependencies
function balanceOf(address account) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The balance of the account |
transfer
Transfers tokens to a recipient
Transfers the specified amount of tokens to the recipient
Notes:
-
security: Validates recipient is not address(0) and caller has sufficient balance
-
validation: Validates to != address(0) and amount <= balanceOf(msg.sender)
-
state-changes: Updates balances of sender and recipient
-
events: Emits Transfer event
-
errors: Throws InsufficientBalance if amount > balance
-
reentrancy: Not protected - no external calls
-
access: Public - any token holder can transfer
-
oracle: No oracle dependencies
function transfer(address to, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
to | address | The recipient address |
amount | uint256 | The amount to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the transfer succeeded |
allowance
Returns the allowance for a spender
Returns the amount of tokens that the spender is allowed to spend
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query allowance
-
oracle: No oracle dependencies
function allowance(address owner, address spender) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
owner | address | The owner address |
spender | address | The spender address |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The allowance amount |
approve
Approves a spender to spend tokens
Sets the allowance for the spender to spend tokens on behalf of the caller
Notes:
-
security: Validates spender is not address(0)
-
validation: Validates spender != address(0)
-
state-changes: Updates allowance mapping
-
events: Emits Approval event
-
errors: No errors thrown - safe function
-
reentrancy: Not protected - no external calls
-
access: Public - any token holder can approve
-
oracle: No oracle dependencies
function approve(address spender, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
spender | address | The spender address |
amount | uint256 | The amount to approve |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the approval succeeded |
transferFrom
Transfers tokens from one account to another
Transfers tokens from the from account to the to account
Notes:
-
security: Validates recipient is not address(0) and sufficient allowance
-
validation: Validates to != address(0) and amount <= allowance(from, msg.sender)
-
state-changes: Updates balances and allowance
-
events: Emits Transfer event
-
errors: Throws InsufficientAllowance if amount > allowance
-
reentrancy: Not protected - no external calls
-
access: Public - any approved spender can transfer
-
oracle: No oracle dependencies
function transferFrom(address from, address to, uint256 amount) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
from | address | The sender address |
to | address | The recipient address |
amount | uint256 | The amount to transfer |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the transfer succeeded |
hasRole
Checks if an account has a specific role
Returns true if the account has been granted the role
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check roles
-
oracle: No oracle dependencies
function hasRole(bytes32 role, address account) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
account | address | The account to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the account has the role |
getRoleAdmin
Returns the admin role for a role
Returns the role that is the admin of the given role
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role admin
-
oracle: No oracle dependencies
function getRoleAdmin(bytes32 role) external view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The admin role |
grantRole
Grants a role to an account
Grants the specified role to the account
Notes:
-
security: Validates caller has admin role for the specified role
-
validation: Validates account is not address(0)
-
state-changes: Grants role to account
-
events: Emits RoleGranted event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to role admin
-
oracle: No oracle dependencies
function grantRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to grant |
account | address | The account to grant the role to |
revokeRole
Revokes a role from an account
Revokes the specified role from the account
Notes:
-
security: Validates caller has admin role for the specified role
-
validation: Validates account is not address(0)
-
state-changes: Revokes role from account
-
events: Emits RoleRevoked event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to role admin
-
oracle: No oracle dependencies
function revokeRole(bytes32 role, address account) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to revoke |
account | address | The account to revoke the role from |
renounceRole
Renounces a role
Renounces the specified role from the caller
Notes:
-
security: Validates caller is renouncing their own role
-
validation: Validates callerConfirmation == msg.sender
-
state-changes: Removes role from caller
-
events: Emits RoleRenounced event
-
errors: Throws AccessControlInvalidCaller if callerConfirmation != msg.sender
-
reentrancy: Not protected - no external calls
-
access: Public - anyone can renounce their own roles
-
oracle: No oracle dependencies
function renounceRole(bytes32 role, address callerConfirmation) external;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to renounce |
callerConfirmation | address | The caller confirmation |
paused
Returns the paused state
Returns true if the contract is paused
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check pause status
-
oracle: No oracle dependencies
function paused() external view returns (bool);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if paused |
upgradeTo
Upgrades the implementation
Upgrades the contract to a new implementation
Notes:
-
security: Validates caller has UPGRADER_ROLE
-
validation: Validates newImplementation is not address(0)
-
state-changes: Updates implementation address
-
events: Emits Upgraded event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks UPGRADER_ROLE
-
reentrancy: Not protected - no external calls
-
access: Restricted to UPGRADER_ROLE
-
oracle: No oracle dependencies
function upgradeTo(address newImplementation) external;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | The new implementation address |
upgradeToAndCall
Upgrades the implementation and calls a function
Upgrades the contract and calls a function on the new implementation
Notes:
-
security: Validates caller has UPGRADER_ROLE
-
validation: Validates newImplementation is not address(0)
-
state-changes: Updates implementation address and calls initialization
-
events: Emits Upgraded event
-
errors: Throws AccessControlUnauthorizedAccount if caller lacks UPGRADER_ROLE
-
reentrancy: Not protected - no external calls
-
access: Restricted to UPGRADER_ROLE
-
oracle: No oracle dependencies
function upgradeToAndCall(address newImplementation, bytes memory data) external payable;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | The new implementation address |
data | bytes | The function call data |
GOVERNANCE_ROLE
Returns the governance role
Returns the role identifier for governance functions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function GOVERNANCE_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The governance role |
YIELD_MANAGER_ROLE
Returns the yield manager role
Returns the role identifier for yield management functions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function YIELD_MANAGER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The yield manager role |
EMERGENCY_ROLE
Returns the emergency role
Returns the role identifier for emergency functions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function EMERGENCY_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The emergency role |
UPGRADER_ROLE
Returns the upgrader role
Returns the role identifier for upgrade functions
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query role identifier
-
oracle: No oracle dependencies
function UPGRADER_ROLE() external view returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | The upgrader role |
qeuro
Returns the QEURO token address
Returns the address of the underlying QEURO token
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token address
-
oracle: No oracle dependencies
function qeuro() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The QEURO token address |
yieldShift
Returns the YieldShift contract address
Returns the address of the YieldShift contract
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query contract address
-
oracle: No oracle dependencies
function yieldShift() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The YieldShift contract address |
usdc
Returns the USDC token address
Returns the address of the USDC token
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query token address
-
oracle: No oracle dependencies
function usdc() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The USDC token address |
treasury
Returns the treasury address
Returns the address of the treasury contract
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query treasury address
-
oracle: No oracle dependencies
function treasury() external view returns (address);
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The treasury address |
exchangeRate
Returns the current exchange rate
Returns the current exchange rate between QEURO and stQEURO
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query exchange rate
-
oracle: No oracle dependencies
function exchangeRate() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The current exchange rate |
lastUpdateTime
Returns the last update time
Returns the timestamp of the last exchange rate update
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query last update time
-
oracle: No oracle dependencies
function lastUpdateTime() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The last update time |
totalUnderlying
Returns the total underlying QEURO
Returns the total amount of QEURO underlying all stQEURO
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total underlying
-
oracle: No oracle dependencies
function totalUnderlying() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total underlying QEURO |
totalYieldEarned
Returns the total yield earned
Returns the total amount of yield earned by all stQEURO holders
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query total yield earned
-
oracle: No oracle dependencies
function totalYieldEarned() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The total yield earned |
yieldFee
Returns the yield fee percentage
Returns the percentage of yield that goes to the treasury
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query yield fee
-
oracle: No oracle dependencies
function yieldFee() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The yield fee percentage |
minYieldThreshold
Returns the minimum yield threshold
Returns the minimum yield amount required for distribution
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query minimum yield threshold
-
oracle: No oracle dependencies
function minYieldThreshold() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The minimum yield threshold |
maxUpdateFrequency
Returns the maximum update frequency
Returns the maximum frequency for exchange rate updates
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query maximum update frequency
-
oracle: No oracle dependencies
function maxUpdateFrequency() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | The maximum update frequency |
getVirtualProtectionStatus
Gets the virtual protection status and parameters
Returns virtual protection configuration for monitoring
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown
-
reentrancy: Not applicable - view function
-
access: Public access - anyone can query virtual protection status
-
oracle: No oracle dependencies
function getVirtualProtectionStatus()
external
view
returns (bool isEnabled, uint256 maxDeviation, uint256 lastUpdateTimestamp, uint256 virtualPrice);
Returns
| Name | Type | Description |
|---|---|---|
isEnabled | bool | Whether virtual protection is enabled |
maxDeviation | uint256 | Maximum allowed deviation from real price |
lastUpdateTimestamp | uint256 | Last time the virtual price was updated |
virtualPrice | uint256 | Current virtual price |
Contents
- AccessControlLibrary
- AdminFunctionsLibrary
- CommonErrorLibrary
- CommonValidationLibrary
- FlashLoanProtectionLibrary
- GovernanceErrorLibrary
- HedgerPoolErrorLibrary
- HedgerPoolLogicLibrary
- HedgerPoolOptimizationLibrary
- HedgerPoolValidationLibrary
- QTITokenGovernanceLibrary
- TimeProvider
- TokenErrorLibrary
- TokenLibrary
- TokenValidationLibrary
- TreasuryRecoveryLibrary
- UserPoolStakingLibrary
- VaultErrorLibrary
- VaultMath
- YieldShiftCalculationLibrary
- YieldShiftOptimizationLibrary
- YieldValidationLibrary
AccessControlLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Access control functions for Quantillon Protocol
Main characteristics:
- Role-based access control validation functions
- Address and amount validation utilities
- Reduces contract bytecode size through library extraction
- Provides standardized error handling for access control
Note: security-contact: team@quantillon.money
Functions
onlyGovernance
Ensures the caller has governance role
Reverts with NotGovernance if caller lacks GOVERNANCE_ROLE
Notes:
-
security: Validates caller has GOVERNANCE_ROLE before allowing access
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws NotGovernance if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function onlyGovernance(AccessControlUpgradeable accessControl) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
accessControl | AccessControlUpgradeable | The access control contract to check roles against |
onlyVaultManager
Ensures the caller has vault manager role
Reverts with NotVaultManager if caller lacks VAULT_MANAGER_ROLE
Notes:
-
security: Validates caller has VAULT_MANAGER_ROLE before allowing access
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws NotVaultManager if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function onlyVaultManager(AccessControlUpgradeable accessControl) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
accessControl | AccessControlUpgradeable | The access control contract to check roles against |
onlyEmergencyRole
Ensures the caller has emergency role
Reverts with NotEmergencyRole if caller lacks EMERGENCY_ROLE
Notes:
-
security: Validates caller has EMERGENCY_ROLE before allowing access
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws NotEmergencyRole if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function onlyEmergencyRole(AccessControlUpgradeable accessControl) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
accessControl | AccessControlUpgradeable | The access control contract to check roles against |
onlyLiquidatorRole
Ensures the caller has liquidator role
Reverts with NotLiquidatorRole if caller lacks LIQUIDATOR_ROLE
Notes:
-
security: Validates caller has LIQUIDATOR_ROLE before allowing access
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws NotLiquidatorRole if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function onlyLiquidatorRole(AccessControlUpgradeable accessControl) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
accessControl | AccessControlUpgradeable | The access control contract to check roles against |
onlyYieldManager
Ensures the caller has yield manager role
Reverts with NotYieldManager if caller lacks YIELD_MANAGER_ROLE
Notes:
-
security: Validates caller has YIELD_MANAGER_ROLE before allowing access
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws NotYieldManager if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function onlyYieldManager(AccessControlUpgradeable accessControl) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
accessControl | AccessControlUpgradeable | The access control contract to check roles against |
onlyAdmin
Ensures the caller has admin role
Reverts with NotAdmin if caller lacks DEFAULT_ADMIN_ROLE
Notes:
-
security: Validates caller has DEFAULT_ADMIN_ROLE before allowing access
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: Throws NotAdmin if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function onlyAdmin(AccessControlUpgradeable accessControl) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
accessControl | AccessControlUpgradeable | The access control contract to check roles against |
validateAddress
Validates that an address is not the zero address
Reverts with InvalidAddress if address is zero
Notes:
-
security: Prevents zero address usage which could cause loss of funds
-
validation: Validates addr != address(0)
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAddress if address is zero
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function validateAddress(address addr) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
addr | address | The address to validate |
validateAmount
Validates that an amount is not zero
Reverts with InvalidAmount if amount is zero
Notes:
-
security: Prevents zero amount operations which could cause unexpected behavior
-
validation: Validates amount > 0
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if amount is zero
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function validateAmount(uint256 amount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
validatePositiveAmount
Validates that an amount is positive (> 0)
Reverts with InvalidAmount if amount is zero or negative
Notes:
-
security: Prevents zero or negative amount operations which could cause unexpected behavior
-
validation: Validates amount > 0
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if amount is zero or negative
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function validatePositiveAmount(uint256 amount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
AdminFunctionsLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Library for rarely used admin functions to reduce contract size
Main characteristics:
- Consolidates admin functions like recoverETH and recoverToken
- Reduces contract size by moving rarely used functions to library
- Maintains same API and behavior
- Uses custom errors for gas efficiency
Note: security-contact: team@quantillon.money
Functions
recoverETH
Recover ETH to treasury address
Emergency function to recover ETH sent to the contract
Notes:
-
security: Requires admin role
-
validation: None required
-
state-changes: Transfers ETH from contract to treasury
-
events: Emits ETHRecovered event
-
errors: Throws NotAuthorized if caller lacks admin role
-
reentrancy: Not protected - no external calls
-
access: Restricted to admin role
-
oracle: Not applicable
function recoverETH(address contractInstance, address treasury, bytes32 adminRole) external;
Parameters
| Name | Type | Description |
|---|---|---|
contractInstance | address | The contract instance calling this function |
treasury | address | The treasury address to send ETH to |
adminRole | bytes32 | The admin role required for this operation |
recoverToken
Recover tokens to treasury address
Emergency function to recover ERC20 tokens sent to the contract
Notes:
-
security: Requires admin role
-
validation: None required
-
state-changes: Transfers tokens from contract to treasury
-
events: Emits TokenRecovered event
-
errors: Throws NotAuthorized if caller lacks admin role
-
reentrancy: Not protected - library handles reentrancy
-
access: Restricted to admin role
-
oracle: Not applicable
function recoverToken(address contractInstance, address token, uint256 amount, address treasury, bytes32 adminRole)
external;
Parameters
| Name | Type | Description |
|---|---|---|
contractInstance | address | The contract instance calling this function |
token | address | Address of the token to recover |
amount | uint256 | Amount of tokens to recover |
treasury | address | The treasury address to send tokens to |
adminRole | bytes32 | The admin role required for this operation |
Events
ETHRecovered
Event emitted when ETH is recovered
event ETHRecovered(address indexed treasury, uint256 amount);
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | The treasury address that received the ETH |
amount | uint256 | The amount of ETH recovered |
CommonErrorLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Common errors used across multiple contracts in Quantillon Protocol
Main characteristics:
- Most frequently used errors across all contracts
- Reduces contract size by importing only needed errors
- Replaces require statements with custom errors for gas efficiency
- Used by 15+ contracts
Note: security-contact: team@quantillon.money
Errors
InvalidAmount
error InvalidAmount();
ZeroAddress
error ZeroAddress();
InvalidAddress
error InvalidAddress();
InsufficientBalance
error InsufficientBalance();
NotAuthorized
error NotAuthorized();
ArrayLengthMismatch
error ArrayLengthMismatch();
BatchSizeTooLarge
error BatchSizeTooLarge();
EmptyArray
error EmptyArray();
InvalidTime
error InvalidTime();
AboveLimit
error AboveLimit();
WouldExceedLimit
error WouldExceedLimit();
ExcessiveSlippage
error ExcessiveSlippage();
ConfigValueTooHigh
error ConfigValueTooHigh();
ConfigValueTooLow
error ConfigValueTooLow();
ConfigInvalid
error ConfigInvalid();
NotAdmin
error NotAdmin();
InvalidAdmin
error InvalidAdmin();
InvalidTreasury
error InvalidTreasury();
InvalidToken
error InvalidToken();
InvalidOracle
error InvalidOracle();
InvalidVault
error InvalidVault();
AlreadyInitialized
error AlreadyInitialized();
NotInitialized
error NotInitialized();
AlreadyActive
error AlreadyActive();
NotActive
error NotActive();
AlreadyPaused
error AlreadyPaused();
NotPaused
error NotPaused();
BelowThreshold
error BelowThreshold();
NoChangeDetected
error NoChangeDetected();
DivisionByZero
error DivisionByZero();
MultiplicationOverflow
error MultiplicationOverflow();
PercentageTooHigh
error PercentageTooHigh();
InvalidParameter
error InvalidParameter();
InvalidCondition
error InvalidCondition();
ETHTransferFailed
error ETHTransferFailed();
TokenTransferFailed
error TokenTransferFailed();
CannotSendToZero
error CannotSendToZero();
NoETHToRecover
error NoETHToRecover();
NoTokensToRecover
error NoTokensToRecover();
CannotRecoverOwnToken
error CannotRecoverOwnToken();
EmergencyModeActive
error EmergencyModeActive();
HoldingPeriodNotMet
error HoldingPeriodNotMet();
InvalidPrice
error InvalidPrice();
InsufficientCollateralization
error InsufficientCollateralization();
TooManyPositions
error TooManyPositions();
PositionNotActive
error PositionNotActive();
LiquidationCooldown
error LiquidationCooldown();
InvalidYieldShift
error InvalidYieldShift();
AdjustmentSpeedTooHigh
error AdjustmentSpeedTooHigh();
TargetRatioTooHigh
error TargetRatioTooHigh();
InvalidRatio
error InvalidRatio();
NotGovernance
error NotGovernance();
NotEmergency
error NotEmergency();
NotEmergencyRole
error NotEmergencyRole();
NotLiquidator
error NotLiquidator();
NotLiquidatorRole
error NotLiquidatorRole();
NotHedger
error NotHedger();
NotVaultManager
error NotVaultManager();
NotYieldManager
error NotYieldManager();
InsufficientYield
error InsufficientYield();
InvalidShiftRange
error InvalidShiftRange();
CommonValidationLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Common validation functions used across multiple contracts
Main characteristics:
- Consolidates common validation patterns
- Reduces code duplication across contracts
- Uses custom errors for gas efficiency
- Maintains same validation logic
Note: security-contact: team@quantillon.money
Functions
validateNonZeroAddress
Validates that an address is not zero
Checks if the provided address is the zero address and reverts with appropriate error
Notes:
-
security: Prevents zero address vulnerabilities in critical operations
-
validation: Ensures all addresses are properly initialized
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws specific custom errors based on errorType
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateNonZeroAddress(address addr, string memory errorType) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
addr | address | The address to validate |
errorType | string | The type of address being validated (admin, treasury, token, oracle, vault) |
validatePositiveAmount
Validates that an amount is positive
Ensures the amount is greater than zero to prevent zero-value operations
Notes:
-
security: Prevents zero-amount vulnerabilities and invalid operations
-
validation: Ensures amounts are meaningful for business logic
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if amount is zero
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositiveAmount(uint256 amount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
validateMinAmount
Validates that an amount is above minimum threshold
Ensures the amount meets the minimum requirement for the operation
Notes:
-
security: Prevents operations with insufficient amounts
-
validation: Ensures amounts meet business requirements
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InsufficientBalance if amount is below minimum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateMinAmount(uint256 amount, uint256 minAmount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
minAmount | uint256 | The minimum required amount |
validateMaxAmount
Validates that an amount is below maximum threshold
Ensures the amount does not exceed the maximum allowed limit
Notes:
-
security: Prevents operations that exceed system limits
-
validation: Ensures amounts stay within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws AboveLimit if amount exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateMaxAmount(uint256 amount, uint256 maxAmount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
maxAmount | uint256 | The maximum allowed amount |
validatePercentage
Validates that a percentage is within valid range (0-100%)
Ensures percentage values are within acceptable bounds for fees and rates
Notes:
-
security: Prevents invalid percentage values that could break system logic
-
validation: Ensures percentages are within business rules
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws AboveLimit if percentage exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePercentage(uint256 percentage, uint256 maxPercentage) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
percentage | uint256 | The percentage to validate (in basis points) |
maxPercentage | uint256 | The maximum allowed percentage (in basis points) |
validateDuration
Validates that a duration is within valid range
Ensures time-based parameters are within acceptable bounds
Notes:
-
security: Prevents invalid time parameters that could affect system stability
-
validation: Ensures durations meet business requirements
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws HoldingPeriodNotMet or AboveLimit based on validation failure
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateDuration(uint256 duration, uint256 minDuration, uint256 maxDuration) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
duration | uint256 | The duration to validate |
minDuration | uint256 | The minimum allowed duration |
maxDuration | uint256 | The maximum allowed duration |
validatePrice
Validates that a price is valid (greater than zero)
Ensures price values are meaningful and not zero
Notes:
-
security: Prevents zero-price vulnerabilities in financial operations
-
validation: Ensures prices are valid for calculations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidPrice if price is zero
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePrice(uint256 price) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
price | uint256 | The price to validate |
validateCondition
Validates that a boolean condition is true
Generic condition validator that throws specific errors based on error type
Notes:
-
security: Prevents invalid conditions from proceeding in critical operations
-
validation: Ensures business logic conditions are met
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws specific custom errors based on errorType
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateCondition(bool condition, string memory errorType) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
condition | bool | The condition to validate |
errorType | string | The type of error to throw if condition is false |
validateCountLimit
Validates that a count is within limits
Ensures count-based operations don't exceed system limits
Notes:
-
security: Prevents operations that exceed system capacity limits
-
validation: Ensures counts stay within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws TooManyPositions if count exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateCountLimit(uint256 count, uint256 maxCount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
count | uint256 | The current count |
maxCount | uint256 | The maximum allowed count |
validateSufficientBalance
Validates that a balance is sufficient
Ensures there's enough balance to perform the required operation
Notes:
-
security: Prevents operations with insufficient funds
-
validation: Ensures sufficient balance for operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InsufficientBalance if balance is below required amount
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateSufficientBalance(uint256 balance, uint256 requiredAmount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
balance | uint256 | The current balance |
requiredAmount | uint256 | The required amount |
validateNotContract
Validates that an address is not a contract (for security)
Prevents sending funds to potentially malicious contracts
Notes:
-
security: Prevents arbitrary-send vulnerabilities
-
validation: Ensures address is not a contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAddress if address is a contract
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateNotContract(address addr, string memory errorType) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
addr | address | The address to validate |
errorType | string | The type of error to throw if validation fails |
validateTreasuryAddress
Validates treasury address is not zero address
Prevents setting treasury to zero address which could cause loss of funds
Notes:
-
security: Prevents loss of funds by ensuring treasury is properly set
-
validation: Ensures treasury address is valid for fund operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws ZeroAddress if treasury is zero address
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTreasuryAddress(address treasury) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | The treasury address to validate |
validateSlippage
Validates slippage protection for token swaps/trades
Ensures received amount is within acceptable tolerance of expected
Notes:
-
security: Prevents excessive slippage attacks in token operations
-
validation: Ensures received amount meets minimum expectations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter if slippage exceeds tolerance
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateSlippage(uint256 received, uint256 expected, uint256 tolerance) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
received | uint256 | The actual amount received |
expected | uint256 | The expected amount |
tolerance | uint256 | The slippage tolerance in basis points |
validateThresholdValue
Validates that a value meets minimum threshold requirements
Used for minimum deposits, stakes, withdrawals, etc.
Notes:
-
security: Prevents operations below minimum thresholds
-
validation: Ensures values meet business requirements
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws BelowThreshold if value is below minimum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateThresholdValue(uint256 value, uint256 threshold) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
value | uint256 | The value to validate |
threshold | uint256 | The minimum required threshold |
validateFee
Validates fee amount against maximum allowed fee
Ensures fees don't exceed protocol limits (typically in basis points)
Notes:
-
security: Prevents excessive fees that could harm users
-
validation: Ensures fees stay within protocol limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter if fee exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateFee(uint256 fee, uint256 maxFee) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
fee | uint256 | The fee amount to validate |
maxFee | uint256 | The maximum allowed fee |
validateThreshold
Validates threshold value against maximum limit
Used for liquidation thresholds, margin ratios, etc.
Notes:
-
security: Prevents thresholds that could destabilize the system
-
validation: Ensures thresholds stay within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter if threshold exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateThreshold(uint256 threshold, uint256 maxThreshold) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
threshold | uint256 | The threshold value to validate |
maxThreshold | uint256 | The maximum allowed threshold |
FlashLoanProtectionLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Library for protecting contracts against flash loan attacks
This library provides functions to detect and prevent flash loan attacks by monitoring balance changes during function execution.
Flash loan attacks can occur when:
- An attacker borrows a large amount of tokens
- Manipulates protocol state (e.g., governance votes, price oracles)
- Repays the loan in the same transaction
- Profits from the manipulated state
Protection mechanism:
- Balance checks before and after function execution
- Validation that balances don't decrease unexpectedly
Note: security-contact: team@quantillon.money
Functions
validateBalanceChange
Validates that a balance change is within acceptable limits
This function validates that balances don't decrease beyond acceptable limits. Currently used by all contract modifiers to prevent flash loan attacks. A maxDecrease of 0 means no decrease is allowed (strict protection).
Notes:
-
security: Prevents flash loan attacks by validating balance changes
-
validation: Validates balance changes are within acceptable limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No custom errors thrown
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function validateBalanceChange(uint256 balanceBefore, uint256 balanceAfter, uint256 maxDecrease)
internal
pure
returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
balanceBefore | uint256 | Balance before operation |
balanceAfter | uint256 | Balance after operation |
maxDecrease | uint256 | Maximum allowed decrease in balance |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | bool True if balance change is acceptable |
GovernanceErrorLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Governance-specific errors for QTIToken governance system
Main characteristics:
- Errors specific to governance operations
- Voting and proposal management errors
- Timelock and execution errors
- MEV protection errors
Note: security-contact: team@quantillon.money
Errors
InsufficientVotingPower
error InsufficientVotingPower();
VotingPeriodTooShort
error VotingPeriodTooShort();
VotingPeriodTooLong
error VotingPeriodTooLong();
ProposalNotFound
error ProposalNotFound();
ProposalAlreadyExecuted
error ProposalAlreadyExecuted();
ProposalAlreadyCanceled
error ProposalAlreadyCanceled();
VotingNotActive
error VotingNotActive();
AlreadyVoted
error AlreadyVoted();
QuorumNotMet
error QuorumNotMet();
ProposalThresholdNotMet
error ProposalThresholdNotMet();
VotingNotStarted
error VotingNotStarted();
VotingEnded
error VotingEnded();
NoVotingPower
error NoVotingPower();
VotingNotEnded
error VotingNotEnded();
ProposalFailed
error ProposalFailed();
ProposalExecutionFailed
error ProposalExecutionFailed();
ProposalCanceled
error ProposalCanceled();
ProposalAlreadyScheduled
error ProposalAlreadyScheduled();
ProposalNotScheduled
error ProposalNotScheduled();
InvalidExecutionHash
error InvalidExecutionHash();
ExecutionTimeNotReached
error ExecutionTimeNotReached();
InvalidDescription
error InvalidDescription();
ExpiredDeadline
error ExpiredDeadline();
InvalidRebalancing
error InvalidRebalancing();
RateLimitTooHigh
error RateLimitTooHigh();
InvalidAmount
error InvalidAmount();
InvalidTime
error InvalidTime();
LockTimeTooShort
error LockTimeTooShort();
LockTimeTooLong
error LockTimeTooLong();
HedgerPoolErrorLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
HedgerPool-specific errors for Quantillon Protocol
Main characteristics:
- Errors specific to HedgerPool operations
- Trading position management errors
- Liquidation system errors
- Margin and leverage validation errors
Note: security-contact: team@quantillon.money
Errors
FlashLoanAttackDetected
error FlashLoanAttackDetected();
NotWhitelisted
error NotWhitelisted();
PendingLiquidationCommitment
error PendingLiquidationCommitment();
InvalidPosition
error InvalidPosition();
PositionNotLiquidatable
error PositionNotLiquidatable();
YieldClaimFailed
error YieldClaimFailed();
InvalidHedger
error InvalidHedger();
TooManyPositions
error TooManyPositions();
MaxPositionsPerTx
error MaxPositionsPerTx();
NotPaused
error NotPaused();
ZeroAddress
error ZeroAddress();
InvalidAmount
error InvalidAmount();
ConfigValueTooLow
error ConfigValueTooLow();
ConfigInvalid
error ConfigInvalid();
ConfigValueTooHigh
error ConfigValueTooHigh();
AlreadyWhitelisted
error AlreadyWhitelisted();
InvalidOraclePrice
error InvalidOraclePrice();
InvalidAddress
error InvalidAddress();
NotAuthorized
error NotAuthorized();
RewardOverflow
error RewardOverflow();
InsufficientMargin
error InsufficientMargin();
CannotRecoverOwnToken
error CannotRecoverOwnToken();
NoETHToRecover
error NoETHToRecover();
MarginExceedsMaximum
error MarginExceedsMaximum();
PositionSizeExceedsMaximum
error PositionSizeExceedsMaximum();
EntryPriceExceedsMaximum
error EntryPriceExceedsMaximum();
LeverageExceedsMaximum
error LeverageExceedsMaximum();
TimestampOverflow
error TimestampOverflow();
TotalMarginExceedsMaximum
error TotalMarginExceedsMaximum();
TotalExposureExceedsMaximum
error TotalExposureExceedsMaximum();
NewMarginExceedsMaximum
error NewMarginExceedsMaximum();
PendingRewardsExceedMaximum
error PendingRewardsExceedMaximum();
InvalidLeverage
error InvalidLeverage();
LeverageTooHigh
error LeverageTooHigh();
LeverageTooLow
error LeverageTooLow();
MaxLeverageExceeded
error MaxLeverageExceeded();
MarginTooLow
error MarginTooLow();
MarginRatioTooLow
error MarginRatioTooLow();
MarginRatioTooHigh
error MarginRatioTooHigh();
MarginInsufficient
error MarginInsufficient();
MarginLimitExceeded
error MarginLimitExceeded();
PositionNotFound
error PositionNotFound();
PositionOwnerMismatch
error PositionOwnerMismatch();
PositionAlreadyClosed
error PositionAlreadyClosed();
PositionClosureRestricted
error PositionClosureRestricted();
PositionNotActive
error PositionNotActive();
LiquidationNotAllowed
error LiquidationNotAllowed();
LiquidationRewardTooHigh
error LiquidationRewardTooHigh();
LiquidationPenaltyTooHigh
error LiquidationPenaltyTooHigh();
LiquidationThresholdInvalid
error LiquidationThresholdInvalid();
LiquidationCooldown
error LiquidationCooldown();
NoValidCommitment
error NoValidCommitment();
CommitmentAlreadyExists
error CommitmentAlreadyExists();
CommitmentDoesNotExist
error CommitmentDoesNotExist();
FeeTooHigh
error FeeTooHigh();
EntryFeeTooHigh
error EntryFeeTooHigh();
ExitFeeTooHigh
error ExitFeeTooHigh();
MarginFeeTooHigh
error MarginFeeTooHigh();
YieldFeeTooHigh
error YieldFeeTooHigh();
YieldBelowThreshold
error YieldBelowThreshold();
YieldNotAvailable
error YieldNotAvailable();
YieldDistributionFailed
error YieldDistributionFailed();
YieldCalculationError
error YieldCalculationError();
InsufficientYield
error InsufficientYield();
HoldingPeriodNotMet
error HoldingPeriodNotMet();
HedgerPoolLogicLibrary
Logic functions for HedgerPool to reduce contract size
Functions
validateAndCalculatePositionParams
Validates position parameters and calculates derived values
Validates all position constraints and calculates fee, margin, and position size
Notes:
-
security: Validates all position constraints and limits
-
validation: Ensures amounts, leverage, and ratios are within limits
-
state-changes: None (pure function)
-
events: None
-
errors: Throws various validation errors if constraints not met
-
reentrancy: Not applicable - pure function
-
access: External pure function
-
oracle: Uses provided eurUsdPrice parameter
function validateAndCalculatePositionParams(
uint256 usdcAmount,
uint256 leverage,
uint256 eurUsdPrice,
uint256 entryFee,
uint256 minMarginRatio,
uint256 maxMarginRatio,
uint256 maxLeverage,
uint256 maxPositionsPerHedger,
uint256 activePositionCount,
uint256 maxMargin,
uint256 maxPositionSize,
uint256 maxEntryPrice,
uint256 maxLeverageValue,
uint256 currentTime
) external pure returns (uint256 fee, uint256 netMargin, uint256 positionSize, uint256 marginRatio);
Parameters
| Name | Type | Description |
|---|---|---|
usdcAmount | uint256 | Amount of USDC to deposit |
leverage | uint256 | Leverage multiplier for the position |
eurUsdPrice | uint256 | Current EUR/USD price from oracle |
entryFee | uint256 | Entry fee rate in basis points |
minMarginRatio | uint256 | Minimum margin ratio in basis points |
maxMarginRatio | uint256 | Maximum margin ratio in basis points |
maxLeverage | uint256 | Maximum allowed leverage |
maxPositionsPerHedger | uint256 | Maximum positions per hedger |
activePositionCount | uint256 | Current active position count for hedger |
maxMargin | uint256 | Maximum margin per position |
maxPositionSize | uint256 | Maximum position size |
maxEntryPrice | uint256 | Maximum entry price |
maxLeverageValue | uint256 | Maximum leverage value |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
fee | uint256 | Calculated entry fee |
netMargin | uint256 | Net margin after fee deduction |
positionSize | uint256 | Calculated position size |
marginRatio | uint256 | Calculated margin ratio |
calculatePnL
Calculates profit or loss for a hedge position
Computes PnL based on price movement from entry to current price
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: Uses provided currentPrice parameter
function calculatePnL(uint256 positionSize, uint256 entryPrice, uint256 currentPrice)
internal
pure
returns (int256);
Parameters
| Name | Type | Description |
|---|---|---|
positionSize | uint256 | Size of the position in USDC |
entryPrice | uint256 | Price at which the position was opened |
currentPrice | uint256 | Current market price |
Returns
| Name | Type | Description |
|---|---|---|
<none> | int256 | Profit (positive) or loss (negative) amount |
isPositionLiquidatable
Determines if a position is eligible for liquidation
Checks if position margin ratio is below liquidation threshold
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: External pure function
-
oracle: Uses provided currentPrice parameter
function isPositionLiquidatable(
uint256 margin,
uint256 positionSize,
uint256 entryPrice,
uint256 currentPrice,
uint256 liquidationThreshold
) external pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
margin | uint256 | Current margin amount for the position |
positionSize | uint256 | Size of the position in USDC |
entryPrice | uint256 | Price at which the position was opened |
currentPrice | uint256 | Current market price |
liquidationThreshold | uint256 | Liquidation threshold in basis points |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if position can be liquidated, false otherwise |
calculateRewardUpdate
Calculates reward updates for hedgers based on interest rate differentials
Computes new pending rewards based on time elapsed and interest rates
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: External pure function
-
oracle: Not applicable
function calculateRewardUpdate(
uint256 totalExposure,
uint256 eurInterestRate,
uint256 usdInterestRate,
uint256 lastRewardBlock,
uint256 currentBlock,
uint256 maxRewardPeriod,
uint256 currentPendingRewards
) external pure returns (uint256 newPendingRewards, uint256 newLastRewardBlock);
Parameters
| Name | Type | Description |
|---|---|---|
totalExposure | uint256 | Total exposure across all positions |
eurInterestRate | uint256 | EUR interest rate in basis points |
usdInterestRate | uint256 | USD interest rate in basis points |
lastRewardBlock | uint256 | Block number of last reward calculation |
currentBlock | uint256 | Current block number |
maxRewardPeriod | uint256 | Maximum reward period in blocks |
currentPendingRewards | uint256 | Current pending rewards amount |
Returns
| Name | Type | Description |
|---|---|---|
newPendingRewards | uint256 | Updated pending rewards amount |
newLastRewardBlock | uint256 | Updated last reward block |
validateMarginOperation
Validates margin operations and calculates new margin values
Validates margin addition/removal and calculates resulting margin ratio
Notes:
-
security: Validates margin constraints and limits
-
validation: Ensures margin operations are within limits
-
state-changes: None (pure function)
-
events: None
-
errors: Throws InsufficientMargin or validation errors
-
reentrancy: Not applicable - pure function
-
access: External pure function
-
oracle: Not applicable
function validateMarginOperation(
uint256 currentMargin,
uint256 amount,
bool isAddition,
uint256 minMarginRatio,
uint256 positionSize,
uint256 maxMargin
) external pure returns (uint256 newMargin, uint256 newMarginRatio);
Parameters
| Name | Type | Description |
|---|---|---|
currentMargin | uint256 | Current margin amount for the position |
amount | uint256 | Amount of margin to add or remove |
isAddition | bool | True if adding margin, false if removing |
minMarginRatio | uint256 | Minimum margin ratio in basis points |
positionSize | uint256 | Size of the position in USDC |
maxMargin | uint256 | Maximum margin per position |
Returns
| Name | Type | Description |
|---|---|---|
newMargin | uint256 | New margin amount after operation |
newMarginRatio | uint256 | New margin ratio after operation |
generateLiquidationCommitment
Generates a unique liquidation commitment hash
Creates a commitment hash for MEV protection in liquidation process
Notes:
-
security: No security validations required for pure function
-
validation: None required for pure function
-
state-changes: None (pure function)
-
events: None
-
errors: None
-
reentrancy: Not applicable - pure function
-
access: External pure function
-
oracle: Not applicable
function generateLiquidationCommitment(address hedger, uint256 positionId, bytes32 salt, address liquidator)
external
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position will be liquidated |
positionId | uint256 | ID of the position to liquidate |
salt | bytes32 | Random salt for commitment uniqueness |
liquidator | address | Address of the liquidator making the commitment |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Commitment hash for liquidation process |
Structs
PositionData
struct PositionData {
uint256 positionSize;
uint256 margin;
uint256 entryPrice;
uint32 entryTime;
uint32 lastUpdateTime;
int128 unrealizedPnL;
uint16 leverage;
bool isActive;
}
HedgerData
struct HedgerData {
uint256 totalMargin;
uint256 totalExposure;
uint128 pendingRewards;
uint64 lastRewardClaim;
bool isActive;
}
HedgerPoolOptimizationLibrary
Author: Quantillon Labs
Library for HedgerPool data packing, validation, and utility functions
Extracts utility functions from HedgerPool to reduce contract size
Functions
packPositionOpenData
Packs position open data into a single bytes32 for gas efficiency
Encodes position size, margin, leverage, and entry price into a compact format
Notes:
-
security: No security implications - pure data packing function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function packPositionOpenData(uint256 positionSize, uint256 margin, uint256 leverage, uint256 entryPrice)
external
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
positionSize | uint256 | Size of the position in USDC |
margin | uint256 | Margin amount for the position |
leverage | uint256 | Leverage multiplier for the position |
entryPrice | uint256 | Price at which the position was opened |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
packPositionCloseData
Packs position close data into a single bytes32 for gas efficiency
Encodes exit price, PnL, and timestamp into a compact format
Notes:
-
security: No security implications - pure data packing function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function packPositionCloseData(uint256 exitPrice, int256 pnl, uint256 timestamp) external pure returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
exitPrice | uint256 | Price at which the position was closed |
pnl | int256 | Profit or loss from the position (can be negative) |
timestamp | uint256 | Timestamp when the position was closed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
packMarginData
Packs margin data into a single bytes32 for gas efficiency
Encodes margin amount, new margin ratio, and operation type
Notes:
-
security: No security implications - pure data packing function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function packMarginData(uint256 marginAmount, uint256 newMarginRatio, bool isAdded)
external
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
marginAmount | uint256 | Amount of margin added or removed |
newMarginRatio | uint256 | New margin ratio after the operation |
isAdded | bool | True if margin was added, false if removed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
packLiquidationData
Packs liquidation data into a single bytes32 for gas efficiency
Encodes liquidation reward and remaining margin
Notes:
-
security: No security implications - pure data packing function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function packLiquidationData(uint256 liquidationReward, uint256 remainingMargin) external pure returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
liquidationReward | uint256 | Reward paid to the liquidator |
remainingMargin | uint256 | Margin remaining after liquidation |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
packRewardData
Packs reward data into a single bytes32 for gas efficiency
Encodes interest differential, yield shift rewards, and total rewards
Notes:
-
security: No security implications - pure data packing function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function packRewardData(uint256 interestDifferential, uint256 yieldShiftRewards, uint256 totalRewards)
external
pure
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
interestDifferential | uint256 | Interest rate differential between EUR and USD |
yieldShiftRewards | uint256 | Rewards from yield shifting operations |
totalRewards | uint256 | Total rewards accumulated |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | Packed data as bytes32 |
validateRole
Validates that the caller has the required role
Internal function to check role-based access control
Notes:
-
security: Prevents unauthorized access to protected functions
-
validation: Ensures proper role-based access control
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: Throws NotAuthorized if caller lacks required role
-
reentrancy: Not applicable - view function
-
access: External function with role validation
-
oracle: No oracle dependencies
function validateRole(bytes32 role, address contractInstance) external view;
Parameters
| Name | Type | Description |
|---|---|---|
role | bytes32 | The role to validate against |
contractInstance | address | The contract instance to check roles on |
validatePositionClosureSafety
Validates that closing a position won't cause protocol undercollateralization
Checks if closing the position would make the protocol undercollateralized for QEURO minting
Notes:
-
security: Prevents protocol undercollateralization from position closures
-
validation: Ensures protocol remains properly collateralized
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: No errors thrown - returns boolean result
-
reentrancy: Not applicable - view function
-
access: External function
-
oracle: No oracle dependencies
function validatePositionClosureSafety(uint256 positionMargin, address vaultAddress)
external
view
returns (bool isValid);
Parameters
| Name | Type | Description |
|---|---|---|
positionMargin | uint256 | The margin amount of the position being closed |
vaultAddress | address | Address of the vault contract |
Returns
| Name | Type | Description |
|---|---|---|
isValid | bool | True if position can be safely closed |
_getProtocolData
Gets protocol collateralization data
Internal function to reduce stack depth
Notes:
-
security: Uses staticcall for safe external contract interaction
-
validation: Validates call success and data length before decoding
-
state-changes: No state changes, view function
-
events: No events emitted
-
errors: Returns default values on call failures
-
reentrancy: No reentrancy risk, view function
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _getProtocolData(address vaultAddress)
internal
view
returns (bool isCollateralized, uint256 currentTotalMargin, uint256 minCollateralizationRatio);
Parameters
| Name | Type | Description |
|---|---|---|
vaultAddress | address | Address of the vault contract |
Returns
| Name | Type | Description |
|---|---|---|
isCollateralized | bool | Whether protocol is currently collateralized |
currentTotalMargin | uint256 | Current total margin in the protocol |
minCollateralizationRatio | uint256 | Minimum collateralization ratio for minting |
_hasQEUROMinted
Checks if QEURO has been minted
Internal function to reduce stack depth
Notes:
-
security: Uses staticcall for safe external contract interaction
-
validation: Validates call success and data length before decoding
-
state-changes: No state changes, view function
-
events: No events emitted
-
errors: Returns false on call failures
-
reentrancy: No reentrancy risk, view function
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _hasQEUROMinted(address vaultAddress) internal view returns (bool hasMinted);
Parameters
| Name | Type | Description |
|---|---|---|
vaultAddress | address | Address of the vault contract |
Returns
| Name | Type | Description |
|---|---|---|
hasMinted | bool | Whether QEURO has been minted (totalSupply > 0) |
_validateClosureWithUserDeposits
Validates closure with user deposits
Internal function to reduce stack depth
Notes:
-
security: Validates protocol remains collateralized after closure
-
validation: Ensures closure doesn't violate collateralization requirements
-
state-changes: No state changes, view function
-
events: No events emitted
-
errors: No custom errors, returns boolean result
-
reentrancy: No reentrancy risk, view function
-
access: Internal function, no access control needed
-
oracle: No oracle dependencies
function _validateClosureWithUserDeposits(
address vaultAddress,
uint256 positionMargin,
uint256 currentTotalMargin,
uint256 minCollateralizationRatio
) internal view returns (bool isValid);
Parameters
| Name | Type | Description |
|---|---|---|
vaultAddress | address | Address of the vault contract |
positionMargin | uint256 | Margin for the position being closed |
currentTotalMargin | uint256 | Current total margin in the protocol |
minCollateralizationRatio | uint256 | Minimum collateralization ratio for minting |
Returns
| Name | Type | Description |
|---|---|---|
isValid | bool | Whether the position can be safely closed |
removePositionFromArrays
Removes a position from the hedger's position arrays
Internal function to maintain position tracking arrays
Notes:
-
security: Maintains data integrity of position tracking arrays
-
validation: Ensures position exists before removal
-
state-changes: Modifies storage mappings and arrays
-
events: No events emitted
-
errors: No errors thrown - returns boolean result
-
reentrancy: Not applicable - no external calls
-
access: External function
-
oracle: No oracle dependencies
function removePositionFromArrays(
address hedger,
uint256 positionId,
mapping(address => mapping(uint256 => bool)) storage hedgerHasPosition,
mapping(address => mapping(uint256 => uint256)) storage positionIndex,
uint256[] storage positionIds
) external returns (bool success);
Parameters
| Name | Type | Description |
|---|---|---|
hedger | address | Address of the hedger whose position to remove |
positionId | uint256 | ID of the position to remove |
hedgerHasPosition | mapping(address => mapping(uint256 => bool)) | Mapping of hedger to position existence |
positionIndex | mapping(address => mapping(uint256 => uint256)) | Mapping of hedger to position index |
positionIds | uint256[] | Array of position IDs for the hedger |
Returns
| Name | Type | Description |
|---|---|---|
success | bool | True if position was successfully removed |
getValidOraclePrice
Gets a valid EUR/USD price from the oracle
Retrieves and validates price data from the oracle contract
Notes:
-
security: Ensures oracle price data is valid before use
-
validation: Validates oracle response format and data
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: No errors thrown - returns boolean result
-
reentrancy: Not applicable - view function
-
access: External function
-
oracle: Depends on oracle contract for price data
function getValidOraclePrice(address oracleAddress) external view returns (uint256 price, bool isValid);
Parameters
| Name | Type | Description |
|---|---|---|
oracleAddress | address | Address of the oracle contract |
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | Valid EUR/USD price from oracle |
isValid | bool | True if price is valid |
HedgerPoolValidationLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
HedgerPool-specific validation functions for Quantillon Protocol
Main characteristics:
- Validation functions specific to HedgerPool operations
- Trading position management validations
- Liquidation system validations
- Margin and leverage validation functions
Note: security-contact: team@quantillon.money
Functions
validateLeverage
Validates leverage parameters for trading positions
Ensures leverage is within acceptable bounds (> 0 and <= max)
Notes:
-
security: Prevents excessive leverage that could cause system instability
-
validation: Ensures leverage is within acceptable risk bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidLeverage or LeverageTooHigh based on validation
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateLeverage(uint256 leverage, uint256 maxLeverage) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
leverage | uint256 | The leverage multiplier to validate |
maxLeverage | uint256 | The maximum allowed leverage |
validateMarginRatio
Validates margin ratio to ensure sufficient collateralization
Prevents positions from being under-collateralized
Notes:
-
security: Prevents under-collateralized positions that could cause liquidations
-
validation: Ensures sufficient margin for position safety
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws MarginRatioTooLow if ratio is below minimum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateMarginRatio(uint256 marginRatio, uint256 minRatio) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
marginRatio | uint256 | The current margin ratio to validate |
minRatio | uint256 | The minimum required margin ratio |
validateMaxMarginRatio
Validates margin ratio against maximum limit to prevent excessive collateralization
Prevents positions from being over-collateralized (leverage too low)
Notes:
-
security: Prevents over-collateralization that could reduce capital efficiency
-
validation: Ensures margin ratio stays within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws MarginRatioTooHigh if ratio exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateMaxMarginRatio(uint256 marginRatio, uint256 maxRatio) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
marginRatio | uint256 | The current margin ratio to validate |
maxRatio | uint256 | The maximum allowed margin ratio |
validateLiquidationCooldown
Validates liquidation cooldown period to prevent manipulation
Uses block numbers to prevent timestamp manipulation attacks
Notes:
-
security: Prevents liquidation manipulation through cooldown bypass
-
validation: Ensures proper cooldown period between liquidation attempts
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: Throws LiquidationCooldown if cooldown period not met
-
reentrancy: Not applicable - view function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateLiquidationCooldown(uint256 lastAttempt, uint256 cooldown) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
lastAttempt | uint256 | The block number of the last liquidation attempt |
cooldown | uint256 | The required cooldown period in blocks |
validatePositionActive
Validates that a position is active before operations
Prevents operations on closed or invalid positions
Notes:
-
security: Prevents operations on inactive positions
-
validation: Ensures position is active before modifications
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws PositionNotActive if position is inactive
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositionActive(bool isActive) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
isActive | bool | The position's active status |
validatePositionOwner
Validates position ownership before allowing operations
Security check to ensure only position owner can modify it
Notes:
-
security: Prevents unauthorized position modifications
-
validation: Ensures only position owner can modify position
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws PositionOwnerMismatch if caller is not owner
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositionOwner(address owner, address caller) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
owner | address | The position owner's address |
caller | address | The address attempting the operation |
validatePositionCount
Validates position count limits to prevent system overload
Enforces maximum positions per user for gas and complexity management
Notes:
-
security: Prevents system overload through excessive positions
-
validation: Ensures position count stays within system limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws TooManyPositions if count exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositionCount(uint256 count, uint256 max) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
count | uint256 | The current position count |
max | uint256 | The maximum allowed positions |
validateCommitmentNotExists
Validates that a commitment doesn't already exist
Prevents duplicate commitments in liquidation system
Notes:
-
security: Prevents duplicate commitments that could cause system issues
-
validation: Ensures commitment doesn't already exist
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws CommitmentAlreadyExists if commitment exists
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateCommitmentNotExists(bool exists) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
exists | bool | Whether the commitment already exists |
validateCommitment
Validates that a valid commitment exists
Ensures commitment exists before executing liquidation
Notes:
-
security: Prevents liquidation without valid commitment
-
validation: Ensures valid commitment exists before liquidation
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws NoValidCommitment if commitment doesn't exist
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateCommitment(bool exists) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
exists | bool | Whether a valid commitment exists |
validatePositionParams
Validates all position parameters against maximum limits
Ensures all position parameters are within acceptable bounds
Notes:
-
security: Prevents position parameters that could destabilize system
-
validation: Ensures all position parameters are within limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws specific errors for each parameter that exceeds limits
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositionParams(
uint256 netMargin,
uint256 positionSize,
uint256 eurUsdPrice,
uint256 leverage,
uint256 maxMargin,
uint256 maxPositionSize,
uint256 maxEntryPrice,
uint256 maxLeverage
) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
netMargin | uint256 | The net margin amount after fees |
positionSize | uint256 | The size of the position |
eurUsdPrice | uint256 | The EUR/USD entry price |
leverage | uint256 | The leverage multiplier |
maxMargin | uint256 | Maximum allowed margin |
maxPositionSize | uint256 | Maximum allowed position size |
maxEntryPrice | uint256 | Maximum allowed entry price |
maxLeverage | uint256 | Maximum allowed leverage |
validateTotals
Validates total margin and exposure limits
Ensures combined totals don't exceed system-wide limits
Notes:
-
security: Prevents system-wide limits from being exceeded
-
validation: Ensures combined totals stay within system limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws TotalMarginExceedsMaximum or TotalExposureExceedsMaximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTotals(
uint256 currentMargin,
uint256 currentExposure,
uint256 additionalMargin,
uint256 additionalExposure,
uint256 maxTotalMargin,
uint256 maxTotalExposure
) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
currentMargin | uint256 | Current total margin |
currentExposure | uint256 | Current total exposure |
additionalMargin | uint256 | Additional margin being added |
additionalExposure | uint256 | Additional exposure being added |
maxTotalMargin | uint256 | Maximum allowed total margin |
maxTotalExposure | uint256 | Maximum allowed total exposure |
validateTimestamp
Validates timestamp fits in uint32 for storage optimization
Prevents timestamp overflow when casting to uint32
Notes:
-
security: Prevents timestamp overflow that could cause data corruption
-
validation: Ensures timestamp fits within uint32 bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws TimestampOverflow if timestamp exceeds uint32 max
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTimestamp(uint256 timestamp) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
timestamp | uint256 | The timestamp to validate |
validateNewMargin
Validates new margin amount against maximum limit
Ensures margin additions don't exceed individual position limits
Notes:
-
security: Prevents margin additions that exceed position limits
-
validation: Ensures new margin stays within position limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws NewMarginExceedsMaximum if new margin exceeds limit
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateNewMargin(uint256 newMargin, uint256 maxMargin) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
newMargin | uint256 | The new total margin amount |
maxMargin | uint256 | Maximum allowed margin per position |
validatePendingRewards
Validates pending rewards against maximum accumulation limit
Prevents excessive reward accumulation that could cause overflow
Notes:
-
security: Prevents reward overflow that could cause system issues
-
validation: Ensures pending rewards stay within accumulation limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws PendingRewardsExceedMaximum if rewards exceed limit
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePendingRewards(uint256 newRewards, uint256 maxRewards) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
newRewards | uint256 | The new total pending rewards amount |
maxRewards | uint256 | Maximum allowed pending rewards |
validatePositiveAmount
Validates that an amount is positive (greater than zero)
Essential for token amounts, deposits, withdrawals, etc.
Notes:
-
security: Prevents zero-amount operations that could cause issues
-
validation: Ensures amount is positive for meaningful operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if amount is zero
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositiveAmount(uint256 amount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
validateFee
Validates fee amount against maximum allowed fee
Ensures fees don't exceed protocol limits (typically in basis points)
Notes:
-
security: Prevents excessive fees that could harm users
-
validation: Ensures fees stay within protocol limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws FeeTooHigh if fee exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateFee(uint256 fee, uint256 maxFee) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
fee | uint256 | The fee amount to validate |
maxFee | uint256 | The maximum allowed fee |
validateTreasuryAddress
Validates treasury address is not zero address
Prevents setting treasury to zero address which could cause loss of funds
Notes:
-
security: Prevents loss of funds by ensuring treasury is properly set
-
validation: Ensures treasury address is valid for fund operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws ZeroAddress if treasury is zero address
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTreasuryAddress(address treasury) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | The treasury address to validate |
QTITokenGovernanceLibrary
Author: Quantillon Labs
Library for QTIToken governance calculations and validations
Extracts calculation logic from QTIToken to reduce contract size
State Variables
MAX_LOCK_TIME
Maximum lock time for QTI tokens (1 year)
uint256 public constant MAX_LOCK_TIME = 365 days
MIN_LOCK_TIME
Minimum lock time for vote-escrow (1 week)
uint256 public constant MIN_LOCK_TIME = 7 days
MAX_VE_QTI_MULTIPLIER
Maximum voting power multiplier (4x)
uint256 public constant MAX_VE_QTI_MULTIPLIER = 4
Functions
calculateVotingPowerMultiplier
Calculate voting power multiplier based on lock time
Calculates linear multiplier from 1x to 4x based on lock duration
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateVotingPowerMultiplier(uint256 lockTime) external pure returns (uint256 multiplier);
Parameters
| Name | Type | Description |
|---|---|---|
lockTime | uint256 | Duration of the lock |
Returns
| Name | Type | Description |
|---|---|---|
multiplier | uint256 | Voting power multiplier |
_calculateVotingPowerMultiplier
Internal function to calculate voting power multiplier
Calculates linear multiplier from 1x to 4x based on lock duration
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateVotingPowerMultiplier(uint256 lockTime) internal pure returns (uint256 multiplier);
Parameters
| Name | Type | Description |
|---|---|---|
lockTime | uint256 | Duration of the lock |
Returns
| Name | Type | Description |
|---|---|---|
multiplier | uint256 | Voting power multiplier |
calculateVotingPower
Calculate voting power with overflow protection
Calculates voting power based on amount and lock time with overflow protection
Notes:
-
security: Prevents overflow in voting power calculations
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if result exceeds uint96 max
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateVotingPower(uint256 amount, uint256 lockTime) external pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of QTI tokens to lock |
lockTime | uint256 | Duration to lock tokens |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | votingPower Calculated voting power |
_calculateVotingPower
Internal function to calculate voting power with overflow protection
Calculates voting power based on amount and lock time with overflow protection
Notes:
-
security: Prevents overflow in voting power calculations
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if result exceeds uint96 max
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateVotingPower(uint256 amount, uint256 lockTime) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Amount of QTI tokens to lock |
lockTime | uint256 | Duration to lock tokens |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | votingPower Calculated voting power |
calculateCurrentVotingPower
Calculate current voting power with linear decay
Calculates current voting power with linear decay over time
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateCurrentVotingPower(LockInfo memory lockInfo, uint256 currentTime)
external
pure
returns (uint256 votingPower);
Parameters
| Name | Type | Description |
|---|---|---|
lockInfo | LockInfo | Lock information structure |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
votingPower | uint256 | Current voting power of the user (decays linearly over time) |
calculateUnlockTime
Calculate unlock time with proper validation
Calculates new unlock time based on current timestamp and lock duration
Notes:
-
security: Prevents timestamp overflow in unlock time calculations
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidTime if result exceeds uint32 max
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateUnlockTime(uint256 currentTimestamp, uint256 lockTime, uint256 existingUnlockTime)
external
pure
returns (uint256 newUnlockTime);
Parameters
| Name | Type | Description |
|---|---|---|
currentTimestamp | uint256 | Current timestamp for calculation |
lockTime | uint256 | Duration to lock tokens |
existingUnlockTime | uint256 | Existing unlock time if already locked |
Returns
| Name | Type | Description |
|---|---|---|
newUnlockTime | uint256 | Calculated unlock time |
_calculateUnlockTime
Internal function to calculate unlock time with proper validation
Calculates new unlock time based on current timestamp and lock duration
Notes:
-
security: Prevents timestamp overflow in unlock time calculations
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidTime if result exceeds uint32 max
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateUnlockTime(uint256 currentTimestamp, uint256 lockTime, uint256 existingUnlockTime)
internal
pure
returns (uint256 newUnlockTime);
Parameters
| Name | Type | Description |
|---|---|---|
currentTimestamp | uint256 | Current timestamp for calculation |
lockTime | uint256 | Duration to lock tokens |
existingUnlockTime | uint256 | Existing unlock time if already locked |
Returns
| Name | Type | Description |
|---|---|---|
newUnlockTime | uint256 | Calculated unlock time |
validateAndCalculateTotalAmount
Validate all amounts and lock times, returns total amount
Ensures all amounts and lock times are valid and calculates total amount
Notes:
-
security: Prevents invalid amounts and lock times from being processed
-
validation: Validates amounts are positive and lock times are within bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws various validation errors for invalid inputs
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function validateAndCalculateTotalAmount(uint256[] calldata amounts, uint256[] calldata lockTimes)
external
pure
returns (uint256 totalAmount);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts to lock |
lockTimes | uint256[] | Array of lock durations |
Returns
| Name | Type | Description |
|---|---|---|
totalAmount | uint256 | Total amount of QTI to be locked |
processBatchLocks
Process batch locks and calculate totals
Processes batch lock operations and calculates total voting power and amounts
Notes:
-
security: Prevents overflow in batch calculations
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function processBatchLocks(
uint256[] calldata amounts,
uint256[] calldata lockTimes,
uint256 currentTimestamp,
uint256 existingUnlockTime
)
external
pure
returns (
uint256 totalNewVotingPower,
uint256 totalNewAmount,
uint256 finalUnlockTime,
uint256 finalLockTime,
uint256[] memory veQTIAmounts
);
Parameters
| Name | Type | Description |
|---|---|---|
amounts | uint256[] | Array of QTI amounts to lock |
lockTimes | uint256[] | Array of lock durations |
currentTimestamp | uint256 | Current timestamp |
existingUnlockTime | uint256 | Existing unlock time if already locked |
Returns
| Name | Type | Description |
|---|---|---|
totalNewVotingPower | uint256 | Total new voting power from all locks |
totalNewAmount | uint256 | Total new amount locked |
finalUnlockTime | uint256 | Final unlock time after all locks |
finalLockTime | uint256 | Final lock time |
veQTIAmounts | uint256[] | Array of calculated voting power amounts |
updateLockInfo
Update lock info with overflow checks
Updates user's lock information with new amounts and times
Notes:
-
security: Prevents overflow in lock info updates
-
validation: Validates amounts and times are within bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if values exceed uint96 max
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function updateLockInfo(
uint256 totalNewAmount,
uint256 newUnlockTime,
uint256 totalNewVotingPower,
uint256 lockTime
) external pure returns (LockInfo memory updatedLockInfo);
Parameters
| Name | Type | Description |
|---|---|---|
totalNewAmount | uint256 | Total new amount to lock |
newUnlockTime | uint256 | New unlock time |
totalNewVotingPower | uint256 | Total new voting power |
lockTime | uint256 | Lock duration |
Returns
| Name | Type | Description |
|---|---|---|
updatedLockInfo | LockInfo | Updated lock information |
calculateDecentralizationLevel
Calculate decentralization level based on time elapsed
Calculates decentralization level based on elapsed time since start
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateDecentralizationLevel(
uint256 currentTime,
uint256 decentralizationStartTime,
uint256 decentralizationDuration,
uint256 maxTimeElapsed
) external pure returns (uint256 newLevel);
Parameters
| Name | Type | Description |
|---|---|---|
currentTime | uint256 | Current timestamp |
decentralizationStartTime | uint256 | Start time for decentralization |
decentralizationDuration | uint256 | Total duration for decentralization |
maxTimeElapsed | uint256 | Maximum time elapsed to consider |
Returns
| Name | Type | Description |
|---|---|---|
newLevel | uint256 | New decentralization level (0-10000) |
Structs
LockInfo
Lock information structure
struct LockInfo {
uint96 amount; // Amount of QTI locked
uint32 unlockTime; // Timestamp when lock expires
uint96 votingPower; // Current voting power
uint32 lastClaimTime; // Last claim time (for future use)
uint96 initialVotingPower; // Initial voting power when locked
uint32 lockTime; // Original lock duration
}
TimeProvider
Inherits: Initializable, AccessControlUpgradeable, UUPSUpgradeable
Centralized time provider for the Quantillon Protocol
Provides a controlled time source that can be adjusted for testing and emergency scenarios SECURITY CONSIDERATIONS:
- Only governance can adjust time offset
- Time offset is limited to prevent abuse
- Emergency reset capability for security incidents
- All time adjustments are logged for transparency
State Variables
GOVERNANCE_ROLE
Role identifier for governance operations
bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE")
EMERGENCY_ROLE
Role identifier for emergency operations
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
UPGRADER_ROLE
Role identifier for upgrade operations
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE")
MAX_TIME_OFFSET
Maximum allowed time offset (7 days) to prevent abuse
uint256 public constant MAX_TIME_OFFSET = 7 days
MAX_TIME_DRIFT
Maximum allowed time drift (1 hour) for normal operations
uint256 public constant MAX_TIME_DRIFT = 1 hours
timeOffset
Current time offset applied to block.timestamp
Can be positive (time advancement) or negative (time delay) within limits
int256 public timeOffset
lastOffsetChange
Timestamp when the time offset was last modified
uint256 public lastOffsetChange
emergencyMode
Flag indicating if time provider is in emergency mode
bool public emergencyMode
adjustmentCounter
Counter for time adjustments (for tracking)
uint256 public adjustmentCounter
Functions
whenNotEmergency
Ensures the contract is not in emergency mode
modifier whenNotEmergency() ;
validTimeOffset
Ensures the time offset is within allowed bounds
modifier validTimeOffset(int256 offset) ;
constructor
Constructor for TimeProvider contract
Disables initializers for proxy pattern compatibility
Notes:
-
security: No security validations required - constructor
-
validation: No input validation required - constructor
-
state-changes: Disables initializers for proxy pattern
-
events: No events emitted
-
errors: No errors thrown - safe constructor
-
reentrancy: Not applicable - constructor
-
access: Public - anyone can deploy
-
oracle: No oracle dependencies
-
oz-upgrades-unsafe-allow: constructor
constructor() ;
initialize
Initializes the TimeProvider contract
Sets up access control roles and initializes state variables
Notes:
-
security: Validates all addresses are not zero, grants admin roles
-
validation: Validates all input addresses are not address(0)
-
state-changes: Initializes all state variables, sets default values
-
events: No events emitted during initialization
-
errors: Throws ZeroAddress if any address is address(0)
-
reentrancy: Protected by initializer modifier
-
access: Public - only callable once during deployment
-
oracle: No oracle dependencies
function initialize(address admin, address governance, address emergency) external initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | The address that will be granted DEFAULT_ADMIN_ROLE |
governance | address | The address that will be granted GOVERNANCE_ROLE |
emergency | address | The address that will be granted EMERGENCY_ROLE |
currentTime
Returns the current time according to this provider
Returns block.timestamp adjusted by the current time offset
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query current time
-
oracle: No oracle dependencies
function currentTime() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current timestamp adjusted by the offset |
_getCurrentTime
Returns the current time according to this provider (internal)
Internal function that applies time offset to block.timestamp with underflow protection
Notes:
-
security: Validates time offset calculations to prevent underflow
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _getCurrentTime() internal view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Current timestamp adjusted by the offset |
rawTimestamp
Returns the raw block timestamp without any offset
Returns unmodified block.timestamp for comparison purposes
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query raw timestamp
-
oracle: No oracle dependencies
function rawTimestamp() external view returns (uint256);
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Raw block.timestamp |
isFuture
Checks if a timestamp is in the future according to provider time
Compares input timestamp with current provider time
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check if timestamp is future
-
oracle: No oracle dependencies
function isFuture(uint256 timestamp) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
timestamp | uint256 | The timestamp to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if timestamp is in the future |
isPast
Checks if a timestamp is in the past according to provider time
Compares input timestamp with current provider time
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check if timestamp is past
-
oracle: No oracle dependencies
function isPast(uint256 timestamp) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
timestamp | uint256 | The timestamp to check |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if timestamp is in the past |
setTimeOffset
Sets the time offset (governance only)
Allows governance to set a new time offset within allowed bounds
Notes:
-
security: Validates governance role and time offset bounds
-
validation: Validates newOffset is within MAX_TIME_OFFSET limits
-
state-changes: Updates timeOffset, lastOffsetChange, adjustmentCounter
-
events: Emits TimeOffsetChanged with old and new offset values
-
errors: Throws InvalidAmount if offset exceeds MAX_TIME_OFFSET
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function setTimeOffset(int256 newOffset, string calldata reason)
external
onlyRole(GOVERNANCE_ROLE)
whenNotEmergency
validTimeOffset(newOffset);
Parameters
| Name | Type | Description |
|---|---|---|
newOffset | int256 | The new time offset to apply |
reason | string | Human-readable reason for the change |
advanceTime
Advances time by a specific amount (governance only)
Adds advancement to current time offset, handling both positive and negative offsets
Notes:
-
security: Validates governance role and advancement amount
-
validation: Validates advancement > 0 and resulting offset within bounds
-
state-changes: Updates timeOffset, lastOffsetChange, adjustmentCounter
-
events: Emits TimeOffsetChanged with old and new offset values
-
errors: Throws InvalidAmount if advancement is 0 or exceeds bounds
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function advanceTime(uint256 advancement, string calldata reason)
external
onlyRole(GOVERNANCE_ROLE)
whenNotEmergency;
Parameters
| Name | Type | Description |
|---|---|---|
advancement | uint256 | Amount of time to advance (in seconds) |
reason | string | Human-readable reason for the advancement |
resetTime
Resets time to normal (no offset)
Sets time offset to 0, returning to normal block.timestamp behavior
Notes:
-
security: Validates governance role authorization
-
validation: No input validation required
-
state-changes: Updates timeOffset to 0, lastOffsetChange, adjustmentCounter
-
events: Emits TimeReset and TimeOffsetChanged events
-
errors: No errors thrown - safe reset operation
-
reentrancy: Not protected - no external calls
-
access: Restricted to GOVERNANCE_ROLE
-
oracle: No oracle dependencies
function resetTime() external onlyRole(GOVERNANCE_ROLE);
setEmergencyMode
Toggles emergency mode (emergency role only)
Enables or disables emergency mode, automatically resetting time offset when enabled
Notes:
-
security: Validates emergency role authorization
-
validation: No input validation required
-
state-changes: Updates emergencyMode flag, resets timeOffset if enabling
-
events: Emits EmergencyModeChanged and TimeOffsetChanged if reset
-
errors: No errors thrown - safe mode toggle
-
reentrancy: Not protected - no external calls
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies
function setEmergencyMode(bool enabled) external onlyRole(EMERGENCY_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
enabled | bool | Whether to enable or disable emergency mode |
emergencyResetTime
Emergency time reset (emergency role only)
Emergency function to immediately reset time offset to 0
Notes:
-
security: Validates emergency role authorization
-
validation: No input validation required
-
state-changes: Updates timeOffset to 0, lastOffsetChange, adjustmentCounter
-
events: Emits TimeReset and TimeOffsetChanged events
-
errors: No errors thrown - safe emergency reset
-
reentrancy: Not protected - no external calls
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies
function emergencyResetTime() external onlyRole(EMERGENCY_ROLE);
getTimeInfo
Returns detailed time information
Provides comprehensive time data including provider time, raw timestamp, offset, and emergency status
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query time information
-
oracle: No oracle dependencies
function getTimeInfo()
external
view
returns (uint256 currentProviderTime, uint256 rawBlockTimestamp, int256 currentOffset, bool isEmergency);
Returns
| Name | Type | Description |
|---|---|---|
currentProviderTime | uint256 | Current time according to provider |
rawBlockTimestamp | uint256 | Raw block timestamp |
currentOffset | int256 | Current time offset |
isEmergency | bool | Whether emergency mode is active |
timeDiff
Calculates time difference between two timestamps according to provider
Pure function that calculates signed time difference between two timestamps
Notes:
-
security: No security validations required - pure function
-
validation: No input validation required - pure function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - pure function
-
access: Public - anyone can calculate time difference
-
oracle: No oracle dependencies
function timeDiff(uint256 timestamp1, uint256 timestamp2) external pure returns (int256);
Parameters
| Name | Type | Description |
|---|---|---|
timestamp1 | uint256 | First timestamp |
timestamp2 | uint256 | Second timestamp |
Returns
| Name | Type | Description |
|---|---|---|
<none> | int256 | Time difference (timestamp1 - timestamp2) |
_authorizeUpgrade
Authorizes contract upgrades
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function _authorizeUpgrade(address newImplementation) internal view override onlyRole(UPGRADER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
Events
TimeOffsetChanged
Emitted when time offset is changed
event TimeOffsetChanged(
address indexed changer, int256 oldOffset, int256 newOffset, string reason, uint256 timestamp
);
EmergencyModeChanged
Emitted when emergency mode is toggled
event EmergencyModeChanged(bool enabled, address indexed changer, uint256 timestamp);
TimeReset
Emitted when time is reset to normal
event TimeReset(address indexed resetter, uint256 timestamp);
TokenErrorLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Token-specific errors for QEURO, QTI, and stQEURO tokens
Main characteristics:
- Errors specific to token operations
- Minting and burning errors
- Blacklist and whitelist errors
- Supply and cap management errors
Note: security-contact: team@quantillon.money
Errors
MintingDisabled
error MintingDisabled();
BlacklistedAddress
error BlacklistedAddress();
NotWhitelisted
error NotWhitelisted();
WouldExceedLimit
error WouldExceedLimit();
CannotRecoverQEURO
error CannotRecoverQEURO();
CannotRecoverQTI
error CannotRecoverQTI();
NewCapBelowCurrentSupply
error NewCapBelowCurrentSupply();
LockTimeTooShort
error LockTimeTooShort();
LockTimeTooLong
error LockTimeTooLong();
LockNotExpired
error LockNotExpired();
NothingToUnlock
error NothingToUnlock();
InsufficientBalance
error InsufficientBalance();
InvalidAmount
error InvalidAmount();
InvalidTime
error InvalidTime();
RateLimitExceeded
error RateLimitExceeded();
AlreadyBlacklisted
error AlreadyBlacklisted();
NotBlacklisted
error NotBlacklisted();
AlreadyWhitelisted
error AlreadyWhitelisted();
PrecisionTooHigh
error PrecisionTooHigh();
TooManyDecimals
error TooManyDecimals();
InvalidAddress
error InvalidAddress();
TokenTransferFailed
error TokenTransferFailed();
ArrayLengthMismatch
error ArrayLengthMismatch();
BatchSizeTooLarge
error BatchSizeTooLarge();
RateLimitTooHigh
error RateLimitTooHigh();
InsufficientVotingPower
error InsufficientVotingPower();
VotingPeriodTooShort
error VotingPeriodTooShort();
VotingPeriodTooLong
error VotingPeriodTooLong();
VotingNotStarted
error VotingNotStarted();
VotingEnded
error VotingEnded();
AlreadyVoted
error AlreadyVoted();
NoVotingPower
error NoVotingPower();
VotingNotEnded
error VotingNotEnded();
ProposalAlreadyExecuted
error ProposalAlreadyExecuted();
ProposalCanceled
error ProposalCanceled();
ProposalFailed
error ProposalFailed();
QuorumNotMet
error QuorumNotMet();
NotAuthorized
error NotAuthorized();
ProposalAlreadyCanceled
error ProposalAlreadyCanceled();
ZeroAddress
error ZeroAddress();
CannotRecoverOwnToken
error CannotRecoverOwnToken();
NoETHToRecover
error NoETHToRecover();
InvalidAdmin
error InvalidAdmin();
InvalidToken
error InvalidToken();
InvalidTreasury
error InvalidTreasury();
AboveLimit
error AboveLimit();
TokenLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Library for essential token operations to reduce contract bytecode size
This library provides core token validation functions:
- Mint and burn parameter validation with supply cap checks
- Used by QEURO token for secure minting and burning operations
Note: security-contact: team@quantillon.money
Functions
validateMint
Validates mint parameters
Ensures minting doesn't exceed maximum supply and validates parameters
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function validateMint(address to, uint256 amount, uint256 totalSupply, uint256 maxSupply) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | Address to mint to |
amount | uint256 | Amount to mint |
totalSupply | uint256 | Current total supply |
maxSupply | uint256 | Maximum supply cap |
validateBurn
Validates burn parameters
Ensures sufficient balance and validates parameters for burning
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function validateBurn(address from, uint256 amount, uint256 balance) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | Address to burn from |
amount | uint256 | Amount to burn |
balance | uint256 | Current balance |
TokenValidationLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Token-specific validation functions for Quantillon Protocol
Main characteristics:
- Validation functions specific to token operations
- Fee and threshold validations
- Oracle price validations
- Treasury address validations
Note: security-contact: team@quantillon.money
Functions
validateFee
Validates fee amount against maximum allowed fee
Ensures fees don't exceed protocol limits (typically in basis points)
Notes:
-
security: Prevents excessive fees that could harm users
-
validation: Ensures fees stay within protocol limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws AboveLimit if fee exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateFee(uint256 fee, uint256 maxFee) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
fee | uint256 | The fee amount to validate |
maxFee | uint256 | The maximum allowed fee |
validateThreshold
Validates threshold value against maximum limit
Used for liquidation thresholds, margin ratios, etc.
Notes:
-
security: Prevents thresholds that could destabilize the system
-
validation: Ensures thresholds stay within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws AboveLimit if threshold exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateThreshold(uint256 threshold, uint256 maxThreshold) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
threshold | uint256 | The threshold value to validate |
maxThreshold | uint256 | The maximum allowed threshold |
validateThresholdValue
Validates that a value meets minimum threshold requirements
Used for minimum deposits, stakes, withdrawals, etc.
Notes:
-
security: Prevents operations below minimum thresholds
-
validation: Ensures values meet business requirements
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws BelowThreshold if value is below minimum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateThresholdValue(uint256 value, uint256 threshold) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
value | uint256 | The value to validate |
threshold | uint256 | The minimum required threshold |
validateOraclePrice
Validates oracle price data integrity
Ensures oracle price is valid before using in calculations
Notes:
-
security: Prevents use of invalid oracle data that could cause financial losses
-
validation: Ensures oracle price data is valid and recent
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter if oracle price is invalid
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: Validates oracle price data integrity
function validateOraclePrice(bool isValid) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
isValid | bool | Whether the oracle price is valid and recent |
validateTreasuryAddress
Validates treasury address is not zero address
Prevents setting treasury to zero address which could cause loss of funds
Notes:
-
security: Prevents loss of funds by ensuring treasury is properly set
-
validation: Ensures treasury address is valid for fund operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws ZeroAddress if treasury is zero address
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTreasuryAddress(address treasury) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | The treasury address to validate |
validatePositiveAmount
Validates that an amount is positive (greater than zero)
Essential for token amounts, deposits, withdrawals, etc.
Notes:
-
security: Prevents zero-amount operations that could cause issues
-
validation: Ensures amount is positive for meaningful operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if amount is zero
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositiveAmount(uint256 amount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
TreasuryRecoveryLibrary
Author: Quantillon Protocol Team
Library for secure token and ETH recovery to treasury addresses
This library factorizes the recoverToken and recoverETH functionality used across all contracts to save gas, reduce bytecode, and ensure consistent security implementation
Note: security-contact: team@quantillon.money
Functions
recoverToken
Recover tokens accidentally sent to the contract to treasury only
SECURITY: Prevents recovery of own tokens and sends only to treasury
Gas optimization: Uses library function to avoid code duplication
Security: Prevents recovery of own tokens and ensures treasury-only recovery
Error handling: Uses custom errors for gas efficiency
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverToken(address token, uint256 amount, address contractAddress, address treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Token address to recover |
amount | uint256 | Amount to recover |
contractAddress | address | Address of the calling contract (for own token check) |
treasury | address | Treasury address to send recovered tokens to |
recoverETH
Recover ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Gas optimization: Uses library function to avoid code duplication
Security: Prevents arbitrary ETH transfers that could be exploited
Error handling: Uses custom errors for gas efficiency
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH(address treasury) external;
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | The contract's treasury address |
UserPoolStakingLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Staking and reward calculation functions for UserPool to reduce contract size
Extracted from UserPool to reduce bytecode size and improve maintainability
Note: security-contact: team@quantillon.money
State Variables
MIN_STAKE_AMOUNT
uint256 public constant MIN_STAKE_AMOUNT = 1e18
MAX_STAKE_AMOUNT
uint256 public constant MAX_STAKE_AMOUNT = 1000000e18
MIN_STAKE_DURATION
uint256 public constant MIN_STAKE_DURATION = 1 days
MAX_STAKE_DURATION
uint256 public constant MAX_STAKE_DURATION = 365 days
UNSTAKE_COOLDOWN
uint256 public constant UNSTAKE_COOLDOWN = 7 days
REWARD_CLAIM_COOLDOWN
uint256 public constant REWARD_CLAIM_COOLDOWN = 1 days
Functions
_calculateStakingRewards
Calculates staking rewards for a user
Internal function to calculate rewards based on stake duration and APY
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateStakingRewards(StakeInfo memory stakeInfo, uint256 stakingAPY, uint256 currentTime)
internal
pure
returns (uint256 rewards);
Parameters
| Name | Type | Description |
|---|---|---|
stakeInfo | StakeInfo | Stake information |
stakingAPY | uint256 | Staking APY in basis points |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
rewards | uint256 | Calculated rewards |
calculateStakingRewards
Public wrapper for calculateStakingRewards
Public interface for calculating staking rewards
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateStakingRewards(StakeInfo memory stakeInfo, uint256 stakingAPY, uint256 currentTime)
external
pure
returns (uint256 rewards);
Parameters
| Name | Type | Description |
|---|---|---|
stakeInfo | StakeInfo | Stake information |
stakingAPY | uint256 | Staking APY in basis points |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
rewards | uint256 | Calculated rewards |
calculateTotalStakingRewards
Calculates total staking rewards for a user
Calculates total rewards across all active stakes for a user
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateTotalStakingRewards(StakeInfo[] memory userStakes, uint256 stakingAPY, uint256 currentTime)
external
pure
returns (uint256 totalRewards);
Parameters
| Name | Type | Description |
|---|---|---|
userStakes | StakeInfo[] | Array of user stakes |
stakingAPY | uint256 | Staking APY in basis points |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
totalRewards | uint256 | Total rewards for all stakes |
validateStakeParameters
Validates stake parameters
Ensures stake parameters are within acceptable bounds
Notes:
-
security: Prevents invalid stake parameters from being processed
-
validation: Validates amounts, durations, and user limits
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws various validation errors for invalid inputs
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function validateStakeParameters(uint256 amount, uint256 duration, UserStakingData memory userStakingData)
external
pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Stake amount |
duration | uint256 | Stake duration |
userStakingData | UserStakingData | User's current staking data |
validateUnstakeParameters
Validates unstake parameters
Ensures unstake operations meet minimum requirements
Notes:
-
security: Prevents premature unstaking and enforces cooldowns
-
validation: Validates stake status and timing requirements
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws various validation errors for invalid unstake attempts
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function validateUnstakeParameters(StakeInfo memory stakeInfo, uint256 currentTime) external pure;
Parameters
| Name | Type | Description |
|---|---|---|
stakeInfo | StakeInfo | Stake information |
currentTime | uint256 | Current timestamp |
calculateUnstakePenalty
Calculates unstake penalty
Calculates penalty based on stake duration to discourage early unstaking
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateUnstakePenalty(StakeInfo memory stakeInfo, uint256 currentTime)
external
pure
returns (uint256 penalty);
Parameters
| Name | Type | Description |
|---|---|---|
stakeInfo | StakeInfo | Stake information |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
penalty | uint256 | Penalty percentage in basis points |
calculateDepositAPY
Calculates deposit APY based on pool metrics
Adjusts deposit APY based on staking ratio to incentivize optimal behavior
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateDepositAPY(uint256 totalDeposits, uint256 totalStaked, uint256 baseAPY)
external
pure
returns (uint256 depositAPY);
Parameters
| Name | Type | Description |
|---|---|---|
totalDeposits | uint256 | Total pool deposits |
totalStaked | uint256 | Total staked amount |
baseAPY | uint256 | Base APY in basis points |
Returns
| Name | Type | Description |
|---|---|---|
depositAPY | uint256 | Calculated deposit APY |
calculateStakingAPY
Calculates staking APY based on pool metrics
Adjusts staking APY based on staking ratio to incentivize optimal behavior
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateStakingAPY(uint256 totalDeposits, uint256 totalStaked, uint256 baseAPY)
external
pure
returns (uint256 stakingAPY);
Parameters
| Name | Type | Description |
|---|---|---|
totalDeposits | uint256 | Total pool deposits |
totalStaked | uint256 | Total staked amount |
baseAPY | uint256 | Base APY in basis points |
Returns
| Name | Type | Description |
|---|---|---|
stakingAPY | uint256 | Calculated staking APY |
calculateDynamicFee
Calculates fee for deposit/withdrawal
Adjusts fees based on pool utilization to manage liquidity
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateDynamicFee(uint256 amount, uint256 baseFee, uint256 poolUtilization)
external
pure
returns (uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | Transaction amount |
baseFee | uint256 | Base fee in basis points |
poolUtilization | uint256 | Pool utilization ratio |
Returns
| Name | Type | Description |
|---|---|---|
fee | uint256 | Calculated fee amount |
calculatePoolMetrics
Calculates pool metrics
Packs pool metrics into a single uint256 for gas efficiency
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculatePoolMetrics(uint256 totalDeposits, uint256 totalStaked, uint256 totalUsers)
external
pure
returns (uint256 metrics);
Parameters
| Name | Type | Description |
|---|---|---|
totalDeposits | uint256 | Total pool deposits |
totalStaked | uint256 | Total staked amount |
totalUsers | uint256 | Total number of users |
Returns
| Name | Type | Description |
|---|---|---|
metrics | uint256 | Packed pool metrics |
unpackPoolMetrics
Unpacks pool metrics
Unpacks pool metrics from a single uint256 for gas efficiency
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function unpackPoolMetrics(uint256 metrics)
external
pure
returns (uint256 stakingRatio, uint256 averageDeposit, uint256 totalUsers);
Parameters
| Name | Type | Description |
|---|---|---|
metrics | uint256 | Packed pool metrics |
Returns
| Name | Type | Description |
|---|---|---|
stakingRatio | uint256 | Staking ratio in basis points |
averageDeposit | uint256 | Average deposit per user |
totalUsers | uint256 | Total number of users |
Structs
StakeInfo
struct StakeInfo {
uint256 amount;
uint256 startTime;
uint256 endTime;
uint256 lastRewardClaim;
uint256 totalRewardsClaimed;
bool isActive;
}
UserStakingData
struct UserStakingData {
uint256 totalStaked;
uint256 totalRewardsEarned;
uint256 totalRewardsClaimed;
uint256 lastStakeTime;
uint256 lastUnstakeTime;
uint256 activeStakes;
}
VaultErrorLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Vault-specific errors for QuantillonVault and related operations
Main characteristics:
- Errors specific to vault operations
- Collateralization and emergency mode errors
- Pool health and balance errors
- Yield distribution errors
Note: security-contact: team@quantillon.money
Errors
TokenTransferFailed
error TokenTransferFailed();
InsufficientCollateralization
error InsufficientCollateralization();
EmergencyModeActive
error EmergencyModeActive();
PoolNotHealthy
error PoolNotHealthy();
PoolRatioInvalid
error PoolRatioInvalid();
PoolSizeZero
error PoolSizeZero();
PoolImbalance
error PoolImbalance();
YieldBelowThreshold
error YieldBelowThreshold();
YieldNotAvailable
error YieldNotAvailable();
YieldDistributionFailed
error YieldDistributionFailed();
YieldCalculationError
error YieldCalculationError();
YieldClaimFailed
error YieldClaimFailed();
CannotRecoverUSDC
error CannotRecoverUSDC();
CannotRecoverAToken
error CannotRecoverAToken();
CannotRecoverOwnToken
error CannotRecoverOwnToken();
CannotRecoverCriticalToken
error CannotRecoverCriticalToken(string tokenName);
InvalidOraclePrice
error InvalidOraclePrice();
AavePoolNotHealthy
error AavePoolNotHealthy();
WouldExceedLimit
error WouldExceedLimit();
InsufficientBalance
error InsufficientBalance();
WouldBreachMinimum
error WouldBreachMinimum();
InvalidAmount
error InvalidAmount();
InvalidAddress
error InvalidAddress();
BelowThreshold
error BelowThreshold();
FeeTooHigh
error FeeTooHigh();
InvalidThreshold
error InvalidThreshold();
NoETHToRecover
error NoETHToRecover();
ExcessiveSlippage
error ExcessiveSlippage();
ConfigValueTooHigh
error ConfigValueTooHigh();
VaultMath
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Mathematical operations library for Quantillon Protocol
This library provides essential mathematical utilities:
- Percentage calculations for fees and yield distributions
- Min/max value selection for safe boundaries
- Decimal scaling utilities for different token precisions
Note: security-contact: team@quantillon.money
State Variables
BASIS_POINTS
Precision for percentage calculations (10000 = 100%)
uint256 public constant BASIS_POINTS = 10000
PRECISION
High precision scalar (18 decimals)
uint256 public constant PRECISION = 1e18
MAX_PERCENTAGE
Maximum allowed percentage (10000%)
uint256 public constant MAX_PERCENTAGE = 1000000
Functions
mulDiv
Multiply two numbers and divide by a third with rounding
Used by percentageOf for fee calculations
Notes:
-
security: Prevents division by zero and multiplication overflow
-
validation: Validates c != 0, checks for multiplication overflow
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws "Division by zero" if c is 0, "Multiplication overflow" if overflow
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function mulDiv(uint256 a, uint256 b, uint256 c) internal pure returns (uint256 result);
Parameters
| Name | Type | Description |
|---|---|---|
a | uint256 | First number |
b | uint256 | Second number |
c | uint256 | Divisor |
Returns
| Name | Type | Description |
|---|---|---|
result | uint256 | a * b / c with proper rounding |
percentageOf
Calculate percentage of a value
Used for fee calculations across all contracts
Notes:
-
security: Prevents percentage overflow and division by zero
-
validation: Validates percentage <= MAX_PERCENTAGE
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws "Percentage too high" if percentage > MAX_PERCENTAGE
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function percentageOf(uint256 value, uint256 percentage) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
value | uint256 | Base value |
percentage | uint256 | Percentage in basis points (e.g., 500 = 5%) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Calculated percentage value |
scaleDecimals
Scale a value between different decimal precisions with proper rounding
Used for converting between token precisions (e.g., USDC 6 decimals to 18 decimals)
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function scaleDecimals(uint256 value, uint8 fromDecimals, uint8 toDecimals)
internal
pure
returns (uint256 scaledValue);
Parameters
| Name | Type | Description |
|---|---|---|
value | uint256 | Original value |
fromDecimals | uint8 | Original decimal places |
toDecimals | uint8 | Target decimal places |
Returns
| Name | Type | Description |
|---|---|---|
scaledValue | uint256 | Scaled value with proper rounding |
min
Calculate minimum value between two numbers
Used for safe boundary calculations in yield management and vault operations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function min(uint256 a, uint256 b) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
a | uint256 | First number |
b | uint256 | Second number |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Minimum value |
max
Calculate maximum value between two numbers
Used in tests and edge case calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function max(uint256 a, uint256 b) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
a | uint256 | First number |
b | uint256 | Second number |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Maximum value |
eurToUsd
Convert EUR amount to USD using exchange rate
Used in tests for currency conversion
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function eurToUsd(uint256 eurAmount, uint256 eurUsdRate) internal pure returns (uint256 usdAmount);
Parameters
| Name | Type | Description |
|---|---|---|
eurAmount | uint256 | Amount in EUR (18 decimals) |
eurUsdRate | uint256 | EUR/USD exchange rate (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
usdAmount | uint256 | Amount in USD (18 decimals) |
usdToEur
Convert USD amount to EUR using exchange rate
Used in tests for currency conversion
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function usdToEur(uint256 usdAmount, uint256 eurUsdRate) internal pure returns (uint256 eurAmount);
Parameters
| Name | Type | Description |
|---|---|---|
usdAmount | uint256 | Amount in USD (18 decimals) |
eurUsdRate | uint256 | EUR/USD exchange rate (18 decimals) |
Returns
| Name | Type | Description |
|---|---|---|
eurAmount | uint256 | Amount in EUR (18 decimals) |
calculateCollateralRatio
Calculate collateralization ratio
Used in tests for collateral calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateCollateralRatio(uint256 collateralValue, uint256 debtValue)
internal
pure
returns (uint256 ratio);
Parameters
| Name | Type | Description |
|---|---|---|
collateralValue | uint256 | Total collateral value in USD |
debtValue | uint256 | Total debt value in USD |
Returns
| Name | Type | Description |
|---|---|---|
ratio | uint256 | Collateralization ratio in 18 decimals (e.g., 1.5e18 = 150%) |
calculateYieldDistribution
Calculate yield distribution between users and hedgers
Used in tests for yield calculations
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function calculateYieldDistribution(uint256 totalYield, uint256 yieldShiftBps)
internal
pure
returns (uint256 userYield, uint256 hedgerYield);
Parameters
| Name | Type | Description |
|---|---|---|
totalYield | uint256 | Total yield generated |
yieldShiftBps | uint256 | Yield shift percentage in basis points (0-10000) |
Returns
| Name | Type | Description |
|---|---|---|
userYield | uint256 | Yield allocated to QEURO users |
hedgerYield | uint256 | Yield allocated to hedgers |
isWithinTolerance
Check if a value is within a certain percentage of another value
Used in tests for tolerance checks
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function isWithinTolerance(uint256 value1, uint256 value2, uint256 toleranceBps) internal pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
value1 | uint256 | First value |
value2 | uint256 | Second value |
toleranceBps | uint256 | Tolerance in basis points |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | isWithinTolerance Whether values are within tolerance |
YieldShiftCalculationLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Calculation functions for YieldShift to reduce contract size
Extracted from YieldShift to reduce bytecode size
Note: security-contact: team@quantillon.money
Functions
calculateOptimalYieldShift
Calculates optimal yield shift based on pool ratio
Calculates optimal yield shift to balance user and hedger pools
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateOptimalYieldShift(
uint256 poolRatio,
uint256 baseYieldShift,
uint256 maxYieldShift,
uint256 targetPoolRatio
) external pure returns (uint256 optimalShift);
Parameters
| Name | Type | Description |
|---|---|---|
poolRatio | uint256 | Current pool ratio (user/hedger) |
baseYieldShift | uint256 | Base yield shift percentage |
maxYieldShift | uint256 | Maximum yield shift percentage |
targetPoolRatio | uint256 | Target pool ratio |
Returns
| Name | Type | Description |
|---|---|---|
optimalShift | uint256 | Optimal yield shift percentage |
applyGradualAdjustment
Applies gradual adjustment to yield shift
Gradually adjusts yield shift to prevent sudden changes
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function applyGradualAdjustment(uint256 currentShift, uint256 targetShift, uint256 adjustmentSpeed)
external
pure
returns (uint256 newShift);
Parameters
| Name | Type | Description |
|---|---|---|
currentShift | uint256 | Current yield shift |
targetShift | uint256 | Target yield shift |
adjustmentSpeed | uint256 | Adjustment speed (basis points per update) |
Returns
| Name | Type | Description |
|---|---|---|
newShift | uint256 | New yield shift after adjustment |
calculateUserAllocation
Calculates user allocation percentage
Calculates user allocation based on yield shift percentage
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateUserAllocation(uint256 yieldShift) external pure returns (uint256 userAllocation);
Parameters
| Name | Type | Description |
|---|---|---|
yieldShift | uint256 | Current yield shift percentage |
Returns
| Name | Type | Description |
|---|---|---|
userAllocation | uint256 | User allocation percentage |
calculateHedgerAllocation
Calculates hedger allocation percentage
Calculates hedger allocation based on yield shift percentage
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateHedgerAllocation(uint256 yieldShift) external pure returns (uint256 hedgerAllocation);
Parameters
| Name | Type | Description |
|---|---|---|
yieldShift | uint256 | Current yield shift percentage |
Returns
| Name | Type | Description |
|---|---|---|
hedgerAllocation | uint256 | Hedger allocation percentage |
calculatePoolTWAP
Calculates TWAP for pool sizes
Calculates time-weighted average price for pool sizes
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculatePoolTWAP(uint256[] memory snapshots)
external
pure
returns (uint256 userPoolTWAP, uint256 hedgerPoolTWAP);
Parameters
| Name | Type | Description |
|---|---|---|
snapshots | uint256[] | Array of pool snapshots |
Returns
| Name | Type | Description |
|---|---|---|
userPoolTWAP | uint256 | TWAP for user pool size |
hedgerPoolTWAP | uint256 | TWAP for hedger pool size |
calculateYieldDistribution
Calculates yield distribution amounts
Calculates yield distribution between users and hedgers
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateYieldDistribution(uint256 totalYield, uint256 userAllocation, uint256 hedgerAllocation)
external
pure
returns (uint256 userYield, uint256 hedgerYield);
Parameters
| Name | Type | Description |
|---|---|---|
totalYield | uint256 | Total yield to distribute |
userAllocation | uint256 | User allocation percentage |
hedgerAllocation | uint256 | Hedger allocation percentage |
Returns
| Name | Type | Description |
|---|---|---|
userYield | uint256 | User yield amount |
hedgerYield | uint256 | Hedger yield amount |
validateYieldShiftParams
Validates yield shift parameters
Ensures yield shift parameters are within valid bounds
Notes:
-
security: Prevents invalid yield shift parameters
-
validation: Validates all parameters are within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws require statements for invalid parameters
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function validateYieldShiftParams(
uint256 baseYieldShift,
uint256 maxYieldShift,
uint256 adjustmentSpeed,
uint256 targetPoolRatio
) external pure;
Parameters
| Name | Type | Description |
|---|---|---|
baseYieldShift | uint256 | Base yield shift |
maxYieldShift | uint256 | Maximum yield shift |
adjustmentSpeed | uint256 | Adjustment speed |
targetPoolRatio | uint256 | Target pool ratio |
YieldShiftOptimizationLibrary
Author: Quantillon Labs
Library for YieldShift pool metrics, historical data, and utility functions
Extracts utility functions from YieldShift to reduce contract size
State Variables
MIN_HOLDING_PERIOD
uint256 public constant MIN_HOLDING_PERIOD = 7 days
TWAP_PERIOD
uint256 public constant TWAP_PERIOD = 24 hours
MAX_TIME_ELAPSED
uint256 public constant MAX_TIME_ELAPSED = 365 days
MAX_HISTORY_LENGTH
uint256 public constant MAX_HISTORY_LENGTH = 100
Functions
getCurrentPoolMetrics
Get current pool metrics
Returns current pool sizes and ratio for yield shift calculations
Notes:
-
security: No security implications - view function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: No errors thrown - view function
-
reentrancy: Not applicable - view function
-
access: Public function
-
oracle: No oracle dependencies
function getCurrentPoolMetrics(address userPoolAddress, address hedgerPoolAddress)
external
view
returns (uint256 userPoolSize, uint256 hedgerPoolSize, uint256 poolRatio);
Parameters
| Name | Type | Description |
|---|---|---|
userPoolAddress | address | Address of the user pool contract |
hedgerPoolAddress | address | Address of the hedger pool contract |
Returns
| Name | Type | Description |
|---|---|---|
userPoolSize | uint256 | Current user pool size |
hedgerPoolSize | uint256 | Current hedger pool size |
poolRatio | uint256 | Ratio of user to hedger pool sizes |
getEligiblePoolMetrics
Get eligible pool metrics that only count deposits meeting holding period requirements
SECURITY: Prevents flash deposit attacks by excluding recent deposits from yield calculations
Notes:
-
security: Prevents flash deposit attacks by excluding recent deposits
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: No errors thrown - view function
-
reentrancy: Not applicable - view function
-
access: Public function
-
oracle: No oracle dependencies
function getEligiblePoolMetrics(
address userPoolAddress,
address hedgerPoolAddress,
uint256 currentTime,
uint256 lastUpdateTime
) external view returns (uint256 userPoolSize, uint256 hedgerPoolSize, uint256 poolRatio);
Parameters
| Name | Type | Description |
|---|---|---|
userPoolAddress | address | Address of the user pool contract |
hedgerPoolAddress | address | Address of the hedger pool contract |
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
userPoolSize | uint256 | Eligible user pool size (deposits older than MIN_HOLDING_PERIOD) |
hedgerPoolSize | uint256 | Eligible hedger pool size (deposits older than MIN_HOLDING_PERIOD) |
poolRatio | uint256 | Ratio of eligible pool sizes |
calculateEligibleUserPoolSize
Calculate eligible user pool size excluding recent deposits
Only counts deposits older than MIN_HOLDING_PERIOD
Notes:
-
security: Prevents flash deposit attacks by excluding recent deposits
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateEligibleUserPoolSize(uint256 totalUserPoolSize, uint256 currentTime, uint256 lastUpdateTime)
external
pure
returns (uint256 eligibleSize);
Parameters
| Name | Type | Description |
|---|---|---|
totalUserPoolSize | uint256 | Current total user pool size |
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
eligibleSize | uint256 | Eligible pool size for yield calculations |
_calculateEligibleUserPoolSize
Internal function to calculate eligible user pool size
Only counts deposits older than MIN_HOLDING_PERIOD
Notes:
-
security: Prevents flash deposit attacks by excluding recent deposits
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateEligibleUserPoolSize(uint256 totalUserPoolSize, uint256 currentTime, uint256 lastUpdateTime)
internal
pure
returns (uint256 eligibleSize);
Parameters
| Name | Type | Description |
|---|---|---|
totalUserPoolSize | uint256 | Current total user pool size |
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
eligibleSize | uint256 | Eligible pool size for yield calculations |
calculateEligibleHedgerPoolSize
Calculate eligible hedger pool size excluding recent deposits
Only counts deposits older than MIN_HOLDING_PERIOD
Notes:
-
security: Prevents flash deposit attacks by excluding recent deposits
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateEligibleHedgerPoolSize(uint256 totalHedgerPoolSize, uint256 currentTime, uint256 lastUpdateTime)
external
pure
returns (uint256 eligibleSize);
Parameters
| Name | Type | Description |
|---|---|---|
totalHedgerPoolSize | uint256 | Current total hedger pool size |
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
eligibleSize | uint256 | Eligible pool size for yield calculations |
_calculateEligibleHedgerPoolSize
Internal function to calculate eligible hedger pool size
Only counts deposits older than MIN_HOLDING_PERIOD
Notes:
-
security: Prevents flash deposit attacks by excluding recent deposits
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateEligibleHedgerPoolSize(uint256 totalHedgerPoolSize, uint256 currentTime, uint256 lastUpdateTime)
internal
pure
returns (uint256 eligibleSize);
Parameters
| Name | Type | Description |
|---|---|---|
totalHedgerPoolSize | uint256 | Current total hedger pool size |
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
eligibleSize | uint256 | Eligible pool size for yield calculations |
calculateHoldingPeriodDiscount
Calculate holding period discount based on recent deposit activity
Returns a percentage (in basis points) representing eligible deposits
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateHoldingPeriodDiscount(uint256 currentTime, uint256 lastUpdateTime)
external
pure
returns (uint256 discountBps);
Parameters
| Name | Type | Description |
|---|---|---|
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
discountBps | uint256 | Discount in basis points (10000 = 100%) |
_calculateHoldingPeriodDiscount
Internal function to calculate holding period discount
Returns a percentage (in basis points) representing eligible deposits
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling function
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Internal function
-
oracle: No oracle dependencies
function _calculateHoldingPeriodDiscount(uint256 currentTime, uint256 lastUpdateTime)
internal
pure
returns (uint256 discountBps);
Parameters
| Name | Type | Description |
|---|---|---|
currentTime | uint256 | Current timestamp |
lastUpdateTime | uint256 | Last update timestamp |
Returns
| Name | Type | Description |
|---|---|---|
discountBps | uint256 | Discount in basis points (10000 = 100%) |
getTimeWeightedAverage
Get time weighted average of pool history
Calculates time weighted average of pool history over a specified period
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function getTimeWeightedAverage(
PoolSnapshot[] memory poolHistory,
uint256 period,
bool isUserPool,
uint256 currentTime
) external pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolHistory | PoolSnapshot[] | Array of pool snapshots |
period | uint256 | Time period for calculation |
isUserPool | bool | Whether this is for user pool or hedger pool |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Time weighted average value |
addToPoolHistory
Add pool snapshot to history
Adds a pool snapshot to the history array with size management
Notes:
-
security: No security implications - pure function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function addToPoolHistory(
PoolSnapshot[] memory poolHistory,
uint256 poolSize,
bool isUserPool,
uint256 currentTime
) external pure returns (PoolSnapshot[] memory newHistory);
Parameters
| Name | Type | Description |
|---|---|---|
poolHistory | PoolSnapshot[] | Array of pool snapshots to add to |
poolSize | uint256 | Size of the pool to record |
isUserPool | bool | Whether this is for user pool or hedger pool |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
newHistory | PoolSnapshot[] | Updated pool history array |
calculateUserAllocation
Calculate user allocation from current yield shift
Calculates user allocation based on current yield shift percentage
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateUserAllocation(uint256 userYieldPool, uint256 hedgerYieldPool, uint256 currentYieldShift)
external
pure
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
userYieldPool | uint256 | Current user yield pool amount |
hedgerYieldPool | uint256 | Current hedger yield pool amount |
currentYieldShift | uint256 | Current yield shift percentage |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | User allocation amount based on current yield shift percentage |
calculateHedgerAllocation
Calculate hedger allocation from current yield shift
Calculates hedger allocation based on current yield shift percentage
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateHedgerAllocation(uint256 userYieldPool, uint256 hedgerYieldPool, uint256 currentYieldShift)
external
pure
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
userYieldPool | uint256 | Current user yield pool amount |
hedgerYieldPool | uint256 | Current hedger yield pool amount |
currentYieldShift | uint256 | Current yield shift percentage |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Hedger allocation amount based on current yield shift percentage |
isWithinTolerance
Check if a value is within tolerance of a target value
Checks if a value is within the specified tolerance of a target
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function isWithinTolerance(uint256 value, uint256 target, uint256 toleranceBps) external pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
value | uint256 | The value to check |
target | uint256 | The target value |
toleranceBps | uint256 | Tolerance in basis points (e.g., 1000 = 10%) |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if value is within tolerance, false otherwise |
calculateHistoricalYieldShift
Calculate historical yield shift metrics
Calculates statistical metrics for yield shift history
Notes:
-
security: No security implications - pure calculation function
-
validation: Input validation handled by calling contract
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - pure function
-
reentrancy: Not applicable - pure function
-
access: Public function
-
oracle: No oracle dependencies
function calculateHistoricalYieldShift(
YieldShiftSnapshot[] memory yieldShiftHistory,
uint256 period,
uint256 currentTime
) external pure returns (uint256 averageShift, uint256 maxShift, uint256 minShift, uint256 volatility);
Parameters
| Name | Type | Description |
|---|---|---|
yieldShiftHistory | YieldShiftSnapshot[] | Array of yield shift snapshots |
period | uint256 | Time period to analyze |
currentTime | uint256 | Current timestamp |
Returns
| Name | Type | Description |
|---|---|---|
averageShift | uint256 | Average yield shift during the period |
maxShift | uint256 | Maximum yield shift during the period |
minShift | uint256 | Minimum yield shift during the period |
volatility | uint256 | Volatility measure of yield shifts |
Structs
PoolSnapshot
struct PoolSnapshot {
uint64 timestamp;
uint128 userPoolSize;
uint128 hedgerPoolSize;
}
YieldShiftSnapshot
struct YieldShiftSnapshot {
uint128 yieldShift;
uint64 timestamp;
}
YieldValidationLibrary
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
Yield-specific validation functions for Quantillon Protocol
Main characteristics:
- Validation functions specific to yield operations
- Yield shift mechanism validations
- Slippage protection validations
- Yield distribution validations
Note: security-contact: team@quantillon.money
Functions
validateYieldShift
Validates yield shift percentage (0-100%)
Ensures yield shift is within valid range of 0-10000 basis points
Notes:
-
security: Prevents invalid yield shifts that could destabilize yield distribution
-
validation: Ensures yield shift is within valid percentage range
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter if shift exceeds 100%
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateYieldShift(uint256 shift) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
shift | uint256 | The yield shift percentage to validate (in basis points) |
validateAdjustmentSpeed
Validates adjustment speed for yield shift mechanisms
Prevents excessively fast adjustments that could destabilize the system
Notes:
-
security: Prevents rapid adjustments that could destabilize yield mechanisms
-
validation: Ensures adjustment speed stays within safe bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter if speed exceeds maximum
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateAdjustmentSpeed(uint256 speed, uint256 maxSpeed) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
speed | uint256 | The adjustment speed to validate |
maxSpeed | uint256 | The maximum allowed adjustment speed |
validateTargetRatio
Validates target ratio for yield distribution mechanisms
Ensures ratio is positive and within acceptable bounds
Notes:
-
security: Prevents invalid ratios that could break yield distribution
-
validation: Ensures ratio is positive and within acceptable bounds
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidParameter or AboveLimit based on validation
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTargetRatio(uint256 ratio, uint256 maxRatio) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
ratio | uint256 | The target ratio to validate |
maxRatio | uint256 | The maximum allowed ratio |
validateSlippage
Validates slippage protection for token swaps/trades
Ensures received amount is within acceptable tolerance of expected
Notes:
-
security: Prevents excessive slippage attacks in yield operations
-
validation: Ensures received amount meets minimum expectations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws ExcessiveSlippage if slippage exceeds tolerance
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateSlippage(uint256 received, uint256 expected, uint256 tolerance) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
received | uint256 | The actual amount received |
expected | uint256 | The expected amount |
tolerance | uint256 | The slippage tolerance in basis points |
validateTreasuryAddress
Validates treasury address is not zero address
Prevents setting treasury to zero address which could cause loss of funds
Notes:
-
security: Prevents loss of funds by ensuring treasury is properly set
-
validation: Ensures treasury address is valid for fund operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws ZeroAddress if treasury is zero address
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validateTreasuryAddress(address treasury) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
treasury | address | The treasury address to validate |
validatePositiveAmount
Validates that an amount is positive (greater than zero)
Essential for token amounts, deposits, withdrawals, etc.
Notes:
-
security: Prevents zero-amount operations that could cause issues
-
validation: Ensures amount is positive for meaningful operations
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws InvalidAmount if amount is zero
-
reentrancy: Not applicable - pure function
-
access: Internal library function
-
oracle: No oracle dependencies
function validatePositiveAmount(uint256 amount) internal pure;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount to validate |
Contents
MockChainlinkOracle
Inherits: IChainlinkOracle, Initializable, AccessControlUpgradeable, PausableUpgradeable
Author: Quantillon Labs
Mock oracle that implements IChainlinkOracle interface but uses mock feeds
Used for localhost testing - provides same interface as ChainlinkOracle
State Variables
EMERGENCY_ROLE
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
eurUsdPriceFeed
AggregatorV3Interface public eurUsdPriceFeed
usdcUsdPriceFeed
AggregatorV3Interface public usdcUsdPriceFeed
treasury
address public treasury
originalAdmin
address private originalAdmin
MIN_EUR_USD_PRICE
uint256 public constant MIN_EUR_USD_PRICE = 0.5e18
MAX_EUR_USD_PRICE
uint256 public constant MAX_EUR_USD_PRICE = 2.0e18
MIN_USDC_USD_PRICE
uint256 public constant MIN_USDC_USD_PRICE = 0.95e18
MAX_USDC_USD_PRICE
uint256 public constant MAX_USDC_USD_PRICE = 1.05e18
MAX_PRICE_DEVIATION
uint256 public constant MAX_PRICE_DEVIATION = 500
lastValidEurUsdPrice
uint256 public lastValidEurUsdPrice
lastValidUsdcUsdPrice
uint256 public lastValidUsdcUsdPrice
lastPriceUpdateBlock
uint256 public lastPriceUpdateBlock
MIN_BLOCKS_BETWEEN_UPDATES
uint256 public constant MIN_BLOCKS_BETWEEN_UPDATES = 1
circuitBreakerTriggered
bool public circuitBreakerTriggered
Functions
constructor
Note: oz-upgrades-unsafe-allow: constructor
constructor() ;
initialize
Initializes the mock oracle
function initialize(
address admin,
address _eurUsdPriceFeed,
address _usdcUsdPriceFeed,
address /* _treasury */
)
external
initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Admin address |
_eurUsdPriceFeed | address | Mock EUR/USD feed address |
_usdcUsdPriceFeed | address | Mock USDC/USD feed address |
<none> | address |
getEurUsdPrice
Gets the current EUR/USD price with validation and auto-updates lastValidEurUsdPrice
function getEurUsdPrice() external view override returns (uint256 price, bool isValid);
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | EUR/USD price in 18 decimals |
isValid | bool | True if price is valid and fresh |
getUsdcUsdPrice
Gets the current USDC/USD price with validation
function getUsdcUsdPrice() external view override returns (uint256 price, bool isValid);
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | USDC/USD price in 18 decimals |
isValid | bool | True if price is valid and fresh |
_updatePrices
Updates prices and validates them
Internal function to update and validate current prices
function _updatePrices() internal;
_calculateEurUsdPrice
Internal function to calculate EUR/USD price
Avoids external calls to prevent reentrancy
function _calculateEurUsdPrice() internal pure returns (uint256);
_calculateUsdcUsdPrice
Internal function to calculate USDC/USD price
Avoids external calls to prevent reentrancy
function _calculateUsdcUsdPrice() internal pure returns (uint256);
_scalePrice
Scales price from feed decimals to 18 decimals
function _scalePrice(int256 price, uint8 feedDecimals) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
price | int256 | Price from feed |
feedDecimals | uint8 | Number of decimals in the feed |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Scaled price in 18 decimals |
_divRound
Divides with rounding
function _divRound(uint256 a, uint256 b) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
a | uint256 | Numerator |
b | uint256 | Denominator |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Result with rounding |
updateTreasury
Updates treasury address
Treasury can only be updated to the original admin address to prevent arbitrary sends
function updateTreasury(address _treasury) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
unpause
Unpauses the contract
function unpause() external onlyRole(EMERGENCY_ROLE);
recoverETH
Recovers ETH sent to the contract
Only sends ETH to the original admin address to prevent arbitrary sends
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
resetCircuitBreaker
Resets the circuit breaker
function resetCircuitBreaker() external onlyRole(EMERGENCY_ROLE);
triggerCircuitBreaker
Triggers the circuit breaker
function triggerCircuitBreaker() external onlyRole(EMERGENCY_ROLE);
pause
Pauses the contract
function pause() external onlyRole(EMERGENCY_ROLE);
receive
receive() external payable;
getOracleHealth
Mock implementation of getOracleHealth
function getOracleHealth() external pure override returns (bool isHealthy, bool eurUsdFresh, bool usdcUsdFresh);
getEurUsdDetails
Mock implementation of getEurUsdDetails
function getEurUsdDetails()
external
view
override
returns (uint256 currentPrice, uint256 lastValidPrice, uint256 lastUpdate, bool isStale, bool withinBounds);
getOracleConfig
Mock implementation of getOracleConfig
function getOracleConfig()
external
view
override
returns (
uint256 minPrice,
uint256 maxPrice,
uint256 maxStaleness,
uint256 usdcTolerance,
bool circuitBreakerActive
);
getPriceFeedAddresses
Mock implementation of getPriceFeedAddresses
function getPriceFeedAddresses()
external
view
override
returns (address eurUsdFeedAddress, address usdcUsdFeedAddress, uint8 eurUsdDecimals, uint8 usdcUsdDecimals);
checkPriceFeedConnectivity
Mock implementation of checkPriceFeedConnectivity
function checkPriceFeedConnectivity()
external
view
override
returns (bool eurUsdConnected, bool usdcUsdConnected, uint80 eurUsdLatestRound, uint80 usdcUsdLatestRound);
updatePriceBounds
Mock implementation of updatePriceBounds
function updatePriceBounds(uint256 _minPrice, uint256 _maxPrice) external override onlyRole(DEFAULT_ADMIN_ROLE);
updateUsdcTolerance
Mock implementation of updateUsdcTolerance
function updateUsdcTolerance(uint256 newToleranceBps) external override onlyRole(DEFAULT_ADMIN_ROLE);
updatePriceFeeds
Mock implementation of updatePriceFeeds
function updatePriceFeeds(address _eurUsdFeed, address _usdcUsdFeed)
external
override
onlyRole(DEFAULT_ADMIN_ROLE);
recoverToken
Mock implementation of recoverToken
function recoverToken(address token, uint256 amount) external view override onlyRole(DEFAULT_ADMIN_ROLE);
setPrice
Set the EUR/USD price for testing purposes
Only available in mock oracle for testing
function setPrice(uint256 _price) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_price | uint256 | The new EUR/USD price in 18 decimals |
setUsdcUsdPrice
Set the USDC/USD price for testing purposes
Only available in mock oracle for testing
function setUsdcUsdPrice(uint256 _price) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_price | uint256 | The new USDC/USD price in 18 decimals |
setPrices
Set both EUR/USD and USDC/USD prices for testing purposes
Only available in mock oracle for testing
function setPrices(uint256 _eurUsdPrice, uint256 _usdcUsdPrice) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_eurUsdPrice | uint256 | The new EUR/USD price in 18 decimals |
_usdcUsdPrice | uint256 | The new USDC/USD price in 18 decimals |
setUpdatedAt
Set the updated timestamp for testing purposes
Only available in mock oracle for testing
function setUpdatedAt(uint256 _updatedAt) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_updatedAt | uint256 | The new timestamp |
Events
PriceDeviationDetected
event PriceDeviationDetected(uint256 newPrice, uint256 lastPrice, uint256 deviationBps, uint256 blockNumber);
CircuitBreakerTriggered
event CircuitBreakerTriggered(uint256 blockNumber, string reason);
CircuitBreakerReset
event CircuitBreakerReset(uint256 blockNumber);
ETHRecovered
event ETHRecovered(address indexed treasury, uint256 amount);
MockUSDC
Inherits: ERC20, Ownable
This is a simplified ERC20 token that mimics USDC behavior
Mock USDC token for testing and development
State Variables
_DECIMALS
uint8 private constant _DECIMALS = 6
Functions
constructor
constructor() ERC20("USD Coin", "USDC") Ownable(msg.sender);
decimals
Returns the number of decimals used to get its user representation.
function decimals() public pure override returns (uint8);
mint
Mint tokens to a specific address (for testing)
function mint(address to, uint256 amount) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | The address to mint tokens to |
amount | uint256 | The amount of tokens to mint |
faucet
Faucet function for easy testing - anyone can call this
function faucet(uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | The amount of tokens to mint to caller |
Contents
ChainlinkOracle
Inherits: IChainlinkOracle, Initializable, AccessControlUpgradeable, PausableUpgradeable, UUPSUpgradeable
Author: Quantillon Labs - Nicolas Bellengé - @chewbaccoin
EUR/USD and USDC/USD price manager for Quantillon Protocol
Key features:
- Fetch EUR/USD price from Chainlink
- Validate USDC/USD (should remain close to $1.00)
- Circuit breakers against outlier prices
- Fallbacks in case of oracle outage
- Data freshness checks
Note: security-contact: team@quantillon.money
State Variables
ORACLE_MANAGER_ROLE
Role to manage oracle configurations
bytes32 public constant ORACLE_MANAGER_ROLE = keccak256("ORACLE_MANAGER_ROLE")
EMERGENCY_ROLE
Role for emergency actions
bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE")
UPGRADER_ROLE
Role for contract upgrades
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE")
MAX_PRICE_STALENESS
Maximum duration before a price is considered stale (1 hour)
3600 seconds = reasonable limit for real-time DeFi
uint256 public constant MAX_PRICE_STALENESS = 3600
MAX_PRICE_DEVIATION
Maximum allowed deviation from previous price (5%)
500 basis points = 5% in basis points (500/10000)
uint256 public constant MAX_PRICE_DEVIATION = 500
BASIS_POINTS
Basis for basis points calculations
uint256 public constant BASIS_POINTS = 10000
MAX_TIMESTAMP_DRIFT
Maximum timestamp drift tolerance (15 minutes)
Prevents timestamp manipulation attacks by miners
uint256 public constant MAX_TIMESTAMP_DRIFT = 900
BLOCKS_PER_HOUR
Blocks per hour for block-based staleness checks
~12 second blocks on Ethereum, ~2 second blocks on L2s
uint256 public constant BLOCKS_PER_HOUR = 300
eurUsdPriceFeed
Interface to Chainlink EUR/USD price feed
AggregatorV3Interface public eurUsdPriceFeed
usdcUsdPriceFeed
Interface to Chainlink USDC/USD price feed
Used for USDC price validation and cross-checking
Should be the official USDC/USD Chainlink feed
AggregatorV3Interface public usdcUsdPriceFeed
treasury
Treasury address for ETH recovery
SECURITY: Only this address can receive ETH from recoverETH function
address public treasury
minEurUsdPrice
Minimum accepted EUR/USD price (lower circuit breaker)
Initialized to 0.80 USD per EUR (extreme crisis)
uint256 public minEurUsdPrice
maxEurUsdPrice
Maximum accepted EUR/USD price (upper circuit breaker)
Initialized to 1.40 USD per EUR (extreme scenario)
uint256 public maxEurUsdPrice
lastValidEurUsdPrice
Last valid EUR/USD price recorded (18 decimals)
Used as fallback if oracle is down
uint256 public lastValidEurUsdPrice
lastPriceUpdateTime
Timestamp of the last valid price update
uint256 public lastPriceUpdateTime
lastPriceUpdateBlock
Block number of the last valid price update
Used for block-based staleness checks to prevent timestamp manipulation
uint256 public lastPriceUpdateBlock
circuitBreakerTriggered
Circuit breaker status (true = triggered, fixed prices)
bool public circuitBreakerTriggered
usdcToleranceBps
USDC/USD tolerance (USDC should remain close to $1.00)
200 basis points = 2% (USDC can vary between 0.98 and 1.02)
uint256 public usdcToleranceBps
TIME_PROVIDER
TimeProvider contract for centralized time management
Used to replace direct block.timestamp usage for testability and consistency
TimeProvider public immutable TIME_PROVIDER
Functions
constructor
Constructor for ChainlinkOracle contract
Initializes the TimeProvider and disables initializers for proxy pattern
Notes:
-
security: Validates TimeProvider address is not zero
-
validation: Validates _TIME_PROVIDER is not address(0)
-
state-changes: Sets TIME_PROVIDER immutable variable and disables initializers
-
events: No events emitted
-
errors: Throws "Zero address" if _TIME_PROVIDER is address(0)
-
reentrancy: Not applicable - constructor
-
access: Public - anyone can deploy
-
oracle: No oracle dependencies
-
oz-upgrades-unsafe-allow: constructor
constructor(TimeProvider _TIME_PROVIDER) ;
Parameters
| Name | Type | Description |
|---|---|---|
_TIME_PROVIDER | TimeProvider | Address of the TimeProvider contract for centralized time management |
initialize
Initializes the oracle contract with Chainlink price feeds
Sets up all core dependencies, roles, and default configuration parameters
Notes:
-
security: Validates all addresses are not zero, grants admin roles
-
validation: Validates all input addresses are not address(0)
-
state-changes: Initializes all state variables, sets default price bounds
-
events: Emits PriceUpdated during initial price update
-
errors: Throws "Oracle: Admin cannot be zero" if admin is address(0)
-
reentrancy: Protected by initializer modifier
-
access: Public - only callable once during deployment
-
oracle: Initializes Chainlink price feed interfaces
function initialize(address admin, address _eurUsdPriceFeed, address _usdcUsdPriceFeed, address _treasury)
public
initializer;
Parameters
| Name | Type | Description |
|---|---|---|
admin | address | Address with administrator privileges |
_eurUsdPriceFeed | address | Chainlink EUR/USD price feed address on Base |
_usdcUsdPriceFeed | address | Chainlink USDC/USD price feed address on Base |
_treasury | address | Treasury address for ETH recovery |
updateTreasury
Update treasury address
SECURITY: Only admin can update treasury address
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function updateTreasury(address _treasury) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_treasury | address | New treasury address |
unpause
Removes pause and resumes oracle operations
Allows emergency role to unpause the oracle after resolving issues
Notes:
-
security: Validates emergency role authorization
-
validation: No input validation required
-
state-changes: Removes pause state, resumes oracle operations
-
events: Emits Unpaused event from OpenZeppelin
-
errors: No errors thrown - safe unpause operation
-
reentrancy: Not protected - no external calls
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies for unpause
function unpause() external onlyRole(EMERGENCY_ROLE);
_divRound
Performs division with proper rounding to nearest integer
Adds half the divisor before division to achieve proper rounding
Notes:
-
security: Validates denominator is not zero to prevent division by zero
-
validation: Validates b > 0
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: Throws "Oracle: Division by zero" if b is 0
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies
function _divRound(uint256 a, uint256 b) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
a | uint256 | Numerator |
b | uint256 | Denominator |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Result of division with rounding to nearest |
_validateTimestamp
Validates if a timestamp is recent enough to prevent manipulation attacks
Checks timestamp is not in future and not too old beyond staleness + drift limits
Notes:
-
security: Validates timestamp is not in future and within acceptable age
-
validation: Validates reportedTime <= currentTime and within MAX_PRICE_STALENESS + MAX_TIMESTAMP_DRIFT
-
state-changes: No state changes - view function
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies for timestamp validation
function _validateTimestamp(uint256 reportedTime) internal view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
reportedTime | uint256 | The timestamp to validate |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | true if the timestamp is valid, false otherwise |
_updatePrices
Updates and validates internal prices
Internal function called during initialization and resets, fetches fresh prices from Chainlink
Notes:
-
security: Validates price data integrity, circuit breaker bounds, and deviation limits
-
validation: Validates roundId == answeredInRound, startedAt <= updatedAt, price > 0
-
state-changes: Updates lastValidEurUsdPrice, lastPriceUpdateTime, lastPriceUpdateBlock
-
events: Emits PriceUpdated with current prices or CircuitBreakerTriggered if invalid
-
errors: Throws "EUR/USD price data is stale" if roundId != answeredInRound
-
reentrancy: Not protected - internal function only
-
access: Internal function - no access restrictions
-
oracle: Fetches fresh prices from Chainlink EUR/USD and USDC/USD feeds
function _updatePrices() internal;
_scalePrice
Scale price to 18 decimals for consistency
Converts Chainlink price from its native decimals to 18 decimals with proper rounding
Notes:
-
security: Validates rawPrice > 0 and handles decimal conversion safely
-
validation: Validates rawPrice > 0, returns 0 if invalid
-
state-changes: No state changes - pure function
-
events: No events emitted
-
errors: No errors thrown - safe arithmetic used
-
reentrancy: Not applicable - pure function
-
access: Internal function - no access restrictions
-
oracle: No oracle dependencies for price scaling
function _scalePrice(int256 rawPrice, uint8 decimals) internal pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
rawPrice | int256 | Raw price from Chainlink |
decimals | uint8 | Number of decimals in raw price |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint256 | Scaled price with 18 decimals |
getOracleHealth
Retrieves the oracle global health status
Checks freshness of both price feeds and overall system health
Notes:
-
security: Validates price feed connectivity and data integrity
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function with try/catch
-
reentrancy: Not applicable - view function
-
access: Public - anyone can check oracle health
-
oracle: Checks connectivity to Chainlink EUR/USD and USDC/USD feeds
function getOracleHealth() external view returns (bool isHealthy, bool eurUsdFresh, bool usdcUsdFresh);
Returns
| Name | Type | Description |
|---|---|---|
isHealthy | bool | true if everything operates normally |
eurUsdFresh | bool | true if EUR/USD price is fresh |
usdcUsdFresh | bool | true if USDC/USD price is fresh |
getEurUsdDetails
Retrieves detailed information about the EUR/USD price
Provides comprehensive EUR/USD price data including staleness and bounds checks
Notes:
-
security: Validates price feed data integrity and circuit breaker status
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function with try/catch
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query EUR/USD details
-
oracle: Fetches fresh data from Chainlink EUR/USD price feed
function getEurUsdDetails()
external
view
returns (uint256 currentPrice, uint256 lastValidPrice, uint256 lastUpdate, bool isStale, bool withinBounds);
Returns
| Name | Type | Description |
|---|---|---|
currentPrice | uint256 | Current price (may be fallback) |
lastValidPrice | uint256 | Last validated price |
lastUpdate | uint256 | Timestamp of last update |
isStale | bool | true if the price is stale |
withinBounds | bool | true if within acceptable bounds |
getOracleConfig
Retrieves current configuration parameters
Returns all key configuration values for oracle operations
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query configuration
-
oracle: No oracle dependencies for configuration query
function getOracleConfig()
external
view
returns (
uint256 minPrice,
uint256 maxPrice,
uint256 maxStaleness,
uint256 usdcTolerance,
bool circuitBreakerActive
);
Returns
| Name | Type | Description |
|---|---|---|
minPrice | uint256 | Minimum EUR/USD price |
maxPrice | uint256 | Maximum EUR/USD price |
maxStaleness | uint256 | Maximum duration before staleness |
usdcTolerance | uint256 | USDC tolerance in basis points |
circuitBreakerActive | bool | Circuit breaker status |
getPriceFeedAddresses
Retrieves addresses of the Chainlink price feeds used
Returns feed addresses and their decimal configurations
Notes:
-
security: No security validations required - view function
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function
-
reentrancy: Not applicable - view function
-
access: Public - anyone can query feed addresses
-
oracle: Queries decimal configuration from Chainlink feeds
function getPriceFeedAddresses()
external
view
returns (address eurUsdFeedAddress, address usdcUsdFeedAddress, uint8 eurUsdDecimals, uint8 usdcUsdDecimals);
Returns
| Name | Type | Description |
|---|---|---|
eurUsdFeedAddress | address | EUR/USD feed address |
usdcUsdFeedAddress | address | USDC/USD feed address |
eurUsdDecimals | uint8 | Number of decimals for the EUR/USD feed |
usdcUsdDecimals | uint8 | Number of decimals for the USDC/USD feed |
checkPriceFeedConnectivity
Tests connectivity to the Chainlink price feeds
Tests if both price feeds are responding and returns latest round information
Notes:
-
security: Validates price feed connectivity and data integrity
-
validation: No input validation required - view function
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - safe view function with try/catch
-
reentrancy: Not applicable - view function
-
access: Public - anyone can test feed connectivity
-
oracle: Tests connectivity to Chainlink EUR/USD and USDC/USD feeds
function checkPriceFeedConnectivity()
external
view
returns (bool eurUsdConnected, bool usdcUsdConnected, uint80 eurUsdLatestRound, uint80 usdcUsdLatestRound);
Returns
| Name | Type | Description |
|---|---|---|
eurUsdConnected | bool | true if the EUR/USD feed responds |
usdcUsdConnected | bool | true if the USDC/USD feed responds |
eurUsdLatestRound | uint80 | Latest round ID for EUR/USD |
usdcUsdLatestRound | uint80 | Latest round ID for USDC/USD |
_authorizeUpgrade
Authorizes oracle contract upgrades
function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | Address of the new implementation |
recoverToken
Recovers tokens accidentally sent to the contract to treasury only
Emergency function to recover ERC20 tokens that are not part of normal operations
Notes:
-
security: Validates admin role and uses secure recovery library
-
validation: No input validation required - library handles validation
-
state-changes: Transfers tokens from contract to treasury
-
events: No events emitted - library handles events
-
errors: No errors thrown - library handles error cases
-
reentrancy: Not protected - library handles reentrancy
-
access: Restricted to DEFAULT_ADMIN_ROLE
-
oracle: No oracle dependencies for token recovery
function recoverToken(address token, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
token | address | Address of the token to recover |
amount | uint256 | Amount to recover |
recoverETH
Recover ETH to treasury address only
SECURITY: Restricted to treasury to prevent arbitrary ETH transfers
Security considerations:
- Only DEFAULT_ADMIN_ROLE can recover
- Prevents sending to zero address
- Validates balance before attempting transfer
- Uses call() for reliable ETH transfers to any contract
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function recoverETH() external onlyRole(DEFAULT_ADMIN_ROLE);
resetCircuitBreaker
Resets the circuit breaker and resumes oracle usage
Emergency action after resolving an incident. Restarts price updates and disables fallback mode.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function resetCircuitBreaker() external onlyRole(EMERGENCY_ROLE);
triggerCircuitBreaker
Manually triggers the circuit breaker
Used when the team detects an issue with the oracles. Forces the use of the last known valid price.
Notes:
-
security: Validates input parameters and enforces security checks
-
validation: Validates input parameters and business logic constraints
-
state-changes: Updates contract state variables
-
events: Emits relevant events for state changes
-
errors: Throws custom errors for invalid conditions
-
reentrancy: Protected by reentrancy guard
-
access: Restricted to authorized roles
-
oracle: Requires fresh oracle price data
function triggerCircuitBreaker() external onlyRole(EMERGENCY_ROLE);
pause
Pauses all oracle operations
Emergency function to pause oracle in case of critical issues
Notes:
-
security: Validates emergency role authorization
-
validation: No input validation required
-
state-changes: Sets pause state, stops oracle operations
-
events: Emits Paused event from OpenZeppelin
-
errors: No errors thrown - safe pause operation
-
reentrancy: Not protected - no external calls
-
access: Restricted to EMERGENCY_ROLE
-
oracle: No oracle dependencies for pause
function pause() external onlyRole(EMERGENCY_ROLE);
getEurUsdPrice
Retrieves the current EUR/USD price with full validation
Validation process:
- Check circuit breaker status
- Fetch from Chainlink
- Freshness check (< 1 hour)
- Convert to 18 decimals
- Check min/max bounds
- Return valid price or fallback
Notes:
-
security: Validates timestamp freshness, circuit breaker status, price bounds
-
validation: Checks price > 0, timestamp < 1 hour old, within min/max bounds
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - returns fallback price if invalid
-
reentrancy: Not applicable - view function
-
access: Public - no access restrictions
-
oracle: Requires fresh Chainlink EUR/USD price feed data
function getEurUsdPrice() external view returns (uint256 price, bool isValid);
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | EUR/USD price in 18 decimals (e.g., 1.10e18 = 1.10 USD per EUR) |
isValid | bool | true if the price is fresh and within acceptable bounds |
getUsdcUsdPrice
Retrieves the USDC/USD price with validation
USDC is expected to maintain parity with USD. A large deviation indicates a systemic issue.
Notes:
-
security: Validates timestamp freshness, USDC tolerance bounds
-
validation: Checks price > 0, timestamp < 1 hour old, within USDC tolerance
-
state-changes: No state changes - view function only
-
events: No events emitted
-
errors: No errors thrown - returns $1.00 fallback if invalid
-
reentrancy: Not applicable - view function
-
access: Public - no access restrictions
-
oracle: Requires fresh Chainlink USDC/USD price feed data
function getUsdcUsdPrice() external view returns (uint256 price, bool isValid);
Returns
| Name | Type | Description |
|---|---|---|
price | uint256 | USDC/USD price in 18 decimals (should be close to 1.0e18) |
isValid | bool | true if USDC remains close to $1.00 |
updatePriceBounds
Updates price bounds for the circuit breaker
Allows oracle manager to adjust price thresholds based on market conditions
Notes:
-
security: Validates oracle manager role and price bounds constraints
-
validation: Validates _minPrice > 0, _maxPrice > _minPrice, _maxPrice < 10e18
-
state-changes: Updates minEurUsdPrice and maxEurUsdPrice
-
events: Emits PriceBoundsUpdated with new bounds
-
errors: Throws "Oracle: Min price must be positive" if _minPrice <= 0
-
reentrancy: Not protected - no external calls
-
access: Restricted to ORACLE_MANAGER_ROLE
-
oracle: No oracle dependencies for bounds update
function updatePriceBounds(uint256 _minPrice, uint256 _maxPrice) external onlyRole(ORACLE_MANAGER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_minPrice | uint256 | Minimum accepted EUR/USD price (18 decimals) |
_maxPrice | uint256 | Maximum accepted EUR/USD price (18 decimals) |
updateUsdcTolerance
Updates the tolerance for USDC/USD
Allows oracle manager to adjust USDC price tolerance around $1.00
Notes:
-
security: Validates oracle manager role and tolerance constraints
-
validation: Validates newToleranceBps <= 1000 (max 10%)
-
state-changes: Updates usdcToleranceBps
-
events: No events emitted for tolerance update
-
errors: Throws "Oracle: Tolerance too high" if newToleranceBps > 1000
-
reentrancy: Not protected - no external calls
-
access: Restricted to ORACLE_MANAGER_ROLE
-
oracle: No oracle dependencies for tolerance update
function updateUsdcTolerance(uint256 newToleranceBps) external onlyRole(ORACLE_MANAGER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newToleranceBps | uint256 | New tolerance in basis points (e.g., 200 = 2%) |
updatePriceFeeds
Updates the Chainlink price feed addresses
Allows oracle manager to update price feed addresses for maintenance or upgrades
Notes:
-
security: Validates oracle manager role and feed address constraints
-
validation: Validates both feed addresses are not address(0)
-
state-changes: Updates eurUsdPriceFeed and usdcUsdPriceFeed interfaces
-
events: Emits PriceFeedsUpdated with new feed addresses
-
errors: Throws "Oracle: EUR/USD feed cannot be zero" if _eurUsdFeed is address(0)
-
reentrancy: Not protected - no external calls
-
access: Restricted to ORACLE_MANAGER_ROLE
-
oracle: Updates Chainlink price feed interface addresses
function updatePriceFeeds(address _eurUsdFeed, address _usdcUsdFeed) external onlyRole(ORACLE_MANAGER_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
_eurUsdFeed | address | New EUR/USD feed address |
_usdcUsdFeed | address | New USDC/USD feed address |
Events
PriceUpdated
Emitted on each valid price update
OPTIMIZED: Indexed timestamp for efficient time-based filtering
event PriceUpdated(uint256 eurUsdPrice, uint256 usdcUsdPrice, uint256 indexed timestamp);
CircuitBreakerTriggered
Emitted when the circuit breaker is triggered
OPTIMIZED: Indexed reason for efficient filtering by trigger type
event CircuitBreakerTriggered(uint256 attemptedPrice, uint256 lastValidPrice, string indexed reason);
CircuitBreakerReset
Emitted when the circuit breaker is reset
event CircuitBreakerReset(address indexed admin);
PriceBoundsUpdated
Emitted when price bounds are modified
OPTIMIZED: Indexed bound type for efficient filtering
event PriceBoundsUpdated(string indexed boundType, uint256 newMinPrice, uint256 newMaxPrice);
PriceFeedsUpdated
Emitted when price feed addresses are updated
event PriceFeedsUpdated(address newEurUsdFeed, address newUsdcUsdFeed);
TreasuryUpdated
Emitted when treasury address is updated
event TreasuryUpdated(address indexed newTreasury);
Parameters
| Name | Type | Description |
|---|---|---|
newTreasury | address | New treasury address |
ETHRecovered
Emitted when ETH is recovered from the contract
event ETHRecovered(address indexed to, uint256 amount);