# Architecture

#### Inheritance Structure

```solidity
MetaVault
├── MetaVaultBase
│   └── MultiFacetProxy
│       └── OwnableRoles
├── Multicallable
└── NoDelegateCall

ERC7540Engine
└── ModuleBase
    └── OwnableRoles

AssetsManager
└── ModuleBase
    └── OwnableRoles

Gateway System
├── SuperformGateway
│   └── MultiFacetProxy
│       └── GatewayBase
├── InvestSuperform
│   └── GatewayBase
├── DivestSuperform
│   └── GatewayBase
└── LiquidateSuperform
    └── GatewayBase
```

#### Core Contract Relationships

**MetaVault Core**

```solidity
contract MetaVault {
    // Core state tracking
    uint128 internal _totalIdle;
    uint128 internal _totalDebt;
    
    // Module interfaces
    AssetsManager public assetsManager;
    ERC7540Engine public engine;
    ISuperformGateway public gateway;
    
    // Access control
    mapping(address => mapping(address => bool)) public isOperator;
    mapping(address => uint256) public positions;
}
```

**ERC7540Engine**

```solidity
contract ERC7540Engine {
    // Withdrawal state management
    struct ProcessRedeemRequestCache {
        uint256[WITHDRAWAL_QUEUE_SIZE][N_CHAINS] dstVaults;
        uint256[WITHDRAWAL_QUEUE_SIZE][N_CHAINS] sharesPerVault;
        uint256[WITHDRAWAL_QUEUE_SIZE][N_CHAINS] assetsPerVault;
        uint256[N_CHAINS] lens;
        // ... additional fields
    }
    
    // Withdrawal queue processing
    function _prepareWithdrawalRoute(
        ProcessRedeemRequestCache memory cache
    ) private view;
}
```

**Gateway System**

```solidity
contract GatewayBase {
    // Core gateway state
    ISuperPositions public superPositions;
    IBaseRouter public superformRouter;
    IMetaVault public vault;
    address public receiverImplementation;
    
    // Cross-chain tracking
    mapping(bytes32 => address) public receivers;
    mapping(uint256 => uint256) public pendingXChainInvests;
    uint256 public totalpendingXChainInvests;
}
```

```solidity
// Receiver contract deployment
function getReceiver(bytes32 key) public returns (address receiverAddress) {
    receiverAddress = LibClone.clone(receiverImplementation);
    ERC20Receiver(receiverAddress).initialize(key);
}
```

```
Engine Architecture Components
ERC7540EngineBase
└── Core withdrawal queue routing logic
└── State caching for cross-chain operations
└── Chain and vault selection algorithms
```

```solidity
contract ERC7540EngineBase is ModuleBase {
    // Core withdrawal routing functionality
    function _prepareWithdrawalRoute(
        ProcessRedeemRequestCache memory cache,
        bool despiseDust
    ) internal view {
        // Process local withdrawal queue
        _exhaustWithdrawalQueue(cache, localWithdrawalQueue, false, despiseDust);
        // Process cross-chain withdrawal queue
        _exhaustWithdrawalQueue(cache, xChainWithdrawalQueue, true, despiseDust);
    }
    
    // Dust threshold management
    function setDustThreshold(uint256 dustThreshold) external onlyRoles(ADMIN_ROLE) {
        // Sets minimum threshold for cross-chain withdrawals
    }
    
    function getDustThreshold() public view returns (uint256) {
        // Retrieves current minimum threshold
    }
}
```

```solidity
ERC7540EngineReader
└── Withdrawal simulation and preview
└── Route optimization analysis
```

```solidity
contract ERC7540EngineReader is ERC7540EngineBase {
    // Simulates withdrawal without execution
    function previewWithdrawalRoute(
        address controller,
        uint256 shares,
        bool despiseDust
    ) public view returns (ProcessRedeemRequestCache memory cachedRoute) {
        // Simulates complete withdrawal route
        // Calculates optimal asset sourcing from idle funds and vaults
        // Returns detailed breakdown of withdrawal strategy
    }
}
```

```
ERC7540EngineSignatures
└── Signature verification for gasless transactions
└── External processing authorization
```

```solidity
contract ERC7540EngineSignatures is ERC7540ProcessRedeemBase {
    // Verifies signed withdrawal requests
    function verifySignature(
        ProcessRedeemRequestParams calldata params,
        uint256 deadline,
        uint256 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public view returns (bool) {
        // Validates signature against expiration, nonce and request parameters
    }
    
    // Processes withdrawals initiated via signature
    function processSignedRequest(
        ProcessRedeemRequestParams calldata params,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external {
        // Processes withdrawal request authorized by signature
        // Enables gas-less withdrawals for users
    }
}
```

#### Error Catalog

```solidity
error InsufficientAssets();
error VaultNotListed();
error RequestNotFound();
error InvalidController();
error MinimumBalanceNotMet();
error InvalidSuperformId();
error InvalidRecoveryAddress();
error InvalidAmount();
error TotalAmountMismatch();
error SharesLocked();
error VaultShutdown();
error Unauthorized();
error ExceedsMaxDeposit();
error ExceedsMaxMint();
```

### State Flow Diagrams

#### Deposit Flow

1. User -> MetaVault: `requestDeposit()`
2. MetaVault: Update deposit request state
3. MetaVault -> User: `deposit()` available
4. MetaVault: Share minting and accounting

<figure><img src="/files/7U1doIm20SWDR7u7OIcZ" alt=""><figcaption></figcaption></figure>

#### Investment Flow

```solidity
// Example investment flow
function investSingleXChainSingleVault(
    SingleXChainSingleVaultStateReq calldata req
) external payable onlyVault {
    // 1. Validate and prepare
    if (!isVaultListed(vaultAddress)) revert VaultNotListed();
    
    // 2. Setup receiver
    address receiver = getReceiver(key);
    
    // 3. Track investment
    pendingXChainInvests[superformId] += amount;
    
    // 4. Initiate bridge
    gateway.investSingleXChainSingleVault{value: msg.value}(req);
}
```

<figure><img src="/files/JOp774uuwCeeCfip7FzM" alt=""><figcaption></figcaption></figure>

#### Withdrawal Flow

1. User -> MetaVault: `requestRedeem()`
2. ERC7540Engine: Process withdrawal route
3. Gateway: Handle cross-chain settlements
4. MetaVault -> User: Final redemption

<figure><img src="/files/afuUvj3mD7EZuWgVarya" alt=""><figcaption></figcaption></figure>

### Key Dependencies

#### External Protocol Integration

```solidity
interface ISuperformGateway {
    function investSingleXChainSingleVault(
        SingleXChainSingleVaultStateReq calldata req
    ) external payable;
    
    function divestSingleXChainSingleVault(
        SingleXChainSingleVaultStateReq calldata req
    ) external payable;
}
```

#### Oracle Integration

```solidity
interface ISharePriceOracle {
    function getLatestSharePrice(
        uint64 chainId,
        address vault
    ) external view returns (uint256);
}
```

### State Management

```solidity
// Request states
mapping(address => ERC7540_Request) private _pendingRedeemRequest;
mapping(address => ERC7540_FilledRequest) private _claimableRedeemRequest;
```

#### Critical State Variables

```solidity
struct VaultData {
    uint16 deductedFees;
    uint64 chainId;
    uint192 lastReportedSharePrice;
    uint256 superformId;
    ISharePriceOracle oracle;
    uint8 decimals;
    uint128 totalDebt;
    address vaultAddress;
}

// Vault positions
mapping(uint256 => VaultData) public vaults;
```

#### Cross-Chain State

```solidity
// Gateway state tracking
mapping(bytes32 => RequestData) public requests;
EnumerableSetLib.Bytes32Set internal _requestsQueue;
```

### Security Architecture

#### Access Control Matrix

| Role             | Permissions            |
| ---------------- | ---------------------- |
| ADMIN\_ROLE      | Protocol configuration |
| EMERGENCY\_ADMIN | Emergency controls     |
| ORACLE\_ROLE     | Price updates          |
| MANAGER\_ROLE    | Investment operations  |
| RELAYER\_ROLE    | Settlement processing  |

#### State Protection

```solidity
modifier nonReentrant() {
    require(_locked != 2, "ReentrancyGuard: reentrant call");
    _locked = 2;
    _;
    _locked = 1;
}

modifier noDelegateCall() {
    require(address(this) == __self, "DelegateCall");
    _;
}
```

### Upgrade Architecture

* Modular design through facet system
* Role-based module management
* State separation between core and modules

### Critical Paths

#### Investment Critical Path

1. Vault listing validation
2. Cross-chain message verification
3. Position tracking updates
4. Settlement confirmation

#### Withdrawal Critical Path

1. Share lock verification
2. Withdrawal route calculation
3. Cross-chain settlement
4. Final redemption processing

### Integration Points

#### Bridge Integration

```solidity
// Bridge configuration
function setGateway(ISuperformGateway _gateway) external onlyRoles(ADMIN_ROLE) {
    gateway = _gateway;
    asset().safeApprove(address(_gateway), type(uint256).max);
    gateway.superPositions().setApprovalForAll(address(_gateway), true);
}
```

#### Oracle Integration

```solidity
function setHurdleRateOracle(IHurdleRateOracle hurdleRateOracle) external onlyRoles(ADMIN_ROLE) {
    _hurdleRateOracle = hurdleRateOracle;
}
```


---

# 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://devs.maxapy.io/maxapy-erc7540/metavault/architecture.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.
