Quantillon Protocol

Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quantillon Protocol Smart Contracts

License: MIT Solidity Foundry Tests Security Security

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

🎯 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

ContractPurposeKey Features
QEUROTokenEuro-pegged stablecoinMint/burn controls, rate limiting, compliance features, 18 decimals
QTITokenGovernance tokenVote-escrow mechanics, fixed supply, lock periods, voting power multipliers
QuantillonVaultMain vaultOvercollateralized minting, liquidation system, fee management
UserPoolUser depositsStaking rewards, yield distribution, deposit/withdrawal management
HedgerPoolHedging operationsEUR/USD positions, margin management, liquidation system
stQEUROTokenYield-bearing wrapperAutomatic yield accrual, exchange rate mechanism
AaveVaultAave integrationAutomated yield farming, risk management, emergency controls
YieldShiftYield managementDynamic yield distribution, pool rebalancing, performance metrics
ChainlinkOraclePrice feedsEUR/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:

PhaseGasContractsPurpose
A~17MTimeProvider, Oracle, QEURO, FeeCollector, VaultCore infrastructure
B~16MQTI, AaveVault, stQEUROToken layer
C~11MUserPool, HedgerPoolPool layer
D~7MYieldShift + wiringYield 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

EnvironmentCommandDescription
localhost./scripts/deployment/deploy.sh localhost --with-mocksDevelopment with Anvil and mock contracts
base-sepolia./scripts/deployment/deploy.sh base-sepolia --verifyTestnet deployment with contract verification
base./scripts/deployment/deploy.sh base --production --verifyProduction deployment with multisig governance

🔧 Deployment Features

  • 🔐 Secure Environment Variables: Manage secrets with standard .env files (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 .env files (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 .env during 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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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.

🙏 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

Contents

IPool

Git Source

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

NameTypeDescription
assetaddressAddress of the asset to supply
amountuint256Amount of assets to supply
onBehalfOfaddressAddress to supply on behalf of
referralCodeuint16Referral 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

NameTypeDescription
assetaddressAddress of the asset to withdraw
amountuint256Amount of assets to withdraw
toaddressAddress to withdraw to

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
assetaddressAddress of the asset

Returns

NameTypeDescription
<none>ReserveDataReserveData Reserve data structure

IPoolAddressesProvider

Git Source

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

NameTypeDescription
<none>addressaddress Address of the Aave pool

IRewardsController

Git Source

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

NameTypeDescription
assetsaddress[]Array of asset addresses
amountuint256Amount of rewards to claim
toaddressAddress to send rewards to

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
assetsaddress[]Array of asset addresses
useraddressAddress of the user

Returns

NameTypeDescription
<none>uint256[]uint256[] Array of reward amounts for each asset

ReserveData

Git Source

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

Git Source

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

NameTypeDescription
adminaddressAddress of the admin role
_usdcaddressAddress of the USDC token contract
_aaveProvideraddressAddress of the Aave pool addresses provider
_rewardsControlleraddressAddress of the Aave rewards controller
_yieldShiftaddressAddress of the yield shift contract
_timelockaddressAddress of the timelock contract
_treasuryaddressAddress 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

NameTypeDescription
amountuint256USDC amount to supply (6 decimals)

Returns

NameTypeDescription
aTokensReceiveduint256Amount 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

NameTypeDescription
amountuint256Amount of aUSDC to withdraw (6 decimals, use type(uint256).max for all)

Returns

NameTypeDescription
usdcWithdrawnuint256Amount 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

NameTypeDescription
amountuint256Requested withdrawal amount (6 decimals)
aaveBalanceuint256Current aUSDC balance (6 decimals)

Returns

NameTypeDescription
withdrawAmountuint256Actual 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

NameTypeDescription
withdrawAmountuint256Amount to withdraw (6 decimals)
aaveBalanceuint256Current 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

NameTypeDescription
withdrawAmountuint256Amount 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

NameTypeDescription
originalAmountuint256Original amount requested
withdrawAmountuint256Amount to withdraw from Aave
usdcBeforeuint256USDC balance before withdrawal

Returns

NameTypeDescription
usdcWithdrawnuint256Actual 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

NameTypeDescription
originalAmountuint256Original amount requested
withdrawAmountuint256Amount to withdraw from Aave
usdcBeforeuint256USDC balance before withdrawal
usdcWithdrawnuint256Actual 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

NameTypeDescription
rewardsClaimeduint256Claimed 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

NameTypeDescription
yieldHarvesteduint256Amount 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
protocolYielduint256Amount of yield allocated to protocol fees
userYielduint256Amount of yield allocated to users
hedgerYielduint256Amount 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
principalDeposited_uint256Total amount originally deposited
currentBalanceuint256Current aToken balance including interest
aTokenBalanceuint256Current aToken balance
lastUpdateTimeuint256Timestamp 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

NameTypeDescription
supplyRateuint256Current supply rate for the asset
utilizationRateuint256Current utilization rate of the reserve
totalSupplyuint256Total supply of the underlying asset
availableLiquidityuint256Available 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

NameTypeDescription
isHealthyboolTrue if position is healthy, false if issues detected
pauseStatusboolCurrent pause status of the contract
lastUpdateuint256Timestamp 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

NameTypeDescription
<none>boolbool 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

NameTypeDescription
rebalancedboolTrue if rebalancing occurred, false otherwise
newAllocationuint256New allocation percentage after rebalancing
expectedYielduint256Expected 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

NameTypeDescription
optimalAllocationuint256Recommended amount to allocate to Aave
expectedYielduint256Expected 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

NameTypeDescription
_maxExposureuint256Maximum 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

NameTypeDescription
amountWithdrawnuint256Amount 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

NameTypeDescription
exposureRatiouint256Percentage of total assets exposed to Aave
concentrationRiskuint256Risk level due to concentration in Aave (1-3 scale)
liquidityRiskuint256Risk 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

NameTypeDescription
newHarvestThresholduint256New harvest threshold in USDC
newYieldFeeuint256New yield fee in basis points
newRebalanceThresholduint256New 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

NameTypeDescription
aavePool_addressAddress of the Aave pool contract
aUSDC_addressAddress of the aUSDC token contract
harvestThreshold_uint256Minimum yield threshold for harvesting
yieldFee_uint256Fee percentage charged on yield
maxExposure_uint256Maximum 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

NameTypeDescription
enabledboolWhether to enable or disable emergency mode
reasonstringHuman-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

NameTypeDescription
tokenaddressThe token address to recover
amountuint256The 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

Git Source

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

NameTypeDescription
_TIME_PROVIDERTimeProviderAddress 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

NameTypeDescription
adminaddressAddress of the admin role
_usdcaddressAddress of the USDC token contract
_userPooladdressAddress of the user pool contract
_hedgerPooladdressAddress of the hedger pool contract
_aaveVaultaddressAddress of the Aave vault contract
_stQEUROaddressAddress of the stQEURO token contract
_timelockaddressAddress of the timelock contract
_treasuryaddressAddress 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

NameTypeDescription
yieldAmountuint256Amount of yield to add (6 decimals)
sourcebytes32Source 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

NameTypeDescription
useraddressAddress of the user to claim yield for

Returns

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
hedgeraddressAddress of the hedger to claim yield for

Returns

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
poolRatiouint256Current ratio between user and hedger pools (basis points)

Returns

NameTypeDescription
<none>uint256Optimal 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

NameTypeDescription
targetShiftuint256Target yield shift percentage (basis points)

Returns

NameTypeDescription
<none>uint256Adjusted 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

NameTypeDescription
userPoolSizeuint256Current user pool size
hedgerPoolSizeuint256Current hedger pool size
poolRatiouint256Ratio 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

NameTypeDescription
userPoolSizeuint256Eligible user pool size (deposits older than MIN_HOLDING_PERIOD)
hedgerPoolSizeuint256Eligible hedger pool size (deposits older than MIN_HOLDING_PERIOD)
poolRatiouint256Ratio 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

NameTypeDescription
discountBpsuint256Discount 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

NameTypeDescription
valueuint256The value to check
targetuint256The target value
toleranceBpsuint256Tolerance in basis points (e.g., 1000 = 10%)

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
useraddressThe 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
useraddressThe user address to check

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
hedgeraddressThe hedger address to check

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
userYieldPool_uint256Yield allocated to user pool
hedgerYieldPool_uint256Yield allocated to hedger pool
distributionRatiouint256Current 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

NameTypeDescription
userPoolSizeuint256Total size of user pool
hedgerPoolSizeuint256Total size of hedger pool
poolRatiouint256Current ratio between pools
targetRatiouint256Target 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

NameTypeDescription
optimalShiftuint256Recommended yield shift percentage
currentDeviationuint256Current 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

NameTypeDescription
aaveYielduint256Yield from Aave protocol
protocolFeesuint256Protocol fees collected
interestDifferentialuint256Interest rate differential yield
otherSourcesuint256Other 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

NameTypeDescription
minHoldingPerioduint256Current minimum holding period
baseDiscountuint256Current base discount percentage
currentDiscountuint256Current calculated discount percentage
timeSinceLastUpdateuint256Time 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

NameTypeDescription
perioduint256The time period to analyze (in seconds)

Returns

NameTypeDescription
averageShiftuint256Average yield shift during the period
maxShiftuint256Maximum yield shift during the period
minShiftuint256Minimum yield shift during the period
volatilityuint256Volatility 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

NameTypeDescription
totalYieldDistributed_uint256Total yield distributed to date
averageUserYielduint256Average yield for users
averageHedgerYielduint256Average yield for hedgers
yieldEfficiencyuint256Yield 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

NameTypeDescription
<none>uint256User 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

NameTypeDescription
<none>uint256Hedger 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

NameTypeDescription
_baseYieldShiftuint256Base yield shift percentage in basis points
_maxYieldShiftuint256Maximum yield shift percentage in basis points
_adjustmentSpeeduint256Adjustment 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

NameTypeDescription
_targetPoolRatiouint256The 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

NameTypeDescription
sourceaddressAddress of the yield source
yieldTypebytes32Type 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

NameTypeDescription
sourceaddressAddress 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

NameTypeDescription
useraddressThe user or hedger address
amountuint256The allocation amount
isUserboolTrue 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

NameTypeDescription
userAmountuint256Amount to distribute to user pool
hedgerAmountuint256Amount 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

NameTypeDescription
baseShiftuint256Base yield shift percentage
maxShiftuint256Maximum allowed yield shift
adjustmentSpeed_uint256Speed of yield adjustments
lastUpdateuint256Timestamp 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
sourceaddressSource address
yieldTypebytes32Yield type identifier

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
poolHistoryPoolSnapshot[]Array of pool snapshots
perioduint256Time period for calculation
isUserPoolboolWhether this is for user pool or hedger pool

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
eligibleUserPoolSizeuint256Eligible user pool size for yield calculations
eligibleHedgerPoolSizeuint256Eligible 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

NameTypeDescription
poolHistoryPoolSnapshot[]Array of pool snapshots to add to
poolSizeuint256Size of the pool to record
isUserPoolboolWhether 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

NameTypeDescription
tokenaddressThe token address to recover
amountuint256The 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

NameTypeDescription
_minHoldingPerioduint256New minimum holding period in seconds
_baseDiscountuint256New base discount percentage in basis points
_maxTimeFactoruint256New 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

Git Source

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

NameTypeDescription
_adminaddressAdmin address (will receive DEFAULT_ADMIN_ROLE, GOVERNANCE_ROLE, and EMERGENCY_ROLE)
_treasuryaddressTreasury address (will receive TREASURY_ROLE)
_devFundaddressDev fund address (cannot be zero)
_communityFundaddressCommunity 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

NameTypeDescription
tokenaddressToken address to collect fees for (cannot be zero address)
amountuint256Amount of fees to collect (must be greater than zero)
sourceTypestringType 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

NameTypeDescription
sourceTypestringType 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

NameTypeDescription
tokenaddressToken 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

NameTypeDescription
balanceuint256Total balance to distribute

Returns

NameTypeDescription
treasuryAmountuint256Amount for treasury
devFundAmountuint256Amount for dev fund
communityAmountuint256Amount 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

NameTypeDescription
tokenaddressToken address (address(0) for ETH)
treasuryAmountuint256Amount for treasury
devFundAmountuint256Amount for dev fund
communityAmountuint256Amount 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

NameTypeDescription
treasuryAmountuint256Amount for treasury
devFundAmountuint256Amount for dev fund
communityAmountuint256Amount 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

NameTypeDescription
recipientaddressAddress to receive ETH (must be treasury, devFund, or communityFund)
amountuint256Amount 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

NameTypeDescription
tokenaddressToken address
treasuryAmountuint256Amount for treasury
devFundAmountuint256Amount for dev fund
communityAmountuint256Amount 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

NameTypeDescription
_treasuryRatiouint256New treasury ratio (in basis points, 10000 = 100%)
_devFundRatiouint256New dev fund ratio (in basis points, 10000 = 100%)
_communityRatiouint256New 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

NameTypeDescription
_treasuryaddressNew treasury address (cannot be zero)
_devFundaddressNew dev fund address (cannot be zero)
_communityFundaddressNew 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

NameTypeDescription
feeSourceaddressContract 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

NameTypeDescription
feeSourceaddressContract 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

NameTypeDescription
tokenaddressToken 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

NameTypeDescription
tokenaddressToken address (address(0) for ETH)

Returns

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
tokenaddressToken address (address(0) for ETH)

Returns

NameTypeDescription
totalCollecteduint256Total amount of fees collected for this token
totalDistributeduint256Total amount of fees distributed for this token
collectionCountuint256Number of fee collection transactions for this token
currentBalanceuint256Current 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

NameTypeDescription
feeSourceaddressAddress to check for authorization

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
feeSourceaddressAddress to check for authorization

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newImplementationaddressAddress 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

Git Source

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

NameTypeDescription
_TIME_PROVIDERTimeProviderThe time provider contract for timestamp management

initialize

Initializes the HedgerPool with contracts and parameters

This function configures:

  1. Access roles and permissions
  2. References to external contracts
  3. Default protocol parameters
  4. 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

NameTypeDescription
adminaddressAddress with administrator privileges
_usdcaddressAddress of the USDC token contract
_oracleaddressAddress of the Oracle contract
_yieldShiftaddressAddress of the YieldShift contract
_timelockaddressAddress of the timelock contract
_treasuryaddressAddress of the treasury contract
_vaultaddressAddress of the QuantillonVault contract

enterHedgePosition

Opens a new hedge position for a hedger

Position opening process:

  1. Validates hedger whitelist status
  2. Fetches current EUR/USD price from oracle
  3. Calculates position size and validates parameters
  4. Transfers USDC to vault for unified liquidity
  5. Creates position record and updates hedger stats

Security features:

  1. Flash loan protection via secureNonReentrant
  2. Whitelist validation if enabled
  3. Parameter validation (leverage, amounts)
  4. 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

NameTypeDescription
usdcAmountuint256Amount of USDC to deposit as margin (6 decimals)
leverageuint256Leverage multiplier for the position (1-20x)

Returns

NameTypeDescription
positionIduint256Unique identifier for the new position

exitHedgePosition

Closes an existing hedge position

Position closing process:

  1. Validates position ownership and active status
  2. Checks protocol collateralization safety
  3. Calculates current PnL based on price change
  4. Determines net payout to hedger
  5. Updates hedger stats and removes position
  6. Withdraws USDC from vault for hedger payout

Security features:

  1. Position ownership validation
  2. Protocol collateralization safety check
  3. 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

NameTypeDescription
positionIduint256Unique identifier of the position to close

Returns

NameTypeDescription
pnlint256Profit or loss from the position (positive = profit, negative = loss)

addMargin

Adds additional margin to an existing hedge position

Margin addition process:

  1. Validates position ownership and active status
  2. Validates amount is positive
  3. Checks liquidation cooldown and pending liquidation status
  4. Transfers USDC from hedger to vault
  5. Updates position margin and hedger stats

Security features:

  1. Flash loan protection
  2. Position ownership validation
  3. 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

NameTypeDescription
positionIduint256Unique identifier of the position
amountuint256Amount of USDC to add as margin (6 decimals)

removeMargin

Removes margin from an existing hedge position

Margin removal process:

  1. Validates position ownership and active status
  2. Validates amount is positive
  3. Validates margin operation maintains minimum margin ratio
  4. Updates position margin and hedger stats
  5. Withdraws USDC from vault to hedger

Security features:

  1. Flash loan protection
  2. Position ownership validation
  3. 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

NameTypeDescription
positionIduint256Unique identifier of the position
amountuint256Amount 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position will be liquidated
positionIduint256ID of the position to liquidate
saltbytes32Random salt for commitment uniqueness and MEV protection

liquidateHedger

Liquidates an undercollateralized hedge position

Liquidation process:

  1. Validates liquidator role and commitment
  2. Validates position ownership and active status
  3. Calculates liquidation reward and remaining margin
  4. Updates hedger stats and removes position
  5. Withdraws USDC from vault for liquidator reward and remaining margin

Security features:

  1. Role-based access control (LIQUIDATOR_ROLE)
  2. Commitment validation to prevent front-running
  3. 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

NameTypeDescription
hedgeraddressAddress of the hedger to liquidate
positionIduint256Unique identifier of the position to liquidate
saltbytes32Random salt for commitment validation

Returns

NameTypeDescription
liquidationRewarduint256Amount of USDC reward for the liquidator

claimHedgingRewards

Claims hedging rewards for a hedger

Reward claiming process:

  1. Calculates interest differential based on exposure and rates
  2. Calculates yield shift rewards from YieldShift contract
  3. Updates hedger's last reward block
  4. Transfers total rewards to hedger

Security features:

  1. Reentrancy protection
  2. 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

NameTypeDescription
interestDifferentialuint256Interest differential rewards earned
yieldShiftRewardsuint256Yield shift rewards earned
totalRewardsuint256Total 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256ID of the position to retrieve

Returns

NameTypeDescription
positionSizeuint256Current size of the position in USDC
marginuint256Current margin amount for the position
entryPriceuint256Price at which the position was opened
currentPriceuint256Current EUR/USD price from oracle
leverageuint256Leverage multiplier for the position
lastUpdateTimeuint256Timestamp 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256ID of the position to check

Returns

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256ID of the position to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
newMinMarginRatiouint256New minimum margin ratio in basis points (minimum 500 = 5%)
newLiquidationThresholduint256New liquidation threshold in basis points (must be < minMarginRatio)
newMaxLeverageuint256New maximum leverage multiplier (maximum 20x)
newLiquidationPenaltyuint256New 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

NameTypeDescription
newEurRateuint256New EUR interest rate in basis points (maximum 2000 = 20%)
newUsdRateuint256New 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

NameTypeDescription
_entryFeeuint256New entry fee in basis points (maximum 100 = 1%)
_exitFeeuint256New exit fee in basis points (maximum 100 = 1%)
_marginFeeuint256New margin fee in basis points (maximum 50 = 0.5%)

emergencyClosePosition

Emergency closure of a hedge position by governance

Emergency closure process:

  1. Validates emergency role and position ownership
  2. Validates position is active
  3. Updates hedger stats and removes position
  4. Withdraws USDC from vault for hedger's margin

Security features:

  1. Role-based access control (EMERGENCY_ROLE)
  2. 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position to close
positionIduint256Unique 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256ID of the position to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
minMarginRatio_uint256Current minimum margin ratio in basis points
liquidationThreshold_uint256Current liquidation threshold in basis points
maxLeverage_uint256Current maximum leverage multiplier
liquidationPenalty_uint256Current liquidation penalty in basis points
entryFee_uint256Current entry fee in basis points
exitFee_uint256Current 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
maxPositionSizeuint256Maximum position size in USDC
maxMarginuint256Maximum margin per position in USDC
maxEntryPriceuint256Maximum entry price for positions
maxLeverageValueuint256Maximum leverage multiplier
maxTotalMarginuint256Maximum total margin across all positions
maxTotalExposureuint256Maximum total exposure across all positions
maxPendingRewardsuint256Maximum 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
hedgeraddressAddress of the hedger whose commitment to clear
positionIduint256ID 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position was committed for liquidation
positionIduint256ID of the position whose commitment to cancel
saltbytes32Salt 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

NameTypeDescription
tokenaddressAddress of the token to recover
amountuint256Amount 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
_vaultaddressNew 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

NameTypeDescription
_oracleaddressNew oracle address

updateYieldShift

Updates the YieldShift address

Governance-only setter to allow phased wiring after minimal initialization

function updateYieldShift(address _yieldShift) external;

Parameters

NameTypeDescription
_yieldShiftaddressNew YieldShift address

whitelistHedger

Whitelists a hedger address for position opening

Whitelisting process:

  1. Validates governance role and hedger address
  2. Checks hedger is not already whitelisted
  3. Adds hedger to whitelist and grants HEDGER_ROLE

Security features:

  1. Role-based access control (GOVERNANCE_ROLE)
  2. 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

NameTypeDescription
hedgeraddressAddress of the hedger to whitelist

removeHedger

Removes a hedger from the whitelist

Removal process:

  1. Validates governance role and hedger address
  2. Checks hedger is currently whitelisted
  3. Removes hedger from whitelist and revokes HEDGER_ROLE

Security features:

  1. Role-based access control (GOVERNANCE_ROLE)
  2. 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

NameTypeDescription
hedgeraddressAddress of the hedger to remove from whitelist

toggleHedgerWhitelistMode

Toggles the hedger whitelist mode on/off

Whitelist mode toggle:

  1. Validates governance role
  2. Updates hedgerWhitelistEnabled state
  3. 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

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
<none>uint256price 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

NameTypeDescription
rolebytes32The 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position to remove
positionIduint256ID 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

NameTypeDescription
positionSizeuint256Size of the position in USDC
marginuint256Margin amount for the position
leverageuint256Leverage multiplier for the position
entryPriceuint256Price at which the position was opened

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
exitPriceuint256Price at which the position was closed
pnlint256Profit or loss from the position (can be negative)
timestampuint256Timestamp when the position was closed

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
marginAmountuint256Amount of margin added or removed
newMarginRatiouint256New margin ratio after the operation
isAddedboolTrue if margin was added, false if removed

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
liquidationRewarduint256Reward paid to the liquidator
remainingMarginuint256Margin remaining after liquidation

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
interestDifferentialuint256Interest rate differential between EUR and USD
yieldShiftRewardsuint256Rewards from yield shifting operations
totalRewardsuint256Total rewards accumulated

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
<none>uint256
positionMarginuint256The 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

Git Source

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:

  1. Initializes the ERC20 token with name and symbol
  2. Configures the role system
  3. Assigns appropriate roles
  4. Configures pause and upgrade system
  5. 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

NameTypeDescription
adminaddressAddress that will have the DEFAULT_ADMIN_ROLE
vaultaddressAddress of the QuantillonVault (will get MINTER_ROLE and BURNER_ROLE)
_timelockaddressAddress of the timelock contract
_treasuryaddressTreasury 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

NameTypeDescription
toaddressAddress that will receive the tokens
amountuint256Amount 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

NameTypeDescription
recipientsaddress[]Array of recipient addresses
amountsuint256[]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

NameTypeDescription
fromaddressAddress from which to burn tokens
amountuint256Amount 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

NameTypeDescription
fromsaddress[]Array of addresses to burn from
amountsuint256[]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

NameTypeDescription
amountuint256The 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
newMintLimituint256New mint rate limit per reset period (~300 blocks)
newBurnLimituint256New 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

NameTypeDescription
accountaddressAddress to blacklist
reasonstringReason 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
accountsaddress[]Array of addresses to blacklist
reasonsstring[]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

NameTypeDescription
accountsaddress[]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

NameTypeDescription
accountsaddress[]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

NameTypeDescription
accountsaddress[]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

NameTypeDescription
newPrecisionuint256New 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

NameTypeDescription
priceuint256Price value from external feed
feedDecimalsuint8Number of decimals in the price feed

Returns

NameTypeDescription
<none>uint256Normalized 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

NameTypeDescription
priceuint256Price value from external feed
feedDecimalsuint8Number of decimals in the price feed

Returns

NameTypeDescription
<none>boolWhether 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

NameTypeDescription
<none>uint8Number 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

NameTypeDescription
accountaddressAddress to check

Returns

NameTypeDescription
<none>booltrue 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

NameTypeDescription
accountaddressAddress to check

Returns

NameTypeDescription
<none>booltrue 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

NameTypeDescription
<none>uint256Percentage 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

NameTypeDescription
<none>uint256Number 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

NameTypeDescription
mintedThisHouruint256Amount minted in current hour (18 decimals)
burnedThisHouruint256Amount burned in current hour (18 decimals)
mintLimituint256Current mint rate limit (18 decimals)
burnLimituint256Current burn rate limit (18 decimals)
nextResetTimeuint256Block 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

NameTypeDescription
recipientsaddress[]Array of recipient addresses
amountsuint256[]Array of amounts to transfer (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
fromaddressSource address (address(0) for mint)
toaddressDestination address (address(0) for burn)
amountuint256Amount 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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount 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

NameTypeDescription
newMaxSupplyuint256New 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
name_stringToken name
symbol_stringToken symbol
decimals_uint8Number of decimals
totalSupply_uint256Current total supply
maxSupply_uint256Maximum authorized supply
isPaused_boolPause state
whitelistEnabled_boolWhether whitelist mode is enabled
mintRateLimit_uint256Current mint rate limit
burnRateLimit_uint256Current 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

NameTypeDescription
limituint256Mint 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

NameTypeDescription
enabledboolTrue 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

NameTypeDescription
limituint256Burn 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

NameTypeDescription
toaddressRecipient of the tokens
amountuint256Amount minted in wei (18 decimals)
minteraddressAddress 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

NameTypeDescription
enabledboolTrue if killswitch is being enabled (minting blocked), false if disabled (minting allowed)
calleraddressAddress 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

NameTypeDescription
fromaddressAddress from which tokens are burned
amountuint256Amount burned in wei (18 decimals)
burneraddressAddress 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

NameTypeDescription
oldCapuint256Old supply limit in wei (18 decimals)
newCapuint256New 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

NameTypeDescription
limitTypestring
mintLimituint256New mint rate limit in wei per hour (18 decimals)
burnLimituint256New burn rate limit in wei per hour (18 decimals)

TreasuryUpdated

Emitted when treasury address is updated

event TreasuryUpdated(address indexed treasury);

Parameters

NameTypeDescription
treasuryaddressNew 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

NameTypeDescription
accountaddressAddress that was blacklisted
reasonstringReason 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
accountaddressAddress that was removed from whitelist

WhitelistModeToggled

Emitted when whitelist mode is toggled

Emitted when COMPLIANCE_ROLE toggles whitelist mode

event WhitelistModeToggled(bool enabled);

Parameters

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
oldPrecisionuint256Old minimum precision value
newPrecisionuint256New 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

NameTypeDescription
blockNumberuint256Block number when reset occurred

ETHRecovered

Emitted when ETH is recovered to treasury

event ETHRecovered(address indexed to, uint256 indexed amount);

Parameters

NameTypeDescription
toaddressAddress to which ETH was recovered
amountuint256Amount 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

Git Source

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

NameTypeDescription
_TIME_PROVIDERTimeProviderTimeProvider 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

NameTypeDescription
adminaddressAddress that receives admin and governance roles
_treasuryaddressTreasury address for protocol fees
_timelockaddressTimelock 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

NameTypeDescription
amountuint256The amount of QTI tokens to lock
lockTimeuint256The duration to lock tokens (in seconds)

Returns

NameTypeDescription
veQTIuint256The 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

NameTypeDescription
amountuint256Amount 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

NameTypeDescription
amountsuint256[]Array of QTI amounts to lock
lockTimesuint256[]Array of lock durations (must be >= MIN_LOCK_TIME)

Returns

NameTypeDescription
veQTIAmountsuint256[]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

NameTypeDescription
amountsuint256[]Array of QTI amounts to lock
lockTimesuint256[]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

NameTypeDescription
amountsuint256[]Array of QTI amounts to lock
lockTimesuint256[]Array of lock durations

Returns

NameTypeDescription
totalAmountuint256Total 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

NameTypeDescription
amountsuint256[]Array of QTI amounts to lock
lockTimesuint256[]Array of lock durations
veQTIAmountsuint256[]Array to store calculated voting power amounts
lockInfoLockInfoStorage reference to user's lock information

Returns

NameTypeDescription
totalNewVotingPoweruint256Total new voting power from all locks
totalNewAmountuint256Total 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

NameTypeDescription
currentTimestampuint256Current timestamp for calculation
lockTimeuint256Duration to lock tokens
existingUnlockTimeuint256Existing unlock time if already locked

Returns

NameTypeDescription
newUnlockTimeuint256Calculated 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

NameTypeDescription
amountuint256Amount of QTI tokens to lock
lockTimeuint256Duration to lock tokens

Returns

NameTypeDescription
<none>uint256votingPower 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

NameTypeDescription
lockInfoLockInfoStorage reference to user's lock information
totalNewAmountuint256Total new amount to lock
newUnlockTimeuint256New unlock time
totalNewVotingPoweruint256Total new voting power
lockTimeuint256Lock 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

NameTypeDescription
totalAmountuint256Total amount of tokens to lock
oldVotingPoweruint256Previous voting power
totalNewVotingPoweruint256New 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

NameTypeDescription
usersaddress[]Array of user addresses to unlock for

Returns

NameTypeDescription
amountsuint256[]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

NameTypeDescription
recipientsaddress[]Array of recipient addresses
amountsuint256[]Array of amounts to transfer

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
useraddressAddress to get voting power for

Returns

NameTypeDescription
votingPoweruint256Current 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

NameTypeDescription
newVotingPoweruint256Updated 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

NameTypeDescription
useraddressAddress to get lock info for

Returns

NameTypeDescription
amountuint256Locked QTI amount
unlockTimeuint256Timestamp when lock expires
votingPoweruint256Current voting power
lastClaimTimeuint256Last claim time (for future use)
initialVotingPoweruint256Initial voting power when locked
lockTimeuint256Original 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

NameTypeDescription
descriptionstringProposal description
votingPerioduint256Voting period in seconds
databytesExecution data (function calls)

Returns

NameTypeDescription
proposalIduint256Unique 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

NameTypeDescription
proposalIduint256Proposal ID
supportboolTrue 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

NameTypeDescription
proposalIdsuint256[]Array of proposal IDs to vote on
supportVotesbool[]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

NameTypeDescription
proposalIduint256Proposal ID

_verifyCallResult

Verifies call result and reverts with appropriate error

function _verifyCallResult(bool success) private pure;

Parameters

NameTypeDescription
successboolWhether 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

NameTypeDescription
proposalIduint256Proposal ID

Returns

NameTypeDescription
scheduledboolWhether the proposal is scheduled
executionTimeuint256When the proposal can be executed
canExecuteboolWhether 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

NameTypeDescription
proposalIduint256Proposal ID

Returns

NameTypeDescription
executionHashbytes32Hash 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

NameTypeDescription
proposalIduint256Proposal 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

NameTypeDescription
proposalIduint256Proposal ID

Returns

NameTypeDescription
proposeraddressAddress of the proposer
startTimeuint256Timestamp when voting starts
endTimeuint256Timestamp when voting ends
forVotesuint256Total votes in favor
againstVotesuint256Total votes against
executedboolWhether the proposal was executed
canceledboolWhether the proposal was canceled
descriptionstringProposal 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

NameTypeDescription
proposalIduint256Proposal ID
voteraddressAddress of the voter

Returns

NameTypeDescription
hasVotedboolWhether the user has voted
supportboolTrue for yes vote, false for no vote
votesuint256Number 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

NameTypeDescription
_proposalThresholduint256New minimum QTI required to propose
_minVotingPerioduint256New minimum voting period
_quorumVotesuint256New 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
lockTimeuint256Duration of the lock

Returns

NameTypeDescription
<none>uint256multiplier 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

NameTypeDescription
useraddressAddress of the user to update

Returns

NameTypeDescription
newVotingPoweruint256Updated 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

NameTypeDescription
<none>uint8The 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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount 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

NameTypeDescription
totalLocked_uint256Total QTI tokens locked in vote-escrow
totalVotingPower_uint256Total voting power across all locked tokens
proposalThreshold_uint256Minimum QTI required to propose
quorumVotes_uint256Quorum required for proposals to pass
currentDecentralizationLevel_uint256Current 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

NameTypeDescription
useraddressAddress of the user who locked tokens
amountuint256Amount of QTI locked
unlockTimeuint256Timestamp when the lock expires
votingPoweruint256Voting 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

NameTypeDescription
useraddressAddress of the user who unlocked tokens
amountuint256Amount of QTI unlocked
votingPoweruint256Voting power before unlocking

VotingPowerUpdated

Emitted when voting power for an address is updated

event VotingPowerUpdated(address indexed user, uint256 oldPower, uint256 newPower);

Parameters

NameTypeDescription
useraddressAddress of the user whose voting power changed
oldPoweruint256Previous voting power
newPoweruint256New voting power

ProposalCreated

Emitted when a new governance proposal is created

event ProposalCreated(uint256 indexed proposalId, address indexed proposer, string description);

Parameters

NameTypeDescription
proposalIduint256Unique identifier for the proposal
proposeraddressAddress of the proposer
descriptionstringDescription 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

NameTypeDescription
proposalIduint256Unique identifier for the proposal
voteraddressAddress of the voter
supportboolTrue for yes vote, false for no vote
votesuint256Number of votes cast

ProposalExecuted

Emitted when a proposal is successfully executed

event ProposalExecuted(uint256 indexed proposalId);

Parameters

NameTypeDescription
proposalIduint256Unique identifier for the executed proposal

ProposalCanceled

Emitted when a proposal is canceled

event ProposalCanceled(uint256 indexed proposalId);

Parameters

NameTypeDescription
proposalIduint256Unique 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

NameTypeDescription
parameterTypestring
proposalThresholduint256New minimum QTI required to propose
minVotingPerioduint256New minimum voting period
quorumVotesuint256New 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

NameTypeDescription
newLeveluint256New decentralization level (0-10000)

ETHRecovered

Emitted when ETH is recovered from the contract

event ETHRecovered(address indexed to, uint256 indexed amount);

Parameters

NameTypeDescription
toaddressRecipient address
amountuint256Amount 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

Git Source

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:

  1. Access roles
  2. References to external contracts
  3. Default protocol parameters
  4. 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

NameTypeDescription
adminaddressAddress with administrator privileges
_qeuroaddressAddress of the QEURO token contract
_usdcaddressAddress of the USDC token contract
_oracleaddressAddress of the Oracle contract
_hedgerPooladdressAddress of the HedgerPool contract
_userPooladdressAddress of the UserPool contract
_timelockaddressAddress of the timelock contract
_feeCollectoraddressAddress of the fee collector contract

mintQEURO

Mints QEURO tokens by swapping USDC

Minting process:

  1. Fetch EUR/USD price from oracle
  2. Calculate amount of QEURO to mint
  3. Transfer USDC from user
  4. Update vault balances
  5. 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

NameTypeDescription
usdcAmountuint256Amount of USDC to swap for QEURO
minQeuroOutuint256Minimum amount of QEURO expected (slippage protection)

redeemQEURO

Redeems QEURO for USDC

Redeem process:

  1. Calculate USDC to return based on EUR/USD price
  2. Apply protocol fees
  3. Burn QEURO
  4. Update vault balances
  5. 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to swap for USDC
minUsdcOutuint256Minimum 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

NameTypeDescription
totalUsdcHeld_uint256Total USDC held in the vault
totalMinted_uint256Total QEURO minted
totalDebtValueuint256Total 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

NameTypeDescription
usdcAmountuint256Amount of USDC to swap

Returns

NameTypeDescription
qeuroAmountuint256Amount of QEURO that will be minted (after fees)
feeuint256Protocol 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to redeem

Returns

NameTypeDescription
usdcAmountuint256USDC received (after fees)
feeuint256Protocol 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

NameTypeDescription
isCollateralizedboolTrue if protocol has active hedging positions
totalMarginuint256Total 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

NameTypeDescription
_mintFeeuint256New minting fee
_redemptionFeeuint256New 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

NameTypeDescription
_minCollateralizationRatioForMintinguint256New minimum collateralization ratio for minting (in basis points)
_criticalCollateralizationRatiouint256New 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

NameTypeDescription
_oracleaddressNew 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

NameTypeDescription
_hedgerPooladdressNew 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

NameTypeDescription
_userPooladdressNew 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

NameTypeDescription
_feeCollectoraddressNew 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

NameTypeDescription
_maxPriceDeviationuint256New maximum price deviation in basis points
_minBlocksBetweenUpdatesuint256New 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

NameTypeDescription
toaddressDestination 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

NameTypeDescription
usdcAmountuint256Amount 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

NameTypeDescription
hedgeraddressAddress of the hedger receiving the USDC
usdcAmountuint256Amount 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
isValidboolWhether 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

NameTypeDescription
ratiouint256Current 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

NameTypeDescription
<none>boolcanMint 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

NameTypeDescription
shouldLiquidateboolWhether 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

NameTypeDescription
lastValidPriceuint256Last valid EUR/USD price used
lastUpdateBlockuint256Block number of last price update
maxDeviationuint256Maximum allowed price deviation in basis points
minBlocksuint256Minimum 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

NameTypeDescription
tokenaddressToken contract address
amountuint256Amount 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

NameTypeDescription
hedgerPooladdressAddress of the HedgerPool contract that made the deposit
usdcAmountuint256Amount of USDC deposited (6 decimals)
totalUsdcHelduint256New 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

NameTypeDescription
hedgeraddressAddress of the hedger receiving the USDC
usdcAmountuint256Amount of USDC withdrawn (6 decimals)
totalUsdcHelduint256New 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

NameTypeDescription
minCollateralizationRatioForMintinguint256New minimum collateralization ratio for minting (in basis points)
criticalCollateralizationRatiouint256New critical collateralization ratio for liquidation (in basis points)
calleraddressAddress 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

NameTypeDescription
currentRatiouint256Current protocol collateralization ratio (in basis points)
canMintboolWhether minting is currently allowed based on collateralization
shouldLiquidateboolWhether liquidation should be triggered based on collateralization

PriceDeviationDetected

event PriceDeviationDetected(
    uint256 currentPrice, uint256 lastValidPrice, uint256 deviationBps, uint256 blockNumber
);

SecureUpgradeable

Git Source

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

NameTypeDescription
_timelockaddressAddress 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

NameTypeDescription
_timelockaddressAddress 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

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription of the upgrade
customDelayuint256Optional 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
isPendingboolWhether 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
upgradeITimelockUpgradeable.PendingUpgradePending 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
canExecuteboolWhether 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

NameTypeDescription
timelockAddressaddressAddress of the timelock contract
secureUpgradesEnabled_boolWhether secure upgrades are enabled
hasTimelockboolWhether 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

Git Source

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

NameTypeDescription
adminaddressThe 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription of the upgrade
customDelayuint256Optional 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription 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

NameTypeDescription
signeraddressAddress 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

NameTypeDescription
signeraddressAddress 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

NameTypeDescription
enabledboolWhether to enable emergency mode
reasonstringReason 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
upgradePendingUpgradePending 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
canExecuteboolWhether 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

NameTypeDescription
signeraddressAddress of the signer
implementationaddressAddress of the implementation

Returns

NameTypeDescription
approvedboolWhether 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

NameTypeDescription
signersaddress[]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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
signeraddressAddress 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

NameTypeDescription
signeraddressAddress 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

NameTypeDescription
_TIME_PROVIDERTimeProviderTimeProvider 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

Git Source

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

NameTypeDescription
_TIME_PROVIDERTimeProviderTimeProvider 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

NameTypeDescription
adminaddressAddress that receives admin and governance roles
_qeuroaddressAddress of the QEURO token contract
_usdcaddressAddress of the USDC token contract
_vaultaddressAddress of the QuantillonVault contract
_oracleaddressAddress of the Chainlink Oracle contract
_yieldShiftaddressAddress of the YieldShift contract
_timelockaddressAddress of the timelock contract
_treasuryaddressAddress 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

NameTypeDescription
usdcAmountsuint256[]Array of USDC amounts to deposit (6 decimals) - use [amount] for single
minQeuroOutsuint256[]Array of minimum QEURO amounts to receive (18 decimals) - use [amount] for single

Returns

NameTypeDescription
qeuroMintedAmountsuint256[]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

NameTypeDescription
amountsuint256[]Array of amounts to validate and transfer
tokenIERC20Token to transfer (usdc or qeuro)
isFromUserboolWhether to transfer from user (true) or to user (false)

Returns

NameTypeDescription
totalAmountuint256Total 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

NameTypeDescription
usdcAmountsuint256[]Array of USDC amounts (6 decimals)

Returns

NameTypeDescription
netAmountsuint256[]Array of net amounts after fees (6 decimals)
totalNetAmountuint256Total 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

NameTypeDescription
netAmountsuint256[]Array of net amounts to mint (6 decimals)
minQeuroOutsuint256[]Array of minimum QEURO outputs (18 decimals)
qeuroMintedAmountsuint256[]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

NameTypeDescription
usdcAmountsuint256[]Array of USDC amounts (6 decimals)
minQeuroOutsuint256[]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

NameTypeDescription
usdcAmountsuint256[]Array of USDC amounts (6 decimals)
qeuroMintedAmountsuint256[]Array of minted QEURO amounts (18 decimals)
currentTimeuint256Current 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

NameTypeDescription
qeuroAmountsuint256[]Array of QEURO amounts to burn (18 decimals) - use [amount] for single
minUsdcOutsuint256[]Array of minimum USDC amounts to receive (6 decimals) - use [amount] for single

Returns

NameTypeDescription
usdcReceivedAmountsuint256[]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

NameTypeDescription
qeuroAmountsuint256[]Array of QEURO amounts to withdraw
minUsdcOutsuint256[]Array of minimum USDC amounts expected
usdcReceivedAmountsuint256[]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

NameTypeDescription
qeuroAmountsuint256[]Array of QEURO amounts to redeem
minUsdcOutsuint256[]Array of minimum USDC amounts expected
usdcReceivedAmountsuint256[]Array to store received USDC amounts
withdrawalFee_uint256Cached 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

NameTypeDescription
qeuroAmountsuint256[]Array of QEURO amounts withdrawn
usdcReceivedAmountsuint256[]Array of USDC amounts received
currentTimeuint256Current 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

NameTypeDescription
qeuroAmountsuint256[]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

NameTypeDescription
qeuroAmountuint256The 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

NameTypeDescription
rewardAmountuint256Amount 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

NameTypeDescription
usersaddress[]Array of user addresses to claim rewards for

Returns

NameTypeDescription
rewardAmountsuint256[]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

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
useraddressAddress of the user to update
currentTimeuint256Current 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

NameTypeDescription
useraddressAddress of the user to query

Returns

NameTypeDescription
qeuroBalanceuint256QEURO balance of the user (18 decimals)
stakedAmountuint256Current staked amount of the user (18 decimals)
pendingRewardsuint256Total pending rewards of the user (18 decimals)
depositHistoryuint256Total historical deposits of the user (6 decimals)
lastStakeTimeuint256Timestamp of the user's last staking action
unstakeAmountuint256Amount being unstaked (18 decimals)
unstakeRequestTimeuint256Timestamp 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

NameTypeDescription
totalDepositsuint256Total USDC deposits (6 decimals)
totalWithdrawalsuint256Total QEURO withdrawals (18 decimals)
totalStakes_uint256Total QEURO staked (18 decimals)
totalUsers_uint256Total 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

NameTypeDescription
useraddressAddress of the user

Returns

NameTypeDescription
<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

NameTypeDescription
useraddressAddress of the user

Returns

NameTypeDescription
<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

NameTypeDescription
<none>uint32Oracle 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
totalUsers_uint256Number of unique users
averageDeposituint256Average deposit amount per user (6 decimals)
stakingRatiouint256Ratio of total staked QEURO to total deposits (basis points)
poolTVLuint256Total 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

NameTypeDescription
currentQeuroSupplyuint256Current QEURO total supply (net minted QEURO)
usdcEquivalentAtCurrentRateuint256Current USDC equivalent of QEURO supply
totalUsers_uint256Total number of users
totalStakes_uint256Total 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

NameTypeDescription
stakingAPY_uint256Current staking APY in basis points
depositAPY_uint256Current deposit APY in basis points
minStakeAmount_uint256Current minimum stake amount (18 decimals)
unstakingCooldown_uint256Current unstaking cooldown period (seconds)
depositFee_uint256Current deposit fee (basis points)
withdrawalFee_uint256Current withdrawal fee (basis points)
performanceFee_uint256Current 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to calculate rewards for (18 decimals)
durationuint256Duration in seconds

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
newStakingAPYuint256New Staking APY in basis points
newMinStakeAmountuint256New Minimum stake amount (18 decimals)
newUnstakingCooldownuint256New 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

NameTypeDescription
_depositFeeuint256New deposit fee in basis points
_withdrawalFeeuint256New withdrawal fee in basis points
_performanceFeeuint256New 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

NameTypeDescription
_yieldShiftaddressNew 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

NameTypeDescription
useraddressAddress 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

NameTypeDescription
<none>boolbool 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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount 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

NameTypeDescription
useraddressAddress of the user who deposited
usdcAmountuint256Amount of USDC deposited (6 decimals)
qeuroMinteduint256Amount of QEURO minted (18 decimals)
timestampuint256Timestamp 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

NameTypeDescription
useraddressAddress of the user who withdrew
qeuroBurneduint256Amount of QEURO burned (18 decimals)
usdcReceiveduint256Amount of USDC received (6 decimals)
timestampuint256Timestamp 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

NameTypeDescription
useraddressAddress of the user who deposited
usdcAmountuint256USDC amount deposited (6 decimals)
qeuroReceiveduint256QEURO amount received (18 decimals)
oracleRatiouint256Oracle ratio at time of deposit (scaled by 1e6)
timestampuint256Block timestamp when deposit was made
blockNumberuint256Block 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

NameTypeDescription
useraddressAddress of the user who withdrew
qeuroAmountuint256QEURO amount withdrawn (18 decimals)
usdcReceiveduint256USDC amount received (6 decimals)
oracleRatiouint256Oracle ratio at time of withdrawal (scaled by 1e6)
timestampuint256Block timestamp when withdrawal was made
blockNumberuint256Block 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

NameTypeDescription
useraddressAddress of the user who staked
qeuroAmountuint256Amount of QEURO staked (18 decimals)
timestampuint256Timestamp 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

NameTypeDescription
useraddressAddress of the user who unstaked
qeuroAmountuint256Amount of QEURO unstaked (18 decimals)
timestampuint256Timestamp 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

NameTypeDescription
useraddressAddress of the user who claimed rewards
rewardAmountuint256Amount of QEURO rewards claimed (18 decimals)
timestampuint256Timestamp 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

NameTypeDescription
totalYielduint256Total amount of yield distributed (18 decimals)
yieldPerShareuint256Amount of yield per staked QEURO share (18 decimals)
timestampuint256Timestamp 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

NameTypeDescription
parameterstringName of the parameter updated
oldValueuint256Original value of the parameter
newValueuint256New value of the parameter

ETHRecovered

Emitted when ETH is recovered to the treasury

event ETHRecovered(address indexed to, uint256 indexed amount);

Parameters

NameTypeDescription
toaddressRecipient address
amountuint256Amount 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

Git Source

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

NameTypeDescription
_TIME_PROVIDERTimeProviderAddress 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

NameTypeDescription
adminaddressAddress of the admin role
_qeuroaddressAddress of the QEURO token contract
_yieldShiftaddressAddress of the YieldShift contract
_usdcaddressAddress of the USDC token contract
_treasuryaddressAddress of the treasury
_timelockaddressAddress 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to stake

Returns

NameTypeDescription
stQEUROAmountuint256Amount 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

NameTypeDescription
stQEUROAmountuint256Amount of stQEURO to burn

Returns

NameTypeDescription
qeuroAmountuint256Amount 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

NameTypeDescription
qeuroAmountsuint256[]Array of QEURO amounts to stake

Returns

NameTypeDescription
stQEUROAmountsuint256[]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

NameTypeDescription
stQEUROAmountsuint256[]Array of stQEURO amounts to burn

Returns

NameTypeDescription
qeuroAmountsuint256[]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

NameTypeDescription
recipientsaddress[]Array of recipient addresses
amountsuint256[]Array of amounts to transfer

Returns

NameTypeDescription
<none>boolbool 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

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
yieldAmountuint256Pending 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
qeuroEquivalentuint256QEURO 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

NameTypeDescription
totalStQEUROSupplyuint256Total supply of stQEURO tokens
totalQEUROUnderlyinguint256Total QEURO underlying all stQEURO
currentExchangeRateuint256Current exchange rate between QEURO and stQEURO
totalYieldEarned_uint256Total yield earned by all stakers
apyuint256Annual 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
_yieldFeeuint256New yield fee in basis points
_minYieldThresholduint256New minimum yield threshold in USDC
_maxUpdateFrequencyuint256New 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
<none>uint8The 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

NameTypeDescription
useraddressAddress 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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount 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

NameTypeDescription
virtualSharesuint256Current virtual shares amount
virtualAssetsuint256Current virtual assets amount
effectiveSupplyuint256Effective supply including virtual shares
effectiveAssetsuint256Effective 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

NameTypeDescription
useraddressAddress of the user who staked
qeuroAmountuint256Amount of QEURO staked (18 decimals)
stQEUROAmountuint256Amount 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

NameTypeDescription
useraddressAddress of the user who unstaked
stQEUROAmountuint256Amount of stQEURO burned (18 decimals)
qeuroAmountuint256Amount 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

NameTypeDescription
oldRateuint256Previous exchange rate (18 decimals)
newRateuint256New exchange rate (18 decimals)
timestampuint256Timestamp 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

NameTypeDescription
yieldAmountuint256Amount of yield distributed (18 decimals)
newExchangeRateuint256New 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

NameTypeDescription
useraddressAddress of the user who claimed yield
yieldAmountuint256Amount 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

NameTypeDescription
parameterTypestring
yieldFeeuint256New yield fee in basis points
minYieldThresholduint256New minimum yield threshold
maxUpdateFrequencyuint256New maximum update frequency

ETHRecovered

Emitted when ETH is recovered to the treasury

event ETHRecovered(address indexed to, uint256 indexed amount);

Parameters

NameTypeDescription
toaddressAddress to which ETH was recovered
amountuint256Amount of ETH recovered

Contents

IAaveVault

Git Source

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

NameTypeDescription
adminaddressAdmin address
_usdcaddressUSDC token address
_aaveProvideraddressAave PoolAddressesProvider
_rewardsControlleraddressAave RewardsController address
_yieldShiftaddressYieldShift contract address
_timelockaddressTimelock contract address
_treasuryaddressTreasury 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

NameTypeDescription
amountuint256USDC amount to supply (6 decimals)

Returns

NameTypeDescription
aTokensReceiveduint256Amount 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

NameTypeDescription
amountuint256Amount of aUSDC to withdraw (use type(uint256).max for all)

Returns

NameTypeDescription
usdcWithdrawnuint256Amount 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

NameTypeDescription
rewardsClaimeduint256Claimed 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

NameTypeDescription
yieldHarvesteduint256Amount 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

NameTypeDescription
availableuint256Amount 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

NameTypeDescription
protocolYielduint256Protocol fee portion
userYielduint256Allocation to users
hedgerYielduint256Allocation 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
principalDeposited_uint256Principal USDC supplied
currentBalanceuint256Current aUSDC balance (1:1 underlying + interest)
aTokenBalanceuint256Alias for aUSDC balance
lastUpdateTimeuint256Timestamp 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

NameTypeDescription
supplyRateuint256Current supply rate (bps)
utilizationRateuint256Utilization rate (bps)
totalSupplyuint256USDC total supply
availableLiquidityuint256Available 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

NameTypeDescription
isHealthyboolTrue if pool considered healthy
pauseStatusboolWhether vault is paused
lastUpdateuint256Last 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

NameTypeDescription
rebalancedboolWhether a rebalance decision was made
newAllocationuint256New 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

NameTypeDescription
optimalAllocationuint256Target allocation (bps)
expectedYielduint256Expected 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

NameTypeDescription
_maxExposureuint256New 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

NameTypeDescription
amountWithdrawnuint256Amount 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

NameTypeDescription
exposureRatiouint256% of assets in Aave (bps)
concentrationRiskuint256Heuristic risk score (1-3)
liquidityRiskuint256Heuristic 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

NameTypeDescription
newHarvestThresholduint256Min yield to harvest
newYieldFeeuint256Protocol fee on yield (bps)
newRebalanceThresholduint256Rebalance 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

NameTypeDescription
aavePool_addressAave Pool address
aUSDC_addressaUSDC token address
harvestThreshold_uint256Current harvest threshold
yieldFee_uint256Current yield fee (bps)
maxExposure_uint256Max 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

NameTypeDescription
enabledboolNew emergency flag
reasonstringReason 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

NameTypeDescription
tokenaddressToken address
amountuint256Amount 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolbool 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

NameTypeDescription
rolebytes32The role to get the admin for

Returns

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressConfirmation 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

NameTypeDescription
<none>boolbool 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
databytesData 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>boolbool True if in emergency mode, false otherwise

IChainlinkOracle

Git Source

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

NameTypeDescription
adminaddressAddress that receives admin and manager roles
_eurUsdPriceFeedaddressChainlink EUR/USD feed address
_usdcUsdPriceFeedaddressChainlink USDC/USD feed address
_treasuryaddressTreasury 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

NameTypeDescription
priceuint256EUR/USD price in 18 decimals
isValidboolTrue 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

NameTypeDescription
priceuint256USDC/USD price in 18 decimals (should be ~1e18)
isValidboolTrue 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

NameTypeDescription
isHealthyboolTrue if both feeds are fresh, circuit breaker is off, and not paused
eurUsdFreshboolTrue if EUR/USD feed is fresh
usdcUsdFreshboolTrue 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

NameTypeDescription
currentPriceuint256Current price (may be fallback)
lastValidPriceuint256Last validated price stored
lastUpdateuint256Timestamp of last successful update
isStaleboolTrue if the feed data is stale
withinBoundsboolTrue 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

NameTypeDescription
minPriceuint256Minimum accepted EUR/USD price
maxPriceuint256Maximum accepted EUR/USD price
maxStalenessuint256Maximum allowed staleness in seconds
usdcToleranceuint256USDC tolerance in basis points
circuitBreakerActiveboolTrue 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

NameTypeDescription
eurUsdFeedAddressaddressEUR/USD feed address
usdcUsdFeedAddressaddressUSDC/USD feed address
eurUsdDecimalsuint8EUR/USD feed decimals
usdcUsdDecimalsuint8USDC/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

NameTypeDescription
eurUsdConnectedboolTrue if EUR/USD feed responds
usdcUsdConnectedboolTrue if USDC/USD feed responds
eurUsdLatestRounduint80Latest round ID for EUR/USD
usdcUsdLatestRounduint80Latest 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

NameTypeDescription
_minPriceuint256New minimum price (18 decimals)
_maxPriceuint256New 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

NameTypeDescription
newToleranceBpsuint256New 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

NameTypeDescription
_eurUsdFeedaddressNew EUR/USD feed
_usdcUsdFeedaddressNew 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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount 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

Git Source

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

NameTypeDescription
adminaddressAdmin address receiving roles
_usdcaddressUSDC token address
_oracleaddressOracle contract address
_yieldShiftaddressYieldShift contract address
_timelockaddressTimelock contract address
_treasuryaddressTreasury address
_vaultaddressQuantillonVault 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

NameTypeDescription
usdcAmountuint256The amount of USDC to use for the position (6 decimals)
leverageuint256The leverage multiplier for the position (e.g., 5 for 5x leverage)

Returns

NameTypeDescription
positionIduint256The 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

NameTypeDescription
positionIduint256The ID of the position to close

Returns

NameTypeDescription
pnlint256The 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

NameTypeDescription
positionIduint256The ID of the position to add margin to
amountuint256The 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

NameTypeDescription
positionIduint256The ID of the position to remove margin from
amountuint256The 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

NameTypeDescription
hedgeraddressThe address of the hedger whose position will be liquidated
positionIduint256The ID of the position to liquidate
saltbytes32A 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

NameTypeDescription
hedgeraddressThe address of the hedger whose position is being liquidated
positionIduint256The ID of the position to liquidate
saltbytes32The same salt value used in the commitment

Returns

NameTypeDescription
liquidationRewarduint256The 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

NameTypeDescription
hedgeraddressThe address of the hedger
positionIduint256The ID of the position

Returns

NameTypeDescription
<none>boolbool 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

NameTypeDescription
hedgeraddressThe address of the hedger
positionIduint256The 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

NameTypeDescription
hedgeraddressThe hedger address
positionIduint256The position ID to cancel liquidation for
saltbytes32Same 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

NameTypeDescription
interestDifferentialuint256USDC rewards from interest rate differential (6 decimals)
yieldShiftRewardsuint256USDC rewards from yield shift mechanism (6 decimals)
totalRewardsuint256Total 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256Unique identifier of the position to query

Returns

NameTypeDescription
positionSizeuint256Total position size in USD equivalent
marginuint256Current margin amount in USDC (6 decimals)
entryPriceuint256EUR/USD price when position was opened
currentPriceuint256Current EUR/USD price from oracle
leverageuint256Leverage multiplier used for the position
lastUpdateTimeuint256Timestamp 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256Unique identifier of the position to query

Returns

NameTypeDescription
<none>uint256marginRatio 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

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionIduint256Unique identifier of the position to check

Returns

NameTypeDescription
<none>boolliquidatable 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

NameTypeDescription
<none>uint256totalExposure 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

NameTypeDescription
newMinMarginRatiouint256New minimum margin ratio in basis points (e.g., 500 = 5%)
newLiquidationThresholduint256New liquidation threshold in basis points (e.g., 100 = 1%)
newMaxLeverageuint256New maximum leverage multiplier (e.g., 20 = 20x)
newLiquidationPenaltyuint256New 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

NameTypeDescription
newEurRateuint256New EUR interest rate in basis points (e.g., 350 = 3.5%)
newUsdRateuint256New 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

NameTypeDescription
_entryFeeuint256New entry fee in basis points (e.g., 20 = 0.2%, max 100 = 1%)
_exitFeeuint256New exit fee in basis points (e.g., 20 = 0.2%, max 100 = 1%)
_marginFeeuint256New 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

NameTypeDescription
_minMarginRatiouint256Minimum margin ratio in basis points
_liquidationThresholduint256Liquidation threshold in basis points
_maxLeverageuint256Maximum leverage multiplier
_liquidationPenaltyuint256Liquidation penalty in basis points
_entryFeeuint256Entry fee in basis points
_exitFeeuint256Exit 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position to close
positionIduint256ID 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

NameTypeDescription
<none>boolisActive 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

NameTypeDescription
tokenaddressAddress of the token to recover
amountuint256Amount 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

NameTypeDescription
<none>IERC20IERC20 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
positionIduint256The ID of the position to query

Returns

NameTypeDescription
hedgeraddressAddress of the hedger who owns the position
positionSizeuint256Total position size in USD equivalent
marginuint256Current margin amount in USDC (6 decimals)
entryPriceuint256EUR/USD price when position was opened
leverageuint256Leverage multiplier used for the position
entryTimeuint256Timestamp when position was opened
lastUpdateTimeuint256Timestamp of last position update
unrealizedPnLint256Current unrealized profit or loss
isActiveboolWhether 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
positionIdsuint256[]Array of position IDs owned by the hedger
_totalMarginuint256Total margin across all positions (6 decimals)
_totalExposureuint256Total exposure across all positions in USD
pendingRewardsuint256Pending rewards available for claim (6 decimals)
lastRewardClaimuint256Timestamp of last reward claim
isActiveboolWhether 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
<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

NameTypeDescription
useraddressAddress of the user to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
useraddressAddress of the user to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
commitmentbytes32Hash of the liquidation commitment

Returns

NameTypeDescription
<none>boolbool 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

NameTypeDescription
commitmentbytes32Hash of the liquidation commitment

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress of the hedger to query

Returns

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress of the hedger
positionIduint256ID of the position

Returns

NameTypeDescription
<none>boolbool 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
hedgeraddressAddress 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

NameTypeDescription
hedgeraddressAddress 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

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
hedgeraddressAddress to check

Returns

NameTypeDescription
<none>boolisWhitelisted 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

NameTypeDescription
<none>boolenabled 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

Git Source

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

NameTypeDescription
<none>stringname 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

NameTypeDescription
<none>stringsymbol 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

NameTypeDescription
<none>uint8decimals 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

NameTypeDescription
<none>uint256totalSupply 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

NameTypeDescription
accountaddressAddress to query

Returns

NameTypeDescription
<none>uint256balance 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

NameTypeDescription
accountaddressAddress to check

Returns

NameTypeDescription
<none>boolisMinter 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

NameTypeDescription
accountaddressAddress to check

Returns

NameTypeDescription
<none>boolisBurner 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

NameTypeDescription
<none>uint256utilization 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

NameTypeDescription
name_stringToken name
symbol_stringToken symbol
decimals_uint8Token decimals
totalSupply_uint256Current total supply
maxSupply_uint256Maximum supply cap
isPaused_boolWhether the token is paused
whitelistEnabled_boolWhether whitelist mode is active
mintRateLimit_uint256Current mint rate limit per hour
burnRateLimit_uint256Current 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

NameTypeDescription
adminaddressAddress of the admin role
vaultaddressAddress of the vault contract
timelockaddressAddress of the timelock contract
treasuryaddressTreasury 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

NameTypeDescription
toaddressAddress to receive the minted tokens
amountuint256Amount 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

NameTypeDescription
fromaddressAddress to burn tokens from
amountuint256Amount 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

NameTypeDescription
recipientsaddress[]Array of addresses to receive the minted tokens
amountsuint256[]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

NameTypeDescription
fromsaddress[]Array of addresses to burn tokens from
amountsuint256[]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

NameTypeDescription
recipientsaddress[]Array of addresses to receive the tokens
amountsuint256[]Array of amounts to transfer to each recipient (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
newMintLimituint256New maximum amount of tokens that can be minted per hour (18 decimals)
newBurnLimituint256New 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

NameTypeDescription
accountaddressAddress to blacklist
reasonstringReason 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
accountaddressAddress 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

NameTypeDescription
enabledboolTrue 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

NameTypeDescription
accountsaddress[]Array of addresses to blacklist
reasonsstring[]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

NameTypeDescription
accountsaddress[]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

NameTypeDescription
accountsaddress[]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

NameTypeDescription
accountsaddress[]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

NameTypeDescription
newPrecisionuint256New 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

NameTypeDescription
priceuint256Price value to normalize
feedDecimalsuint8Number of decimal places in the source feed

Returns

NameTypeDescription
<none>uint256normalizedPrice 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

NameTypeDescription
priceuint256Price value to validate
feedDecimalsuint8Number of decimal places in the price feed

Returns

NameTypeDescription
<none>boolisValid 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

NameTypeDescription
tokenaddressAddress of the token to recover
amountuint256Amount 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

NameTypeDescription
newMaxSupplyuint256New 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

NameTypeDescription
toaddressAddress to transfer tokens to
amountuint256Amount of tokens to transfer (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
owneraddressAddress of the token owner
spenderaddressAddress of the spender

Returns

NameTypeDescription
<none>uint256allowance 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

NameTypeDescription
spenderaddressAddress of the spender to approve
amountuint256Amount of tokens to approve (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
fromaddressAddress to transfer tokens from
toaddressAddress to transfer tokens to
amountuint256Amount of tokens to transfer (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
rolebytes32Role to check for
accountaddressAddress to check

Returns

NameTypeDescription
<none>boolhasRole 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

NameTypeDescription
rolebytes32Role to get admin for

Returns

NameTypeDescription
<none>bytes32adminRole 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

NameTypeDescription
rolebytes32Role to grant
accountaddressAddress 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

NameTypeDescription
rolebytes32Role to revoke
accountaddressAddress 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

NameTypeDescription
rolebytes32Role to renounce
callerConfirmationaddressAddress 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

NameTypeDescription
<none>boolisPaused 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
databytesEncoded 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

NameTypeDescription
<none>bytes32role 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

NameTypeDescription
<none>bytes32role 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

NameTypeDescription
<none>bytes32role 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

NameTypeDescription
<none>bytes32role 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

NameTypeDescription
<none>bytes32role 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

NameTypeDescription
<none>uint256maxSupply 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

NameTypeDescription
<none>uint256maxLimit 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

NameTypeDescription
<none>uint256precision 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

NameTypeDescription
<none>uint256maxSupply 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

NameTypeDescription
<none>uint256mintLimit 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

NameTypeDescription
<none>uint256burnLimit 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

NameTypeDescription
<none>uint256minted 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

NameTypeDescription
<none>uint256burned 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

NameTypeDescription
<none>uint256resetTime 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

NameTypeDescription
accountaddressAddress to check

Returns

NameTypeDescription
<none>boolisBlacklisted 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

NameTypeDescription
accountaddressAddress to check

Returns

NameTypeDescription
<none>boolisWhitelisted 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

NameTypeDescription
<none>boolenabled 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

NameTypeDescription
<none>uint256precision Minimum price precision value

IQTIToken

Git Source

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

NameTypeDescription
adminaddressAdmin address
_treasuryaddressTreasury address
timelockaddressTimelock 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

NameTypeDescription
amountuint256Amount of QTI to lock (18 decimals)
lockTimeuint256Duration to lock (seconds)

Returns

NameTypeDescription
veQTIuint256Voting 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

NameTypeDescription
amountuint256Amount 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

NameTypeDescription
amountsuint256[]Array of amounts to lock (18 decimals each)
lockTimesuint256[]Array of corresponding lock durations (seconds each)

Returns

NameTypeDescription
veQTIAmountsuint256[]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

NameTypeDescription
usersaddress[]Array of user addresses to unlock for

Returns

NameTypeDescription
amountsuint256[]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

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
votingPoweruint256Current 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

NameTypeDescription
newVotingPoweruint256Updated 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

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
amountuint256Locked amount (18 decimals)
unlockTimeuint256Unlock timestamp
votingPoweruint256Current voting power (18 decimals)
lastClaimTimeuint256Last claim time
initialVotingPoweruint256Initial voting power when locked (18 decimals)
lockTimeuint256Original 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

NameTypeDescription
descriptionstringProposal description
votingPerioduint256Voting period in seconds
databytesExecution data

Returns

NameTypeDescription
proposalIduint256New 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

NameTypeDescription
proposalIduint256Proposal ID
supportboolTrue 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

NameTypeDescription
proposalIdsuint256[]Array of proposal IDs
supportVotesbool[]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

NameTypeDescription
proposalIduint256Proposal 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

NameTypeDescription
proposalIduint256Proposal 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

NameTypeDescription
proposalIduint256Proposal ID

Returns

NameTypeDescription
proposeraddressProposal creator
startTimeuint256Voting start time
endTimeuint256Voting end time
forVotesuint256Votes in favor (18 decimals)
againstVotesuint256Votes against (18 decimals)
executedboolWhether executed
canceledboolWhether canceled
descriptionstringProposal 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

NameTypeDescription
proposalIduint256Proposal ID
voteraddressVoter address

Returns

NameTypeDescription
hasVotedboolWhether user voted
supportboolVote direction
votesuint256Number 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

NameTypeDescription
proposalIduint256ID of the proposal

Returns

NameTypeDescription
executionHashbytes32Hash of the execution data
executionTimeuint256Time when proposal was executed
executoraddressAddress 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

NameTypeDescription
proposalIduint256ID of the proposal

Returns

NameTypeDescription
executionHashbytes32Hash 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

NameTypeDescription
_proposalThresholduint256New proposal threshold (18 decimals)
_minVotingPerioduint256New minimum voting period (seconds)
_quorumVotesuint256New 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
_totalLockeduint256Total locked QTI (18 decimals)
_totalVotingPoweruint256Total voting power (18 decimals)
_proposalThresholduint256Proposal threshold (18 decimals)
_quorumVotesuint256Quorum requirement (18 decimals)
_currentDecentralizationLeveluint256Current 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

NameTypeDescription
<none>stringname 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

NameTypeDescription
<none>stringsymbol 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

NameTypeDescription
<none>uint8decimals 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

NameTypeDescription
<none>uint256totalSupply 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

NameTypeDescription
accountaddressAddress to query

Returns

NameTypeDescription
<none>uint256balance 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

NameTypeDescription
toaddressAddress to transfer tokens to
amountuint256Amount of tokens to transfer (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
owneraddressAddress of the token owner
spenderaddressAddress of the spender

Returns

NameTypeDescription
<none>uint256allowance 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

NameTypeDescription
spenderaddressAddress of the spender to approve
amountuint256Amount of tokens to approve (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
fromaddressAddress to transfer tokens from
toaddressAddress to transfer tokens to
amountuint256Amount of tokens to transfer (18 decimals)

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolbool 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

NameTypeDescription
rolebytes32The role to get admin for

Returns

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressThe 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

NameTypeDescription
<none>boolbool 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
databytesInitialization 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>bytes32bytes32 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
useraddressAddress of the user to query

Returns

NameTypeDescription
amountuint256Locked amount (18 decimals)
unlockTimeuint256Unlock timestamp
votingPoweruint256Current voting power (18 decimals)
lastClaimTimeuint256Last claim time
initialVotingPoweruint256Initial voting power when locked (18 decimals)
lockTimeuint256Original 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
proposalIduint256ID of the proposal to query

Returns

NameTypeDescription
proposeraddressProposal creator address
startTimeuint256Voting start timestamp
endTimeuint256Voting end timestamp
forVotesuint256Votes in favor (18 decimals)
againstVotesuint256Votes against (18 decimals)
executedboolWhether proposal was executed
canceledboolWhether proposal was canceled
descriptionstringProposal 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>addressaddress 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
tokenaddressAddress of the token to recover
amountuint256Amount 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

Git Source

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

NameTypeDescription
adminaddressAdmin address receiving roles
_qeuroaddressQEURO token address
_usdcaddressUSDC token address
_oracleaddressOracle contract address
_hedgerPooladdressHedgerPool contract address
_userPooladdressUserPool contract address
_timelockaddressTimelock 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

NameTypeDescription
usdcAmountuint256Amount of USDC to swap
minQeuroOutuint256Minimum 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to swap
minUsdcOutuint256Minimum 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

NameTypeDescription
totalUsdcHeld_uint256Total USDC held in the vault
totalMinted_uint256Total QEURO minted
totalDebtValueuint256Total 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

NameTypeDescription
usdcAmountuint256USDC to swap

Returns

NameTypeDescription
qeuroAmountuint256Expected QEURO to mint (after fees)
feeuint256Protocol 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

NameTypeDescription
qeuroAmountuint256QEURO to swap

Returns

NameTypeDescription
usdcAmountuint256USDC returned after fees
feeuint256Protocol 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

NameTypeDescription
_mintFeeuint256New minting fee
_redemptionFeeuint256New 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

NameTypeDescription
_oracleaddressNew 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

NameTypeDescription
toaddressRecipient 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

NameTypeDescription
tokenaddressToken address
toaddressRecipient
amountuint256Amount 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to get admin for

Returns

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressConfirmation 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation contract
databytesEncoded 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
isCollateralizedboolTrue if protocol has active hedging positions
totalMarginuint256Total 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
usdcAmountuint256Amount 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

NameTypeDescription
hedgeraddressAddress of the hedger receiving the USDC
usdcAmountuint256Amount 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

NameTypeDescription
<none>uint256uint256 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

NameTypeDescription
_hedgerPooladdressNew 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

NameTypeDescription
_userPooladdressNew 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

NameTypeDescription
lastValidPriceuint256Last valid EUR/USD price
lastUpdateBlockuint256Block number of last price update
maxDeviationuint256Maximum allowed price deviation
minBlocksuint256Minimum blocks between price updates

ISecureUpgradeable

Git Source

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

NameTypeDescription
adminaddressAddress 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

NameTypeDescription
_timelockaddressAddress 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

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription of the upgrade
customDelayuint256Optional 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
isPendingboolWhether 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
upgradeITimelockUpgradeable.PendingUpgradePending 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
canExecuteboolWhether 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

NameTypeDescription
timelockAddressaddressAddress of the timelock contract
secureUpgradesEnabled_boolWhether secure upgrades are enabled
hasTimelockboolWhether 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

NameTypeDescription
<none>ITimelockUpgradeableThe 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to get admin for

Returns

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressConfirmation 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation contract
databytesEncoded function call data

ITimelockUpgradeable

Git Source

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

NameTypeDescription
adminaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription of the upgrade
customDelayuint256Optional 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
implementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation
descriptionstringDescription 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

NameTypeDescription
signeraddressAddress 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

NameTypeDescription
signeraddressAddress 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

NameTypeDescription
enabledboolWhether to enable emergency mode
reasonstringReason 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
upgradePendingUpgradePending 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

NameTypeDescription
implementationaddressAddress of the implementation

Returns

NameTypeDescription
canExecuteboolWhether 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

NameTypeDescription
signeraddressAddress of the signer
implementationaddressAddress of the implementation

Returns

NameTypeDescription
approvedboolWhether 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

NameTypeDescription
signersaddress[]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

NameTypeDescription
<none>address

Returns

NameTypeDescription
implementationaddressAddress of the new implementation
proposedAtuint256Timestamp when upgrade was proposed
executableAtuint256Timestamp when upgrade can be executed
descriptionstringDescription of the upgrade
isEmergencyboolWhether this is an emergency upgrade
proposeraddressAddress 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

NameTypeDescription
signeraddressThe address to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
signeraddressThe address of the signer
newImplementationaddressThe address of the new implementation

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newImplementationaddressThe address of the new implementation

Returns

NameTypeDescription
<none>uint256Number 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
<none>uint256Default 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

NameTypeDescription
<none>uint256Maximum 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

NameTypeDescription
<none>uint256Minimum 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

NameTypeDescription
<none>uint256Maximum 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

Git Source

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

NameTypeDescription
adminaddressAdmin address
_qeuroaddressQEURO token address
_usdcaddressUSDC token address
_vaultaddressVault contract address
_yieldShiftaddressYieldShift contract address
_timelockaddressTimelock contract address
_treasuryaddressTreasury 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

NameTypeDescription
usdcAmountuint256Amount of USDC to deposit
minQeuroOutuint256Minimum QEURO expected (slippage protection)

Returns

NameTypeDescription
qeuroMinteduint256Amount 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to burn
minUsdcOutuint256Minimum USDC expected

Returns

NameTypeDescription
usdcReceiveduint256USDC 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

NameTypeDescription
qeuroAmountuint256Amount 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

NameTypeDescription
qeuroAmountuint256Amount 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

NameTypeDescription
rewardAmountuint256Amount 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

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
useraddressAddress to query

Returns

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
useraddressAddress to query

Returns

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
useraddressAddress to query

Returns

NameTypeDescription
<none>uint256Pending 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

NameTypeDescription
useraddressAddress to query

Returns

NameTypeDescription
qeuroBalanceuint256QEURO balance from deposits
stakedAmountuint256QEURO amount staked
pendingRewardsuint256Pending staking rewards
depositHistoryuint256Total historical deposits
lastStakeTimeuint256Timestamp of last stake
unstakeRequestTimeuint256Timestamp of unstake request
unstakeAmountuint256Amount 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
totalUsers_uint256Number of users
averageDeposituint256Average deposit per user
stakingRatiouint256Staking ratio (bps)
poolTVLuint256Total 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
qeuroAmountuint256QEURO amount
durationuint256Duration in seconds

Returns

NameTypeDescription
projectedRewardsuint256Expected 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

NameTypeDescription
_stakingAPYuint256New staking APY (bps)
_depositAPYuint256New base deposit APY (bps)
_minStakeAmountuint256Minimum stake amount
_unstakingCooldownuint256Unstaking 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

NameTypeDescription
_depositFeeuint256Deposit fee (bps)
_withdrawalFeeuint256Withdrawal fee (bps)
_performanceFeeuint256Performance 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

NameTypeDescription
useraddressUser 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

NameTypeDescription
_stakingAPYuint256Staking APY (bps)
_depositAPYuint256Deposit APY (bps)
_minStakeAmountuint256Minimum stake amount
_unstakingCooldownuint256Unstaking cooldown seconds
_depositFeeuint256Deposit fee (bps)
_withdrawalFeeuint256Withdrawal fee (bps)
_performanceFeeuint256Performance 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to get admin for

Returns

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressConfirmation 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation contract
databytesEncoded 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>uint256Number 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

NameTypeDescription
<none>uint256Maximum 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>addressAddress 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
<none>uint256Minimum 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

NameTypeDescription
<none>uint256Unstaking 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

NameTypeDescription
<none>uint256Deposit 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

NameTypeDescription
<none>uint256Withdrawal 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

NameTypeDescription
<none>uint256Performance 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
<none>uint256Accumulated 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

NameTypeDescription
<none>uint256Last 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
<none>uint256Last 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

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
useraddressThe user address

Returns

NameTypeDescription
qeuroBalanceuint256QEURO balance from deposits
stakedAmountuint256QEURO amount staked
pendingRewardsuint256Pending staking rewards
depositHistoryuint256Total historical deposits
lastStakeTimeuint256Timestamp of last stake
unstakeRequestTimeuint256Timestamp of unstake request
unstakeAmountuint256Amount 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

NameTypeDescription
tokenaddressToken address
amountuint256Amount 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

Git Source

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

NameTypeDescription
adminaddressAdmin address
_usdcaddressUSDC token address
_userPooladdressUserPool address
_hedgerPooladdressHedgerPool address
_aaveVaultaddressAave vault address
_stQEUROaddressstQEURO token address
_timelockaddressTimelock contract address
_treasuryaddressTreasury 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

NameTypeDescription
yieldAmountuint256Yield amount in USDC equivalent
sourcebytes32Source 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

NameTypeDescription
useraddressAddress of the user

Returns

NameTypeDescription
yieldAmountuint256Yield 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

NameTypeDescription
hedgeraddressAddress of the hedger

Returns

NameTypeDescription
yieldAmountuint256Yield 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
useraddressAddress of the user

Returns

NameTypeDescription
<none>uint256Pending 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

NameTypeDescription
hedgeraddressAddress of the hedger

Returns

NameTypeDescription
<none>uint256Pending 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

NameTypeDescription
<none>uint256Total 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

NameTypeDescription
userAllocationuint256Current allocation to users
hedgerAllocationuint256Current 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

NameTypeDescription
userPoolSizeuint256User pool size
hedgerPoolSizeuint256Hedger pool size
poolRatiouint256Ratio (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

NameTypeDescription
optimalShiftuint256Optimal shift (bps)
currentDeviationuint256Current 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

NameTypeDescription
aaveYielduint256Aave yield amount
protocolFeesuint256Protocol fees amount
interestDifferentialuint256Interest differential amount
otherSourcesuint256Other 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

NameTypeDescription
perioduint256Time period in seconds

Returns

NameTypeDescription
averageShiftuint256Average shift over period
maxShiftuint256Maximum shift over period
minShiftuint256Minimum shift over period
volatilityuint256Volatility 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

NameTypeDescription
totalYieldDistributed_uint256Total distributed
averageUserYielduint256Average user yield
averageHedgerYielduint256Average hedger yield
yieldEfficiencyuint256Yield 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

NameTypeDescription
_baseYieldShiftuint256Base allocation (bps)
_maxYieldShiftuint256Max allocation (bps)
_adjustmentSpeeduint256Adjustment 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

NameTypeDescription
_targetPoolRatiouint256Target 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

NameTypeDescription
sourceaddressAddress of the yield source
yieldTypebytes32Type 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

NameTypeDescription
sourceaddressAddress 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

NameTypeDescription
sourceaddressAddress to check
yieldTypebytes32Yield type to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
useraddressAddress of participant
amountuint256Amount to add/subtract
isUserboolTrue 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

NameTypeDescription
userAmountuint256Amount to users
hedgerAmountuint256Amount 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

NameTypeDescription
baseShiftuint256Base shift (bps)
maxShiftuint256Max shift (bps)
adjustmentSpeed_uint256Adjustment speed (bps)
lastUpdateuint256Last 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
useraddressAddress 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to get admin for

Returns

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressConfirmation 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
newImplementationaddressAddress of the new implementation contract
databytesEncoded 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

NameTypeDescription
tokenaddressToken address
amountuint256Amount 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

Git Source

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

NameTypeDescription
adminaddressAdmin address
_qeuroaddressQEURO token address
_yieldShiftaddressYieldShift contract address
_usdcaddressUSDC token address
_treasuryaddressTreasury address
timelockaddressTimelock 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

NameTypeDescription
qeuroAmountuint256Amount of QEURO to stake

Returns

NameTypeDescription
stQEUROAmountuint256Amount 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

NameTypeDescription
stQEUROAmountuint256Amount of stQEURO to burn

Returns

NameTypeDescription
qeuroAmountuint256Amount 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

NameTypeDescription
qeuroAmountsuint256[]Array of QEURO amounts

Returns

NameTypeDescription
stQEUROAmountsuint256[]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

NameTypeDescription
stQEUROAmountsuint256[]Array of stQEURO amounts

Returns

NameTypeDescription
qeuroAmountsuint256[]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

NameTypeDescription
recipientsaddress[]Array of recipient addresses
amountsuint256[]Array of amounts to transfer

Returns

NameTypeDescription
<none>boolsuccess 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

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
yieldAmountuint256Amount 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

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
yieldAmountuint256Pending 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

NameTypeDescription
<none>uint256exchangeRate 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

NameTypeDescription
<none>uint256tvl 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

NameTypeDescription
useraddressUser address

Returns

NameTypeDescription
qeuroEquivalentuint256QEURO 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

NameTypeDescription
totalStQEUROSupplyuint256Total stQEURO supply
totalQEUROUnderlyinguint256Total QEURO underlying
currentExchangeRateuint256Current exchange rate
_totalYieldEarneduint256Total yield earned
apyuint256Annual 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

NameTypeDescription
_yieldFeeuint256New yield fee percentage
_minYieldThresholduint256New minimum yield threshold
_maxUpdateFrequencyuint256New 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
useraddressUser 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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount 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

NameTypeDescription
<none>stringThe 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

NameTypeDescription
<none>stringThe 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

NameTypeDescription
<none>uint8The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
accountaddressThe account to check

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
toaddressThe recipient address
amountuint256The amount to transfer

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
owneraddressThe owner address
spenderaddressThe spender address

Returns

NameTypeDescription
<none>uint256The 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

NameTypeDescription
spenderaddressThe spender address
amountuint256The amount to approve

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
fromaddressThe sender address
toaddressThe recipient address
amountuint256The amount to transfer

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to check
accountaddressThe account to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
rolebytes32The role to check

Returns

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
rolebytes32The role to grant
accountaddressThe 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

NameTypeDescription
rolebytes32The role to revoke
accountaddressThe 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

NameTypeDescription
rolebytes32The role to renounce
callerConfirmationaddressThe 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

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newImplementationaddressThe 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

NameTypeDescription
newImplementationaddressThe new implementation address
databytesThe 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>bytes32The 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

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>addressThe 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
<none>uint256The 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

NameTypeDescription
isEnabledboolWhether virtual protection is enabled
maxDeviationuint256Maximum allowed deviation from real price
lastUpdateTimestampuint256Last time the virtual price was updated
virtualPriceuint256Current virtual price

Contents

AccessControlLibrary

Git Source

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

NameTypeDescription
accessControlAccessControlUpgradeableThe 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

NameTypeDescription
accessControlAccessControlUpgradeableThe 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

NameTypeDescription
accessControlAccessControlUpgradeableThe 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

NameTypeDescription
accessControlAccessControlUpgradeableThe 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

NameTypeDescription
accessControlAccessControlUpgradeableThe 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

NameTypeDescription
accessControlAccessControlUpgradeableThe 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

NameTypeDescription
addraddressThe 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
amountuint256The amount to validate

AdminFunctionsLibrary

Git Source

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

NameTypeDescription
contractInstanceaddressThe contract instance calling this function
treasuryaddressThe treasury address to send ETH to
adminRolebytes32The 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

NameTypeDescription
contractInstanceaddressThe contract instance calling this function
tokenaddressAddress of the token to recover
amountuint256Amount of tokens to recover
treasuryaddressThe treasury address to send tokens to
adminRolebytes32The admin role required for this operation

Events

ETHRecovered

Event emitted when ETH is recovered

event ETHRecovered(address indexed treasury, uint256 amount);

Parameters

NameTypeDescription
treasuryaddressThe treasury address that received the ETH
amountuint256The amount of ETH recovered

CommonErrorLibrary

Git Source

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

Git Source

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

NameTypeDescription
addraddressThe address to validate
errorTypestringThe 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
amountuint256The amount to validate
minAmountuint256The 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

NameTypeDescription
amountuint256The amount to validate
maxAmountuint256The 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

NameTypeDescription
percentageuint256The percentage to validate (in basis points)
maxPercentageuint256The 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

NameTypeDescription
durationuint256The duration to validate
minDurationuint256The minimum allowed duration
maxDurationuint256The 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

NameTypeDescription
priceuint256The 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

NameTypeDescription
conditionboolThe condition to validate
errorTypestringThe 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

NameTypeDescription
countuint256The current count
maxCountuint256The 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

NameTypeDescription
balanceuint256The current balance
requiredAmountuint256The 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

NameTypeDescription
addraddressThe address to validate
errorTypestringThe 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

NameTypeDescription
treasuryaddressThe 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

NameTypeDescription
receiveduint256The actual amount received
expecteduint256The expected amount
toleranceuint256The 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

NameTypeDescription
valueuint256The value to validate
thresholduint256The 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

NameTypeDescription
feeuint256The fee amount to validate
maxFeeuint256The 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

NameTypeDescription
thresholduint256The threshold value to validate
maxThresholduint256The maximum allowed threshold

FlashLoanProtectionLibrary

Git Source

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

NameTypeDescription
balanceBeforeuint256Balance before operation
balanceAfteruint256Balance after operation
maxDecreaseuint256Maximum allowed decrease in balance

Returns

NameTypeDescription
<none>boolbool True if balance change is acceptable

GovernanceErrorLibrary

Git Source

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

Git Source

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

Git Source

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

NameTypeDescription
usdcAmountuint256Amount of USDC to deposit
leverageuint256Leverage multiplier for the position
eurUsdPriceuint256Current EUR/USD price from oracle
entryFeeuint256Entry fee rate in basis points
minMarginRatiouint256Minimum margin ratio in basis points
maxMarginRatiouint256Maximum margin ratio in basis points
maxLeverageuint256Maximum allowed leverage
maxPositionsPerHedgeruint256Maximum positions per hedger
activePositionCountuint256Current active position count for hedger
maxMarginuint256Maximum margin per position
maxPositionSizeuint256Maximum position size
maxEntryPriceuint256Maximum entry price
maxLeverageValueuint256Maximum leverage value
currentTimeuint256Current timestamp

Returns

NameTypeDescription
feeuint256Calculated entry fee
netMarginuint256Net margin after fee deduction
positionSizeuint256Calculated position size
marginRatiouint256Calculated 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

NameTypeDescription
positionSizeuint256Size of the position in USDC
entryPriceuint256Price at which the position was opened
currentPriceuint256Current market price

Returns

NameTypeDescription
<none>int256Profit (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

NameTypeDescription
marginuint256Current margin amount for the position
positionSizeuint256Size of the position in USDC
entryPriceuint256Price at which the position was opened
currentPriceuint256Current market price
liquidationThresholduint256Liquidation threshold in basis points

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
totalExposureuint256Total exposure across all positions
eurInterestRateuint256EUR interest rate in basis points
usdInterestRateuint256USD interest rate in basis points
lastRewardBlockuint256Block number of last reward calculation
currentBlockuint256Current block number
maxRewardPerioduint256Maximum reward period in blocks
currentPendingRewardsuint256Current pending rewards amount

Returns

NameTypeDescription
newPendingRewardsuint256Updated pending rewards amount
newLastRewardBlockuint256Updated 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

NameTypeDescription
currentMarginuint256Current margin amount for the position
amountuint256Amount of margin to add or remove
isAdditionboolTrue if adding margin, false if removing
minMarginRatiouint256Minimum margin ratio in basis points
positionSizeuint256Size of the position in USDC
maxMarginuint256Maximum margin per position

Returns

NameTypeDescription
newMarginuint256New margin amount after operation
newMarginRatiouint256New 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position will be liquidated
positionIduint256ID of the position to liquidate
saltbytes32Random salt for commitment uniqueness
liquidatoraddressAddress of the liquidator making the commitment

Returns

NameTypeDescription
<none>bytes32Commitment 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

Git Source

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

NameTypeDescription
positionSizeuint256Size of the position in USDC
marginuint256Margin amount for the position
leverageuint256Leverage multiplier for the position
entryPriceuint256Price at which the position was opened

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
exitPriceuint256Price at which the position was closed
pnlint256Profit or loss from the position (can be negative)
timestampuint256Timestamp when the position was closed

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
marginAmountuint256Amount of margin added or removed
newMarginRatiouint256New margin ratio after the operation
isAddedboolTrue if margin was added, false if removed

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
liquidationRewarduint256Reward paid to the liquidator
remainingMarginuint256Margin remaining after liquidation

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
interestDifferentialuint256Interest rate differential between EUR and USD
yieldShiftRewardsuint256Rewards from yield shifting operations
totalRewardsuint256Total rewards accumulated

Returns

NameTypeDescription
<none>bytes32Packed 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

NameTypeDescription
rolebytes32The role to validate against
contractInstanceaddressThe 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

NameTypeDescription
positionMarginuint256The margin amount of the position being closed
vaultAddressaddressAddress of the vault contract

Returns

NameTypeDescription
isValidboolTrue 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

NameTypeDescription
vaultAddressaddressAddress of the vault contract

Returns

NameTypeDescription
isCollateralizedboolWhether protocol is currently collateralized
currentTotalMarginuint256Current total margin in the protocol
minCollateralizationRatiouint256Minimum 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

NameTypeDescription
vaultAddressaddressAddress of the vault contract

Returns

NameTypeDescription
hasMintedboolWhether 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

NameTypeDescription
vaultAddressaddressAddress of the vault contract
positionMarginuint256Margin for the position being closed
currentTotalMarginuint256Current total margin in the protocol
minCollateralizationRatiouint256Minimum collateralization ratio for minting

Returns

NameTypeDescription
isValidboolWhether 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

NameTypeDescription
hedgeraddressAddress of the hedger whose position to remove
positionIduint256ID of the position to remove
hedgerHasPositionmapping(address => mapping(uint256 => bool))Mapping of hedger to position existence
positionIndexmapping(address => mapping(uint256 => uint256))Mapping of hedger to position index
positionIdsuint256[]Array of position IDs for the hedger

Returns

NameTypeDescription
successboolTrue 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

NameTypeDescription
oracleAddressaddressAddress of the oracle contract

Returns

NameTypeDescription
priceuint256Valid EUR/USD price from oracle
isValidboolTrue if price is valid

HedgerPoolValidationLibrary

Git Source

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

NameTypeDescription
leverageuint256The leverage multiplier to validate
maxLeverageuint256The 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

NameTypeDescription
marginRatiouint256The current margin ratio to validate
minRatiouint256The 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

NameTypeDescription
marginRatiouint256The current margin ratio to validate
maxRatiouint256The 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

NameTypeDescription
lastAttemptuint256The block number of the last liquidation attempt
cooldownuint256The 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

NameTypeDescription
isActiveboolThe 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

NameTypeDescription
owneraddressThe position owner's address
calleraddressThe 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

NameTypeDescription
countuint256The current position count
maxuint256The 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

NameTypeDescription
existsboolWhether 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

NameTypeDescription
existsboolWhether 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

NameTypeDescription
netMarginuint256The net margin amount after fees
positionSizeuint256The size of the position
eurUsdPriceuint256The EUR/USD entry price
leverageuint256The leverage multiplier
maxMarginuint256Maximum allowed margin
maxPositionSizeuint256Maximum allowed position size
maxEntryPriceuint256Maximum allowed entry price
maxLeverageuint256Maximum 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

NameTypeDescription
currentMarginuint256Current total margin
currentExposureuint256Current total exposure
additionalMarginuint256Additional margin being added
additionalExposureuint256Additional exposure being added
maxTotalMarginuint256Maximum allowed total margin
maxTotalExposureuint256Maximum 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

NameTypeDescription
timestampuint256The 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

NameTypeDescription
newMarginuint256The new total margin amount
maxMarginuint256Maximum 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

NameTypeDescription
newRewardsuint256The new total pending rewards amount
maxRewardsuint256Maximum 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

NameTypeDescription
amountuint256The 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

NameTypeDescription
feeuint256The fee amount to validate
maxFeeuint256The 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

NameTypeDescription
treasuryaddressThe treasury address to validate

QTITokenGovernanceLibrary

Git Source

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

NameTypeDescription
lockTimeuint256Duration of the lock

Returns

NameTypeDescription
multiplieruint256Voting 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

NameTypeDescription
lockTimeuint256Duration of the lock

Returns

NameTypeDescription
multiplieruint256Voting 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

NameTypeDescription
amountuint256Amount of QTI tokens to lock
lockTimeuint256Duration to lock tokens

Returns

NameTypeDescription
<none>uint256votingPower 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

NameTypeDescription
amountuint256Amount of QTI tokens to lock
lockTimeuint256Duration to lock tokens

Returns

NameTypeDescription
<none>uint256votingPower 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

NameTypeDescription
lockInfoLockInfoLock information structure
currentTimeuint256Current timestamp

Returns

NameTypeDescription
votingPoweruint256Current 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

NameTypeDescription
currentTimestampuint256Current timestamp for calculation
lockTimeuint256Duration to lock tokens
existingUnlockTimeuint256Existing unlock time if already locked

Returns

NameTypeDescription
newUnlockTimeuint256Calculated 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

NameTypeDescription
currentTimestampuint256Current timestamp for calculation
lockTimeuint256Duration to lock tokens
existingUnlockTimeuint256Existing unlock time if already locked

Returns

NameTypeDescription
newUnlockTimeuint256Calculated 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

NameTypeDescription
amountsuint256[]Array of QTI amounts to lock
lockTimesuint256[]Array of lock durations

Returns

NameTypeDescription
totalAmountuint256Total 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

NameTypeDescription
amountsuint256[]Array of QTI amounts to lock
lockTimesuint256[]Array of lock durations
currentTimestampuint256Current timestamp
existingUnlockTimeuint256Existing unlock time if already locked

Returns

NameTypeDescription
totalNewVotingPoweruint256Total new voting power from all locks
totalNewAmountuint256Total new amount locked
finalUnlockTimeuint256Final unlock time after all locks
finalLockTimeuint256Final lock time
veQTIAmountsuint256[]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

NameTypeDescription
totalNewAmountuint256Total new amount to lock
newUnlockTimeuint256New unlock time
totalNewVotingPoweruint256Total new voting power
lockTimeuint256Lock duration

Returns

NameTypeDescription
updatedLockInfoLockInfoUpdated 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

NameTypeDescription
currentTimeuint256Current timestamp
decentralizationStartTimeuint256Start time for decentralization
decentralizationDurationuint256Total duration for decentralization
maxTimeElapseduint256Maximum time elapsed to consider

Returns

NameTypeDescription
newLeveluint256New 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

Git Source

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

NameTypeDescription
adminaddressThe address that will be granted DEFAULT_ADMIN_ROLE
governanceaddressThe address that will be granted GOVERNANCE_ROLE
emergencyaddressThe 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
<none>uint256Current 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

NameTypeDescription
<none>uint256Raw 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

NameTypeDescription
timestampuint256The timestamp to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
timestampuint256The timestamp to check

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
newOffsetint256The new time offset to apply
reasonstringHuman-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

NameTypeDescription
advancementuint256Amount of time to advance (in seconds)
reasonstringHuman-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

NameTypeDescription
enabledboolWhether 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

NameTypeDescription
currentProviderTimeuint256Current time according to provider
rawBlockTimestampuint256Raw block timestamp
currentOffsetint256Current time offset
isEmergencyboolWhether 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

NameTypeDescription
timestamp1uint256First timestamp
timestamp2uint256Second timestamp

Returns

NameTypeDescription
<none>int256Time 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

NameTypeDescription
newImplementationaddressAddress 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

Git Source

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

Git Source

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

NameTypeDescription
toaddressAddress to mint to
amountuint256Amount to mint
totalSupplyuint256Current total supply
maxSupplyuint256Maximum 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

NameTypeDescription
fromaddressAddress to burn from
amountuint256Amount to burn
balanceuint256Current balance

TokenValidationLibrary

Git Source

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

NameTypeDescription
feeuint256The fee amount to validate
maxFeeuint256The 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

NameTypeDescription
thresholduint256The threshold value to validate
maxThresholduint256The 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

NameTypeDescription
valueuint256The value to validate
thresholduint256The 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

NameTypeDescription
isValidboolWhether 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

NameTypeDescription
treasuryaddressThe 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

NameTypeDescription
amountuint256The amount to validate

TreasuryRecoveryLibrary

Git Source

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

NameTypeDescription
tokenaddressToken address to recover
amountuint256Amount to recover
contractAddressaddressAddress of the calling contract (for own token check)
treasuryaddressTreasury 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

NameTypeDescription
treasuryaddressThe contract's treasury address

UserPoolStakingLibrary

Git Source

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

NameTypeDescription
stakeInfoStakeInfoStake information
stakingAPYuint256Staking APY in basis points
currentTimeuint256Current timestamp

Returns

NameTypeDescription
rewardsuint256Calculated 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

NameTypeDescription
stakeInfoStakeInfoStake information
stakingAPYuint256Staking APY in basis points
currentTimeuint256Current timestamp

Returns

NameTypeDescription
rewardsuint256Calculated 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

NameTypeDescription
userStakesStakeInfo[]Array of user stakes
stakingAPYuint256Staking APY in basis points
currentTimeuint256Current timestamp

Returns

NameTypeDescription
totalRewardsuint256Total 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

NameTypeDescription
amountuint256Stake amount
durationuint256Stake duration
userStakingDataUserStakingDataUser'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

NameTypeDescription
stakeInfoStakeInfoStake information
currentTimeuint256Current 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

NameTypeDescription
stakeInfoStakeInfoStake information
currentTimeuint256Current timestamp

Returns

NameTypeDescription
penaltyuint256Penalty 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

NameTypeDescription
totalDepositsuint256Total pool deposits
totalStakeduint256Total staked amount
baseAPYuint256Base APY in basis points

Returns

NameTypeDescription
depositAPYuint256Calculated 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

NameTypeDescription
totalDepositsuint256Total pool deposits
totalStakeduint256Total staked amount
baseAPYuint256Base APY in basis points

Returns

NameTypeDescription
stakingAPYuint256Calculated 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

NameTypeDescription
amountuint256Transaction amount
baseFeeuint256Base fee in basis points
poolUtilizationuint256Pool utilization ratio

Returns

NameTypeDescription
feeuint256Calculated 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

NameTypeDescription
totalDepositsuint256Total pool deposits
totalStakeduint256Total staked amount
totalUsersuint256Total number of users

Returns

NameTypeDescription
metricsuint256Packed 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

NameTypeDescription
metricsuint256Packed pool metrics

Returns

NameTypeDescription
stakingRatiouint256Staking ratio in basis points
averageDeposituint256Average deposit per user
totalUsersuint256Total 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

Git Source

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

Git Source

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

NameTypeDescription
auint256First number
buint256Second number
cuint256Divisor

Returns

NameTypeDescription
resultuint256a * 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

NameTypeDescription
valueuint256Base value
percentageuint256Percentage in basis points (e.g., 500 = 5%)

Returns

NameTypeDescription
<none>uint256Calculated 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

NameTypeDescription
valueuint256Original value
fromDecimalsuint8Original decimal places
toDecimalsuint8Target decimal places

Returns

NameTypeDescription
scaledValueuint256Scaled 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

NameTypeDescription
auint256First number
buint256Second number

Returns

NameTypeDescription
<none>uint256Minimum 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

NameTypeDescription
auint256First number
buint256Second number

Returns

NameTypeDescription
<none>uint256Maximum 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

NameTypeDescription
eurAmountuint256Amount in EUR (18 decimals)
eurUsdRateuint256EUR/USD exchange rate (18 decimals)

Returns

NameTypeDescription
usdAmountuint256Amount 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

NameTypeDescription
usdAmountuint256Amount in USD (18 decimals)
eurUsdRateuint256EUR/USD exchange rate (18 decimals)

Returns

NameTypeDescription
eurAmountuint256Amount 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

NameTypeDescription
collateralValueuint256Total collateral value in USD
debtValueuint256Total debt value in USD

Returns

NameTypeDescription
ratiouint256Collateralization 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

NameTypeDescription
totalYielduint256Total yield generated
yieldShiftBpsuint256Yield shift percentage in basis points (0-10000)

Returns

NameTypeDescription
userYielduint256Yield allocated to QEURO users
hedgerYielduint256Yield 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

NameTypeDescription
value1uint256First value
value2uint256Second value
toleranceBpsuint256Tolerance in basis points

Returns

NameTypeDescription
<none>boolisWithinTolerance Whether values are within tolerance

YieldShiftCalculationLibrary

Git Source

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

NameTypeDescription
poolRatiouint256Current pool ratio (user/hedger)
baseYieldShiftuint256Base yield shift percentage
maxYieldShiftuint256Maximum yield shift percentage
targetPoolRatiouint256Target pool ratio

Returns

NameTypeDescription
optimalShiftuint256Optimal 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

NameTypeDescription
currentShiftuint256Current yield shift
targetShiftuint256Target yield shift
adjustmentSpeeduint256Adjustment speed (basis points per update)

Returns

NameTypeDescription
newShiftuint256New 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

NameTypeDescription
yieldShiftuint256Current yield shift percentage

Returns

NameTypeDescription
userAllocationuint256User 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

NameTypeDescription
yieldShiftuint256Current yield shift percentage

Returns

NameTypeDescription
hedgerAllocationuint256Hedger 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

NameTypeDescription
snapshotsuint256[]Array of pool snapshots

Returns

NameTypeDescription
userPoolTWAPuint256TWAP for user pool size
hedgerPoolTWAPuint256TWAP 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

NameTypeDescription
totalYielduint256Total yield to distribute
userAllocationuint256User allocation percentage
hedgerAllocationuint256Hedger allocation percentage

Returns

NameTypeDescription
userYielduint256User yield amount
hedgerYielduint256Hedger 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

NameTypeDescription
baseYieldShiftuint256Base yield shift
maxYieldShiftuint256Maximum yield shift
adjustmentSpeeduint256Adjustment speed
targetPoolRatiouint256Target pool ratio

YieldShiftOptimizationLibrary

Git Source

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

NameTypeDescription
userPoolAddressaddressAddress of the user pool contract
hedgerPoolAddressaddressAddress of the hedger pool contract

Returns

NameTypeDescription
userPoolSizeuint256Current user pool size
hedgerPoolSizeuint256Current hedger pool size
poolRatiouint256Ratio 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

NameTypeDescription
userPoolAddressaddressAddress of the user pool contract
hedgerPoolAddressaddressAddress of the hedger pool contract
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
userPoolSizeuint256Eligible user pool size (deposits older than MIN_HOLDING_PERIOD)
hedgerPoolSizeuint256Eligible hedger pool size (deposits older than MIN_HOLDING_PERIOD)
poolRatiouint256Ratio 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

NameTypeDescription
totalUserPoolSizeuint256Current total user pool size
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
eligibleSizeuint256Eligible 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

NameTypeDescription
totalUserPoolSizeuint256Current total user pool size
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
eligibleSizeuint256Eligible 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

NameTypeDescription
totalHedgerPoolSizeuint256Current total hedger pool size
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
eligibleSizeuint256Eligible 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

NameTypeDescription
totalHedgerPoolSizeuint256Current total hedger pool size
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
eligibleSizeuint256Eligible 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

NameTypeDescription
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
discountBpsuint256Discount 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

NameTypeDescription
currentTimeuint256Current timestamp
lastUpdateTimeuint256Last update timestamp

Returns

NameTypeDescription
discountBpsuint256Discount 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

NameTypeDescription
poolHistoryPoolSnapshot[]Array of pool snapshots
perioduint256Time period for calculation
isUserPoolboolWhether this is for user pool or hedger pool
currentTimeuint256Current timestamp

Returns

NameTypeDescription
<none>uint256Time 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

NameTypeDescription
poolHistoryPoolSnapshot[]Array of pool snapshots to add to
poolSizeuint256Size of the pool to record
isUserPoolboolWhether this is for user pool or hedger pool
currentTimeuint256Current timestamp

Returns

NameTypeDescription
newHistoryPoolSnapshot[]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

NameTypeDescription
userYieldPooluint256Current user yield pool amount
hedgerYieldPooluint256Current hedger yield pool amount
currentYieldShiftuint256Current yield shift percentage

Returns

NameTypeDescription
<none>uint256User 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

NameTypeDescription
userYieldPooluint256Current user yield pool amount
hedgerYieldPooluint256Current hedger yield pool amount
currentYieldShiftuint256Current yield shift percentage

Returns

NameTypeDescription
<none>uint256Hedger 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

NameTypeDescription
valueuint256The value to check
targetuint256The target value
toleranceBpsuint256Tolerance in basis points (e.g., 1000 = 10%)

Returns

NameTypeDescription
<none>boolTrue 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

NameTypeDescription
yieldShiftHistoryYieldShiftSnapshot[]Array of yield shift snapshots
perioduint256Time period to analyze
currentTimeuint256Current timestamp

Returns

NameTypeDescription
averageShiftuint256Average yield shift during the period
maxShiftuint256Maximum yield shift during the period
minShiftuint256Minimum yield shift during the period
volatilityuint256Volatility measure of yield shifts

Structs

PoolSnapshot

struct PoolSnapshot {
    uint64 timestamp;
    uint128 userPoolSize;
    uint128 hedgerPoolSize;
}

YieldShiftSnapshot

struct YieldShiftSnapshot {
    uint128 yieldShift;
    uint64 timestamp;
}

YieldValidationLibrary

Git Source

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

NameTypeDescription
shiftuint256The 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

NameTypeDescription
speeduint256The adjustment speed to validate
maxSpeeduint256The 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

NameTypeDescription
ratiouint256The target ratio to validate
maxRatiouint256The 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

NameTypeDescription
receiveduint256The actual amount received
expecteduint256The expected amount
toleranceuint256The 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

NameTypeDescription
treasuryaddressThe 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

NameTypeDescription
amountuint256The amount to validate

Contents

MockChainlinkOracle

Git Source

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

NameTypeDescription
adminaddressAdmin address
_eurUsdPriceFeedaddressMock EUR/USD feed address
_usdcUsdPriceFeedaddressMock 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

NameTypeDescription
priceuint256EUR/USD price in 18 decimals
isValidboolTrue 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

NameTypeDescription
priceuint256USDC/USD price in 18 decimals
isValidboolTrue 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

NameTypeDescription
priceint256Price from feed
feedDecimalsuint8Number of decimals in the feed

Returns

NameTypeDescription
<none>uint256Scaled price in 18 decimals

_divRound

Divides with rounding

function _divRound(uint256 a, uint256 b) internal pure returns (uint256);

Parameters

NameTypeDescription
auint256Numerator
buint256Denominator

Returns

NameTypeDescription
<none>uint256Result 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
_priceuint256The 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

NameTypeDescription
_priceuint256The 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

NameTypeDescription
_eurUsdPriceuint256The new EUR/USD price in 18 decimals
_usdcUsdPriceuint256The 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

NameTypeDescription
_updatedAtuint256The 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

Git Source

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

NameTypeDescription
toaddressThe address to mint tokens to
amountuint256The amount of tokens to mint

faucet

Faucet function for easy testing - anyone can call this

function faucet(uint256 amount) external;

Parameters

NameTypeDescription
amountuint256The amount of tokens to mint to caller

Contents

ChainlinkOracle

Git Source

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

NameTypeDescription
_TIME_PROVIDERTimeProviderAddress 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

NameTypeDescription
adminaddressAddress with administrator privileges
_eurUsdPriceFeedaddressChainlink EUR/USD price feed address on Base
_usdcUsdPriceFeedaddressChainlink USDC/USD price feed address on Base
_treasuryaddressTreasury 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

NameTypeDescription
_treasuryaddressNew 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

NameTypeDescription
auint256Numerator
buint256Denominator

Returns

NameTypeDescription
<none>uint256Result 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

NameTypeDescription
reportedTimeuint256The timestamp to validate

Returns

NameTypeDescription
<none>booltrue 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

NameTypeDescription
rawPriceint256Raw price from Chainlink
decimalsuint8Number of decimals in raw price

Returns

NameTypeDescription
<none>uint256Scaled 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

NameTypeDescription
isHealthybooltrue if everything operates normally
eurUsdFreshbooltrue if EUR/USD price is fresh
usdcUsdFreshbooltrue 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

NameTypeDescription
currentPriceuint256Current price (may be fallback)
lastValidPriceuint256Last validated price
lastUpdateuint256Timestamp of last update
isStalebooltrue if the price is stale
withinBoundsbooltrue 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

NameTypeDescription
minPriceuint256Minimum EUR/USD price
maxPriceuint256Maximum EUR/USD price
maxStalenessuint256Maximum duration before staleness
usdcToleranceuint256USDC tolerance in basis points
circuitBreakerActiveboolCircuit 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

NameTypeDescription
eurUsdFeedAddressaddressEUR/USD feed address
usdcUsdFeedAddressaddressUSDC/USD feed address
eurUsdDecimalsuint8Number of decimals for the EUR/USD feed
usdcUsdDecimalsuint8Number 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

NameTypeDescription
eurUsdConnectedbooltrue if the EUR/USD feed responds
usdcUsdConnectedbooltrue if the USDC/USD feed responds
eurUsdLatestRounduint80Latest round ID for EUR/USD
usdcUsdLatestRounduint80Latest round ID for USDC/USD

_authorizeUpgrade

Authorizes oracle contract upgrades

function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE);

Parameters

NameTypeDescription
newImplementationaddressAddress 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

NameTypeDescription
tokenaddressAddress of the token to recover
amountuint256Amount 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:

  1. Check circuit breaker status
  2. Fetch from Chainlink
  3. Freshness check (< 1 hour)
  4. Convert to 18 decimals
  5. Check min/max bounds
  6. 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

NameTypeDescription
priceuint256EUR/USD price in 18 decimals (e.g., 1.10e18 = 1.10 USD per EUR)
isValidbooltrue 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

NameTypeDescription
priceuint256USDC/USD price in 18 decimals (should be close to 1.0e18)
isValidbooltrue 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

NameTypeDescription
_minPriceuint256Minimum accepted EUR/USD price (18 decimals)
_maxPriceuint256Maximum 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

NameTypeDescription
newToleranceBpsuint256New 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

NameTypeDescription
_eurUsdFeedaddressNew EUR/USD feed address
_usdcUsdFeedaddressNew 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

NameTypeDescription
newTreasuryaddressNew treasury address

ETHRecovered

Emitted when ETH is recovered from the contract

event ETHRecovered(address indexed to, uint256 amount);