# EUR0 DaoCollateral

## DaoCollateral Contract Documentation

### High-Level Overview

The DaoCollateral contract is a fundamental component of the EUR0 ecosystem, designed to manage the collateralization, minting, and redemption of EUR0 tokens. It ensures that the circulating supply of EUR0 is always fully backed by Euro-denominated collateral, providing transparency and security for EUR0 holders. The contract facilitates the swapping of Euro collateral tokens for EUR0, redemption of EUR0 for Euro collateral tokens, and implements a Counter Bank Run (CBR) mechanism for emergency situations. Additionally, it provides advanced functionality for intent-based trading and integration with the SwapperEngine for EURC trading.

### Contract Summary

#### Inherited Contracts

* **ReentrancyGuardUpgradeable (OZ)**: Prevents reentrant attacks on sensitive functions.
* **PausableUpgradeable (OZ)**: Enables pausing of contract functionality by authorized accounts.
* **EIP712Upgradeable (OZ)**: Implements EIP-712 for structured data hashing and signing.
* **NoncesUpgradeable**: Manages nonce-based operations for intent matching and replay protection.

### Functionality Breakdown

#### Key Functionalities

**1. Basic Token Operations**

* **Minting and redeeming EUR0**: The contract manages the collateralization of EUR0 by handling Euro-denominated collateral tokens. When a user sends Euro collateral, the DaoCollateral contract mints the equivalent amount of EUR0 stablecoins, and vice versa, allowing users to exchange their EUR0 stablecoins for Euro collateral at the current exchange rate.

**2. Swap Operations**

* **swap**: Facilitates the conversion of Euro collateral into EUR0. Upon initiating this function, users exchange their Euro collateral tokens for EUR0 stablecoins directly.
* **swapWithPermit**: Similar to swap but uses ERC20Permit for gasless approval, allowing users to approve token transfers without a separate transaction.

**3. Redemption Operations**

* **redeem**: Allows users to redeem their EUR0 stablecoins for Euro collateral against a fee. By invoking this function, users exchange their EUR0 stablecoins for Euro collateral at the current exchange rate.
* **redeemDao**: Special redemption function for DAO operations that bypasses fees. Only callable by accounts with DAO\_REDEMPTION\_ROLE.

**4. Advanced Trading Features**

* **swapCollateralTokenToEurc**: Enables users to swap collateral tokens directly for EURC through the SwapperEngine. This function mints EUR0 internally and uses it to fulfill EURC orders on the SwapperEngine.
* **swapCollateralTokenToEurcIntent**: Advanced intent-based trading system that allows pre-signed orders to be executed by authorized parties. This enables gasless trading and more sophisticated trading strategies.

**5. Intent Management System**

* **Intent-based Trading**: The contract implements a sophisticated intent system where users can pre-sign trading instructions that can be executed by authorized parties (INTENT\_MATCHING\_ROLE).
* **Nonce Management**: Users can invalidate nonces to cancel pending intents or invalidate ranges of nonces for bulk cancellation.
* **Partial Matching**: Intents support partial fulfillment, allowing large orders to be filled incrementally.

**6. Counter Bank Run (CBR) Mechanism**

The contract implements a Counter Bank Run mechanism that can be activated in emergency situations. When activated:

* The CBR coefficient is applied to reduce the amount of collateral returned during redemptions
* Swap functionality is automatically paused
* The system helps maintain protocol stability during market stress

#### Role-Based Access Control

The contract implements a comprehensive role-based access control system for sensitive operations:

* **DEFAULT\_ADMIN\_ROLE**: Has the highest level of access, including the ability to manage CBR parameters and perform critical administrative tasks.
* **DAO\_REDEMPTION\_ROLE**: Required for special DAO redemption operations.
* **PAUSING\_CONTRACTS\_ROLE**: Grants the ability to pause specific contract functionalities in case of emergencies.
* **UNPAUSING\_CONTRACTS\_ROLE**: Grants the ability to unpause contract functionalities.
* **NONCE\_THRESHOLD\_SETTER\_ROLE**: Allows setting the nonce threshold for intent consumption.
* **INTENT\_MATCHING\_ROLE**: Required for executing intent-based trades on behalf of users.

### Functions Description

#### Public/External Functions

**Initialization**

* **initialize**: Sets up the contract with initial parameters including registry information and redeem fee.

**Basic Trading Functions**

* **swap**: Allows users to swap Euro collateral tokens for EUR0.
* **swapWithPermit**: Similar to swap but uses permit for approval.
* **redeem**: Enables users to redeem EUR0 for Euro collateral tokens.
* **redeemDao**: Special redemption function for DAO operations. Only callable by DAO\_REDEMPTION\_ROLE.

**Advanced Trading Functions**

* **swapCollateralTokenToEurc**: Swaps collateral tokens for EURC through the SwapperEngine with order matching.
* **swapCollateralTokenToEurcIntent**: Executes intent-based trades for collateral token to EURC swaps.

**Intent Management**

* **invalidateNonce**: Invalidates the current nonce for the message sender.
* **invalidateUpToNonce**: Invalidates all nonces up to a specified value for the message sender.

**Administrative Functions**

* **activateCBR**: Activates the Counter Bank Run mechanism. Only callable by DEFAULT\_ADMIN\_ROLE.
* **deactivateCBR**: Deactivates the Counter Bank Run mechanism. Only callable by DEFAULT\_ADMIN\_ROLE.
* **setRedeemFee**: Sets the fee for redemption operations. Only callable by DEFAULT\_ADMIN\_ROLE.
* **setNonceThreshold**: Sets the threshold for intent consumption. Only callable by NONCE\_THRESHOLD\_SETTER\_ROLE.

**Pausing Functions**

* **pauseRedeem, pause, pauseSwap**: Pausing functions for specific operations. Only callable by PAUSING\_CONTRACTS\_ROLE.
* **unpause, unpauseRedeem, unpauseSwap**: Global unpausing functions. Only callable by UNPAUSING\_CONTRACTS\_ROLE.

**View Functions**

* **redeemFee**: Returns the current redemption fee.
* **isCBROn**: Returns whether the Counter Bank Run mechanism is active.
* **cbrCoef**: Returns the current CBR coefficient.
* **isRedeemPaused**: Returns whether redeem functionality is paused.
* **isSwapPaused**: Returns whether swap functionality is paused.
* **nonceThreshold**: Returns the current nonce threshold for intent consumption.
* **orderAmountTakenCurrentNonce**: Returns the amount of tokens taken for the current nonce of an address.
* **DOMAIN\_SEPARATOR**: Returns the EIP712 domain separator for signature verification.

### Data Structures

#### Approval

```solidity
struct Approval {
    uint256 deadline;
    uint8 v; // Changes at each new signature because of ERC20 Permit nonce
    bytes32 r;
    bytes32 s;
}
```

#### Intent

```solidity
struct Intent {
    address recipient;
    address rwaToken;
    uint256 amountInTokenDecimals;
    uint256 deadline;
    bytes signature;
}
```

### Constants

#### Contract Addresses

* **`CONTRACT_REGISTRY_ACCESS`**: Address of the registry access contract.
* **`CONTRACT_TOKEN_MAPPING`**: Address of the token mapping contract.
* **`CONTRACT_ORACLE`**: Address of the oracle contract.
* **`CONTRACT_TREASURY`**: Address of the treasury contract.
* **`CONTRACT_EUR0`**: Address of the EUR0 token contract.
* **`CONTRACT_YIELD_TREASURY`**: Address of the yield treasury contract.
* **`CONTRACT_SWAPPER_ENGINE`**: Address of the swapper engine contract.

#### Role Identifiers

* **`DEFAULT_ADMIN_ROLE`**: Role identifier for the default admin.
* **`DAO_REDEMPTION_ROLE`**: Role identifier for DAO redemption operations.
* **`PAUSING_CONTRACTS_ROLE`**: Role identifier for pausing contract operations.
* **`UNPAUSING_CONTRACTS_ROLE`**: Role identifier for unpausing contract operations.
* **`NONCE_THRESHOLD_SETTER_ROLE`**: Role identifier for setting nonce thresholds.
* **`INTENT_MATCHING_ROLE`**: Role identifier for executing intent-based trades.

#### Fee and Calculation Constants

* **`MAX_REDEEM_FEE`**: Maximum allowed redemption fee (25%).
* **`BASIS_POINT_BASE`**: Base value for basis point calculations (10000).
* **`SCALAR_ONE`**: Scalar value representing 1 in the contract's decimal system.

#### Intent System Constants

* **`INTENT_TYPE_HASH`**: EIP712 type hash for intent signatures.

### Key Components

#### Oracle Integration

Uses an oracle to fetch real-time price data for Euro collateral tokens.

#### Token Mapping

Manages the mapping of supported Euro collateral tokens using `isEur0Collateral()` function.

#### Access Control

Implements comprehensive role-based access control for administrative functions and intent execution.

#### Treasury Management

Handles the storage and distribution of Euro collateral tokens across multiple treasuries.

#### SwapperEngine Integration

Provides seamless integration with the SwapperEngine for advanced trading operations and EURC trading.

#### Intent System

Implements a sophisticated intent-based trading system with:

* Pre-signed order execution
* Partial order fulfillment
* Nonce-based replay protection
* Gasless trading capabilities

### Safeguards Implementation

#### Pausability

Allows pausing of critical functions in emergencies with granular control over different functionalities.

#### Reentrancy Protection

Uses OpenZeppelin's ReentrancyGuard to prevent reentrancy attacks.

#### Access Control

Restricts sensitive operations to authorized roles with comprehensive role management.

#### CBR Mechanism

Implements a Counter Bank Run mechanism for emergency situations with configurable coefficients.

#### Fee Management

Implements a configurable redemption fee system with a maximum cap of 25%.

#### Intent Security

* Signature verification using EIP712
* Nonce-based replay protection
* Deadline enforcement
* Partial matching with threshold-based consumption

### Events

The contract emits various events for tracking operations:

* **Swap**: Emitted when tokens are swapped
* **Redeem**: Emitted when tokens are redeemed
* **IntentMatched**: Emitted when an intent is matched
* **IntentConsumed**: Emitted when an intent is fully consumed
* **NonceInvalidated**: Emitted when nonces are invalidated
* **CBRActivated/CBRDeactivated**: Emitted when CBR mechanism is activated/deactivated
* **RedeemFeeUpdated**: Emitted when redeem fee is updated
* **NonceThresholdSet**: Emitted when nonce threshold is set
* **RedeemPaused/RedeemUnPaused**: Emitted when redeem functionality is paused/unpaused
* **SwapPaused/SwapUnPaused**: Emitted when swap functionality is paused/unpaused


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tech.usual.money/smart-contracts/protocol-contracts/eur0/eur0-daocollateral.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
