Skip to content
Verified contractPartialGPL-3.0

RebalancingManager

Address0x6b4f05cc94b2f7ab3c15f5cc7edb9927940e9e2d
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 999,999 runs
EVM version
paris
License
GPL-3.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,247,522
Creation transaction
0xa52353bf9e…5cad7cd99c

contracts/manager/RebalancingManager.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {Create2} from "@openzeppelin/contracts/utils/Create2.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IEIP6492} from "../interfaces/IEIP6492.sol";
import {EncodeKeyLib} from "../lib/EncodeKeyLib.sol";
import {FeesLib} from "../lib/FeesLib.sol";
import {AccessControl} from "../manager/access/AccessControl.sol";
import {EIP3009Args} from "../manager/args/EIP3009Args.sol";
import {RebalancingArgs} from "../manager/args/RebalancingArgs.sol";
import {RebalancingConfigArgs} from "../manager/args/RebalancingConfigArgs.sol";
import {Operation} from "../manager/operation/Operation.sol";
import {PoolIdentifier} from "../manager/pool/PoolIdentifier.sol";
import {PoolToken} from "../manager/pool/PoolToken.sol";
import {IRebalancer} from "../rebalancer/IRebalancer.sol";
import {RebalancerProxy} from "../rebalancer/RebalancerProxy.sol";
import {IRebalancingManager} from "./IRebalancingManager.sol";

/**
 * @title RebalancingManager
 * @author MetaLend
 * @notice This contract manages the rebalancing of assets across different pools and domains (chains).
 */
contract RebalancingManager is IRebalancingManager, AccessControl {
    /// @notice The name type hash for EIP-712 signatures
    bytes32 public constant NAME_TYPEHASH = keccak256(bytes("MetaLend Rebalancing"));
    /// @notice The version type hash for EIP-712 signatures
    bytes32 public constant VERSION_TYPEHASH = keccak256(bytes("4.2.0"));
    /// @notice The domain type hash for EIP-712 signatures
    bytes32 public constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    /// @notice The withdrawal type hash for EIP-712 signatures
    bytes32 public constant WITHDRAWAL_TYPEHASH =
        keccak256("Withdrawal(address token,address poolContract,uint256 amount,uint256 deadline)");
    /// @notice USDC CCTP domain ID for the Linea mainnet
    uint32 public constant LINEA_DOMAIN_ID = 11;
    /// @notice The address of the Linea AAVE USDC aToken contract
    address private constant _LINEA_USDC_AAVE_TOKEN = 0x374D7860c4f2f604De0191298dD393703Cce84f3;

    /// @notice The address of the rebalancer implementation contract
    address private _rebalancerImplementation;
    /// @notice The address of the USDC CCTP token messenger contract
    address private _usdcCctpTokenMessenger;
    /// @notice The address of the USDC CCTP message transmitter contract
    address private _usdcCctpMessageTransmitter;
    /// @notice The gas transaction fee for on behalf of transactions
    /// @dev Discontinued storage slot in favor of _domainFees mapping supporting different fees per operation and different token decimals
    uint256 private _gasTransactionFee;
    /// @notice The address of the USDC token contract
    address private _usdcToken;
    /// @notice The cooldown period for rebalancing
    uint256 public rebalanceCooldown;
    /// @notice Mapping of owner addresses to rebalancer contract addresses
    mapping(address owner => address rebalancer) public rebalancers;
    /// @notice Mapping of destination domains, also specifies the fee on destination domain, supported is when value is greater than 0
    /// @dev Discontinued storage slot in favor of _domainFees mapping supporting different fees per operation and different token decimals
    // solhint-disable-next-line private-vars-leading-underscore
    mapping(uint32 destinationDomain => uint256 supported) private supportedDestinationDomains;
    /// @notice Mapping of rebalancer addresses to their last rebalance timestamps
    /// @dev Discontinued storage slot in favor of _rebalancerLastRebalanceTimestampPerToken which supports cooldown per token
    // solhint-disable-next-line private-vars-leading-underscore
    mapping(address rebalancer => uint256 timestamp) private rebalancerLastRebalanceTimestamp;
    /// @notice Mapping of token addresses to their corresponding pool contracts
    /// @dev Discontinued storage slot in favor of _domainPoolContract mapping which supports multiple pool contracts for the same token
    mapping(address token => mapping(PoolIdentifier pool => address poolContract)) private _tokenToPool;
    /// @notice Mapping of used withdrawal signatures
    mapping(bytes signature => bool used) private _usedWithdrawalSignatures;
    /// @notice Mapping of pool contract addresses to their corresponding token address for each pool on given domain
    /// @dev Discontinued storage slot in favor of _pools mapping which supports multiple tokens for the same pool address (such as AAVE)
    mapping(uint256 destinationDomain => mapping(address poolContract => PoolToken poolToken)) private _domainPoolContract;
    /// @notice The rebalancing fee percentage
    uint256 private _rebalancingFeePercent;
    /// @notice The destination domain for this chain
    uint32 public thisDestinationDomain;
    /// @notice The universal signature validator contract address
    address public universalSigValidator;
    /// @notice Mapping of domain to fees, additionally provides if domain is supported with value > 0 for given identifier (operation)
    /// @dev for constants use fractional human readable format, convert constant by token decimals.
    /// @dev enables future support of percentage based fees as well with a FeeType identifier included in encoded key
    mapping(uint32 domain => mapping(bytes32 identifier => uint256 gasTransactionFee)) private _domainFees;
    /// @notice Mapping of rebalancer address to token address to their last rebalance timestamp, supports cooldown per token
    mapping(address rebalancer => mapping(address token => uint256 timestamp)) private _rebalancerLastRebalanceTimestampPerToken;
    /// @notice Mapping domain to encoded supported pool (pool address, pool identifier, token) to boolean indicating if supported
    mapping(uint256 domain => mapping(bytes32 pool => bool supported)) private _pools;

    /**
     * @inheritdoc IRebalancingManager
     */
    function initialize(
        address admin_,
        address rebalancerImplementation_,
        address tokenMessenger_,
        address messageTransmitter_,
        address usdcToken_,
        uint32 thisDestinationDomain_,
        address universalSigValidator_
    ) external override {
        _initializeAdmin(admin_);
        _rebalancerImplementation = rebalancerImplementation_;
        _usdcCctpTokenMessenger = tokenMessenger_;
        _usdcCctpMessageTransmitter = messageTransmitter_;
        _usdcToken = usdcToken_;
        thisDestinationDomain = thisDestinationDomain_;
        universalSigValidator = universalSigValidator_;
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function depositWithAuthorization(
        address token,
        address onBehalfOf,
        uint32 destinationDomain,
        EIP3009Args calldata tranferArgs,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external override onlyOperator {
        // 1. preprocess the deposit operation
        address rebalancerAddress = _preprocessDeposit({
            destinationDomain: destinationDomain,
            rebalancingArgs: rebalancingArgs,
            rebalancingConfigArgs: rebalancingConfigArgs,
            onBehalfOf: onBehalfOf,
            token: token
        });
        // 2. retrieve USDC approval signature components
        (uint8 v, bytes32 r, bytes32 s) = _getSignatureComponents(onBehalfOf, tranferArgs.signature);
        // 3. trigger deposit with authorization on the rebalancer
        IRebalancer(rebalancerAddress).approveAndDeposit({
            destinationDomain: destinationDomain == thisDestinationDomain ? type(uint32).max : destinationDomain,
            pool: rebalancingArgs.pool,
            poolContract: rebalancingArgs.poolContract,
            token: token,
            amount: tranferArgs.value,
            validAfter: tranferArgs.validAfter,
            validBefore: tranferArgs.validBefore,
            nonce: tranferArgs.nonce,
            v: v,
            r: r,
            s: s
        });

        // 4. finally, emit the DepositWithAuthorization event
        emit DepositWithAuthorization(token, onBehalfOf, tranferArgs.value);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function deposit(
        address token,
        address onBehalfOf,
        uint32 destinationDomain,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external override onlyOperator {
        // 1. preprocess the deposit operation
        address rebalancerAddress = _preprocessDeposit({
            destinationDomain: destinationDomain,
            rebalancingArgs: rebalancingArgs,
            rebalancingConfigArgs: rebalancingConfigArgs,
            onBehalfOf: onBehalfOf,
            token: token
        });
        // 2. trigger deposit on the rebalancer
        uint256 amount = IRebalancer(rebalancerAddress).approveAndDeposit({
            destinationDomain: destinationDomain == thisDestinationDomain ? type(uint32).max : destinationDomain,
            pool: rebalancingArgs.pool,
            poolContract: rebalancingArgs.poolContract,
            token: token
        });

        // 3. finally, emit the Deposit event
        emit Deposit(token, onBehalfOf, amount);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function rebalanceUsdcSrc(
        address onBehalfOf,
        uint32 destinationDomain,
        uint256 amount,
        RebalancingArgs calldata rebalancingArgsFrom,
        RebalancingArgs calldata rebalancingArgsTo,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external override onlyOperator {
        // 1. ensure the rebalancer exists for the owner
        address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf);

        // 2. validation, domain must be supported, config must be valid, cooldown must be passed
        _ensureDestinationDomainSupported(destinationDomain);
        _ensurePoolContractSupported(thisDestinationDomain, rebalancingArgsFrom.poolContract, rebalancingArgsFrom.pool, _usdcToken);
        // this ensures at least 1 pool is approved for the destination domain
        _verifyPoolsApprovedAndSupported(rebalancingArgsTo, rebalancingConfigArgs, destinationDomain, _usdcToken);
        _verifyConfigSignature(onBehalfOf, rebalancingConfigArgs);
        _ensureCooldownPassedAndUpdate(rebalancerAddress, _usdcToken);

        // 3. withdraw and deposit USDC for burn
        IRebalancer(rebalancerAddress).withdrawAndDepositForBurnUsdc(
            amount,
            rebalancingArgsFrom.pool,
            rebalancingArgsFrom.poolContract,
            destinationDomain
        );

        // 4. finally, emit the RebalanceSrc event
        emit RebalanceSrc(onBehalfOf, destinationDomain, rebalancingArgsFrom.pool, _usdcToken);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function rebalanceUsdcDst(
        address onBehalfOf,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs,
        bytes calldata message,
        bytes calldata attestation
    ) external override onlyOperator {
        // 1. validation, config must be valid
        _verifyPoolsApprovedAndSupported(rebalancingArgs, rebalancingConfigArgs, thisDestinationDomain, _usdcToken);
        _verifyConfigSignature(onBehalfOf, rebalancingConfigArgs);

        // 2. get or create the rebalancer for the owner
        address rebalancerAddress = _getOrCreateRebalancer(onBehalfOf);

        // 3. claim the USDC tokens from the CCTP and deposit them into the pool
        IRebalancer(rebalancerAddress).receiveUsdcApproveAndDeposit(
            rebalancingArgs.pool,
            rebalancingArgs.poolContract,
            message,
            attestation
        );

        // 4. finally, emit the RebalanceDst event
        emit RebalanceDst(onBehalfOf, rebalancingArgs.pool, _usdcToken);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function rebalanceThisDomain(
        address onBehalfOf,
        address token,
        RebalancingArgs calldata rebalancingArgsFrom,
        RebalancingArgs calldata rebalancingArgsTo,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external override onlyOperator {
        // 1. ensure the rebalancer exists for the owner
        address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf);

        // 2. validation, config must be valid, cooldown must be passed, cannot rebalance to the same pool
        if (rebalancingArgsFrom.poolContract == rebalancingArgsTo.poolContract) {
            revert InvalidOperation();
        }
        _ensurePoolContractSupported(thisDestinationDomain, rebalancingArgsFrom.poolContract, rebalancingArgsFrom.pool, token);
        _verifyPoolsApprovedAndSupported(rebalancingArgsTo, rebalancingConfigArgs, thisDestinationDomain, token);
        _verifyConfigSignature(onBehalfOf, rebalancingConfigArgs);
        _ensureCooldownPassedAndUpdate(rebalancerAddress, token);

        // 3. withdraw from the source pool and deposit into the destination pool
        IRebalancer(rebalancerAddress).withdrawAndRedeposit({
            token: token,
            srcPool: rebalancingArgsFrom.pool,
            srcPoolContract: rebalancingArgsFrom.poolContract,
            dstPool: rebalancingArgsTo.pool,
            dstPoolContract: rebalancingArgsTo.poolContract
        });

        // 4. finally, emit the RebalanceSrc and RebalanceDst events
        emit RebalanceSrc(onBehalfOf, thisDestinationDomain, rebalancingArgsFrom.pool, token);
        emit RebalanceDst(onBehalfOf, rebalancingArgsTo.pool, token);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function fundOwner(address onBehalfOf, RebalancingConfigArgs calldata rebalancingConfigArgs) external override onlyOperator {
        // 1. validation, config must be valid, funding cap must be greater than zero, this domain must be Linea domain (11)
        if (rebalancingConfigArgs.fundingCap == 0 || !isLineaDomain()) {
            revert InvalidOperation();
        }
        _verifyConfigSignature(onBehalfOf, rebalancingConfigArgs);

        // 2. ensure the rebalancer exists for the owner
        address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf);

        // 3. fund the owner with aTokens (AAVE)
        IRebalancer(rebalancerAddress).fundOwnerWithUsdcAaveToken(rebalancingConfigArgs.fundingCap);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function withdrawFromPool(
        address onBehalfOf,
        address token,
        PoolIdentifier pool,
        address poolContract,
        uint256 amount,
        uint256 deadline,
        bytes calldata signature
    ) external override {
        address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf);
        _ensurePoolContractSupported(thisDestinationDomain, poolContract, pool, token);
        // owner withdrawal
        if (signature.length == 0) {
            if (onBehalfOf != msg.sender) {
                revert Unauthorized();
            }
            IRebalancer(rebalancerAddress).withdrawFromPoolToOwner({
                token: token,
                pool: pool,
                poolContract: poolContract,
                amount: amount,
                payFee: false
            });
        } else {
            // on behalf of withdrawal
            _verifyWithdrawalSignature({
                signer: onBehalfOf,
                signature: signature,
                token: token,
                poolContract: poolContract,
                amount: amount,
                deadline: deadline
            });
            IRebalancer(rebalancerAddress).withdrawFromPoolToOwner({
                token: token,
                pool: pool,
                poolContract: poolContract,
                amount: amount,
                payFee: true
            });
        }
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function claimRewardsMorpho(
        address rewardDistributor,
        address rewardToken,
        uint256 claimable,
        bytes32[] calldata proof
    ) external override {
        address rebalancerAddress = _getOrCreateRebalancer(msg.sender);
        IRebalancer(rebalancerAddress).claimRewardsMorpho(rewardDistributor, rewardToken, claimable, proof);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function claimRewards(
        address rewardDistributor,
        address[] calldata rewardTokens,
        uint256[] calldata claimable,
        bytes32[][] calldata proofs
    ) external override {
        address rebalancerAddress = _getOrCreateRebalancer(msg.sender);
        IRebalancer(rebalancerAddress).claimRewards(rewardDistributor, rewardTokens, claimable, proofs);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function claimRewardsAave(address rewardsController, address[] calldata assets) external override {
        address rebalancerAddress = _getOrCreateRebalancer(msg.sender);
        IRebalancer(rebalancerAddress).claimRewardsAave(rewardsController, assets);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function claimRewardsRelease(address tokenVesting) external override {
        address rebalancerAddress = _getOrCreateRebalancer(msg.sender);
        IRebalancer(rebalancerAddress).claimRewardsRelease(tokenVesting);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function collectFee(
        address[] calldata onBehalfOf,
        address[] calldata token,
        RebalancingArgs[][] calldata rebalancingArgs
    ) external override onlyOperator {
        // 1. validation of input lengths
        if (onBehalfOf.length != token.length || onBehalfOf.length != rebalancingArgs.length) {
            revert InvalidInputLength();
        }

        // 2. iterate and collect fees for each onBehalfOf address
        uint256 length = onBehalfOf.length;
        for (uint256 i = 0; i < length; ) {
            // 2.1 get rebalancer address
            address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf[i]);

            // 2.2 verify size and supported pools for each rebalancing args
            RebalancingArgs[] memory args = rebalancingArgs[i];
            address tokenEntry = token[i];
            uint256 argsLength = args.length;

            if (argsLength == 0) {
                revert InvalidInputLength();
            }

            for (uint256 j = 0; j < argsLength; ) {
                _ensurePoolContractSupported(thisDestinationDomain, args[j].poolContract, args[j].pool, tokenEntry);

                unchecked {
                    ++j;
                }
            }

            // 2.3 collect the fee
            IRebalancer(rebalancerAddress).collectFee(tokenEntry, args);

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function withdrawAllToOwner(
        address[] calldata onBehalfOf,
        address[] calldata token,
        RebalancingArgs[][] calldata rebalancingArgs
    ) external override onlyOperator {
        // 1. validation of input lengths
        if (onBehalfOf.length != token.length || onBehalfOf.length != rebalancingArgs.length) {
            revert InvalidInputLength();
        }

        // 2. iterate and withdraw all funds for each onBehalfOf address
        uint256 length = onBehalfOf.length;
        for (uint256 i = 0; i < length; ) {
            // 2.1 get rebalancer address
            address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf[i]);

            // 2.2 verify supported pools for each rebalancing args
            RebalancingArgs[] calldata args = rebalancingArgs[i];
            address tokenEntry = token[i];
            uint256 argsLength = args.length;
            for (uint256 j = 0; j < argsLength; ) {
                _ensurePoolContractSupported(thisDestinationDomain, args[j].poolContract, args[j].pool, tokenEntry);

                unchecked {
                    ++j;
                }
            }

            // 2.3 withdraw all funds to the owner
            uint256 amount = IRebalancer(rebalancerAddress).withdrawAllToOwner(tokenEntry, args);

            emit WithdrawAllToOwner(tokenEntry, onBehalfOf[i], amount);

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function claimRewardsToOwner(
        address onBehalfOf,
        address rewardDistributor,
        address[] calldata rewardTokens,
        uint256[] calldata claimable,
        bytes32[][] calldata proofs
    ) external override onlyOperator {
        // 1. validation of input lengths
        if (rewardTokens.length != claimable.length || rewardTokens.length != proofs.length) {
            revert InvalidInputLength();
        }
        // 2. ensure the rebalancer exists for the owner
        address rebalancerAddress = _getRebalancerEnsureCreated(onBehalfOf);
        // 3. claim the rewards, the rebalancer transfers them to the owner
        IRebalancer(rebalancerAddress).claimRewards(rewardDistributor, rewardTokens, claimable, proofs);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function updatePoolContract(
        uint32 destinationDomain,
        address[] calldata poolContracts,
        PoolIdentifier[] calldata pools,
        address[] calldata tokens,
        bool[] calldata supported
    ) external override onlyAdmin {
        if (poolContracts.length != pools.length || poolContracts.length != tokens.length || poolContracts.length != supported.length) {
            revert InvalidInputLength();
        }

        uint256 length = poolContracts.length;
        for (uint256 i = 0; i < length; ++i) {
            bytes32 poolKey = EncodeKeyLib._getEncodedPoolKey(poolContracts[i], pools[i], tokens[i]);
            _pools[destinationDomain][poolKey] = supported[i];
            emit PoolContractUpdated({
                destinationDomain: destinationDomain,
                poolContract: poolContracts[i],
                pool: pools[i],
                token: tokens[i],
                supported: supported[i]
            });
        }
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function updateRebalancerImplementation(address rebalancerImplementation) external override onlyAdmin {
        _rebalancerImplementation = rebalancerImplementation;

        emit RebalancerImplementationUpdated(rebalancerImplementation);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function setDomainFeeForOperation(
        uint32[] calldata domains,
        Operation[] calldata operations,
        uint256[] calldata fees
    ) external override onlyAdmin {
        if (domains.length != operations.length || domains.length != fees.length) {
            revert InvalidInputLength();
        }

        uint256 length = domains.length;
        for (uint256 i = 0; i < length; ) {
            uint32 domain = domains[i];
            Operation operation = operations[i];
            uint256 fee = fees[i];

            if (domain == type(uint32).max) {
                revert InvalidOperation();
            }
            _domainFees[domain][EncodeKeyLib._getEncodedOperationKey(operation)] = fee;

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function setRebalanceFeePercent(uint256 rebalancingFeePercent) external override onlyAdmin {
        if (rebalancingFeePercent > FeesLib.MAX_REBALANCING_FEE_PERCENT) {
            revert InvalidOperation();
        }
        _rebalancingFeePercent = rebalancingFeePercent;

        emit RebalanceFeePercentUpdated(rebalancingFeePercent);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function setRebalanceCooldown(uint256 cooldown) external override onlyAdmin {
        rebalanceCooldown = cooldown;
    }

    /**
     * @notice Returns the address of the rebalancer implementation contract
     * @dev Use this with _implementation() in the proxy contract to get the implementation address
     * @return rebalancerImplementation The address of the rebalancer implementation contract
     */
    function getRebalancerImplementation() external view override returns (address rebalancerImplementation) {
        rebalancerImplementation = _rebalancerImplementation;
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getRebalanceFee(uint256 amount, uint256 timestamp) external view override returns (uint256 rebalanceFee) {
        rebalanceFee = FeesLib.getRebalanceFee(amount, timestamp, _rebalancingFeePercent);
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getDestinationDomainGasTransactionFeeForOperation(
        uint32 destinationDomain,
        address token,
        Operation operation,
        bool useThisDomain
    ) external view override returns (uint256 gasTransactionFee) {
        gasTransactionFee = FeesLib.convertConstantFeeToRawValue(
            _domainFees[useThisDomain ? thisDestinationDomain : destinationDomain][EncodeKeyLib._getEncodedOperationKey(operation)],
            token
        );
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getUsdcCctpTokenMessenger() external view override returns (address tokenMessenger) {
        tokenMessenger = _usdcCctpTokenMessenger;
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getUsdcCctpMessageTransmitter() external view override returns (address messageTransmitter) {
        messageTransmitter = _usdcCctpMessageTransmitter;
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getUsdcToken() external view override returns (address usdcToken) {
        usdcToken = _usdcToken;
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getPoolContractSupported(
        uint32 destinationDomain,
        address poolContract,
        PoolIdentifier pool,
        address token
    ) external view override returns (bool supported) {
        supported = _pools[destinationDomain][EncodeKeyLib._getEncodedPoolKey(poolContract, pool, token)];
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function getLineaUsdcAaveToken() external pure override returns (address aToken) {
        aToken = _LINEA_USDC_AAVE_TOKEN;
    }

    /**
     * @inheritdoc IRebalancingManager
     */
    function isLineaDomain() public view override returns (bool isLinea) {
        isLinea = thisDestinationDomain == LINEA_DOMAIN_ID;
    }

    /**
     * @notice Internal function to create or get the rebalancer address for a given owner
     * @param owner                The address of the owner
     * @return rebalancerAddress   The address of the rebalancer contract
     */
    function _getOrCreateRebalancer(address owner) private returns (address rebalancerAddress) {
        if (rebalancers[owner] == address(0)) {
            rebalancerAddress = _createRebalancer(owner);
        } else {
            rebalancerAddress = rebalancers[owner];
        }
    }

    /**
     * @notice Internal function to create a new rebalancer contract
     * @dev Reverts if the rebalancer already exists for the owner
     * @param owner                The address of the owner
     * @return rebalancerAddress   The address of the newly created rebalancer contract
     */
    function _createRebalancer(address owner) private returns (address rebalancerAddress) {
        bytes memory bytecode = type(RebalancerProxy).creationCode;
        bytes memory initCode = abi.encodePacked(bytecode, abi.encode(address(this), owner));
        bytes32 salt = keccak256(abi.encodePacked(owner));
        rebalancerAddress = Create2.deploy(0, salt, initCode);
        rebalancers[owner] = rebalancerAddress;
        emit RebalancerDeployed(owner, rebalancerAddress);
    }

    /**
     * @notice Internal function to preprocess the deposit operation
     * @dev This function validates the pools, config and then gets or creates the rebalancer
     * @param destinationDomain       The destination domain for the deposit
     * @param rebalancingArgs         The rebalancing arguments. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     * @param onBehalfOf              The address on behalf of which the deposit is made
     * @param token                   The address of the token being deposited
     * @return rebalancerAddress      The address of the rebalancer contract
     */
    function _preprocessDeposit(
        uint32 destinationDomain,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs,
        address onBehalfOf,
        address token
    ) private returns (address rebalancerAddress) {
        // 1. validate approved pools and pool contracts and ensure the pool (vault) is supported for the token
        _verifyPoolsApprovedAndSupported(rebalancingArgs, rebalancingConfigArgs, destinationDomain, token);
        _verifyConfigSignature(onBehalfOf, rebalancingConfigArgs);
        // 2. double check destination domain if different than this domain
        if (destinationDomain != thisDestinationDomain) {
            _ensureDestinationDomainSupported(destinationDomain);
            // 2.1 only USDC is currently supported for cross-domain deposit
            if (token != _usdcToken) {
                revert InvalidOperation();
            }
        }
        // 3. get or create the rebalancer for the owner
        rebalancerAddress = _getOrCreateRebalancer(onBehalfOf);
        // 4. reset cooldown to allow immediate rebalancing for new deposits
        _resetCooldown(rebalancerAddress, token);
    }

    /**
     * @notice Internal function to ensure the cooldown period has passed and update the last rebalance timestamp
     * @param rebalancerAddress   The address of the rebalancer contract
     * @param token               The address of the token for which to check the cooldown
     */
    function _ensureCooldownPassedAndUpdate(address rebalancerAddress, address token) private {
        uint256 lastRebalanceTimestamp = _rebalancerLastRebalanceTimestampPerToken[rebalancerAddress][token];
        if (block.timestamp < lastRebalanceTimestamp + rebalanceCooldown) {
            revert RebalanceCooldownNotPassed(block.timestamp, lastRebalanceTimestamp + rebalanceCooldown);
        }
        _rebalancerLastRebalanceTimestampPerToken[rebalancerAddress][token] = block.timestamp;

        emit RebalancerLastRebalanceTimestampUpdated(rebalancerAddress, token, block.timestamp);
    }

    /**
     * @notice Internal function to reset the cooldown for a rebalancer
     * @dev This function sets the last rebalance timestamp to zero, effectively resetting the cooldown
     * @param rebalancerAddress   The address of the rebalancer contract
     * @param token               The address of the token for which to reset the cooldown
     */
    function _resetCooldown(address rebalancerAddress, address token) private {
        // Only reset if cooldown has NOT passed yet to avoid unnecessary storage writes
        if (block.timestamp < _rebalancerLastRebalanceTimestampPerToken[rebalancerAddress][token] + rebalanceCooldown) {
            _rebalancerLastRebalanceTimestampPerToken[rebalancerAddress][token] = 0;

            emit RebalancerLastRebalanceTimestampUpdated(rebalancerAddress, token, 0);
        }
    }

    /**
     * @notice Internal function to verify the withdrawal signature
     * @dev Reverts if the signature is invalid. The message hash is created by hashing the token address, amount and chain ID.
     * @param signer      The address of the signer
     * @param signature   The signature to verify
     * @param token       The address of the token
     * @param poolContract The address of the pool contract
     * @param amount      The amount to verify against
     * @param deadline    The deadline for the signature
     */
    function _verifyWithdrawalSignature(
        address signer,
        bytes memory signature,
        address token,
        address poolContract,
        uint256 amount,
        uint256 deadline
    ) private {
        if (block.timestamp > deadline) {
            revert InvalidDeadline(deadline);
        }
        if (_usedWithdrawalSignatures[signature]) {
            revert SignatureUsedAlready(signature);
        }
        _usedWithdrawalSignatures[signature] = true;

        bytes32 structHash = keccak256(abi.encode(WITHDRAWAL_TYPEHASH, token, poolContract, amount, deadline));
        bytes32 digest = keccak256(abi.encodePacked("\x19\x01", _getDomainSeparator(), structHash));
        _verifySignature(signer, signature, digest);
    }

    /**
     * @notice Internal function to verify the signature of the rebalancing configuration
     * @dev Reverts if the signature is invalid. The message hash is created by hashing the approved pools, pool contracts, and domains.
     * @param signer                  The address of the signer
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     */
    function _verifyConfigSignature(address signer, RebalancingConfigArgs calldata rebalancingConfigArgs) private {
        if (rebalancingConfigArgs.rebalancingManager != address(this)) {
            revert InvalidOperation();
        }

        bytes32 messageHash = keccak256(
            abi.encode(
                rebalancingConfigArgs.rebalancingManager,
                rebalancingConfigArgs.approvedPools,
                rebalancingConfigArgs.approvedPoolContracts,
                rebalancingConfigArgs.approvedDestinationDomains,
                rebalancingConfigArgs.fundingCap
            )
        );

        bytes32 ethSignedMessageHash = MessageHashUtils.toEthSignedMessageHash(messageHash);
        _verifySignature(signer, rebalancingConfigArgs.signature, ethSignedMessageHash);
    }

    /**
     * @notice Internal helper function to verify the signature
     * @dev Reverts if the signature is invalid.
     * @param signer      The address of the signer
     * @param signature   The signature to verify
     * @param digest      The digest to verify against
     */
    function _verifySignature(address signer, bytes memory signature, bytes32 digest) private {
        if (!IEIP6492(universalSigValidator).isValidSig(signer, digest, signature)) {
            revert InvalidSignature(signer, signature);
        }
    }

    /**
     *  @notice Internal function to get the EIP-712 domain separator
     *  @dev This function constructs the domain separator used for EIP-712 signatures.
     *  @return domainSeparator The EIP-712 domain separator
     */
    function _getDomainSeparator() private view returns (bytes32 domainSeparator) {
        domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, NAME_TYPEHASH, VERSION_TYPEHASH, block.chainid, address(this)));
    }

    /**
     * @notice Internal function to ensure the rebalancer exists for the given owner
     * @dev Reverts if the rebalancer does not exist
     * @param owner                The address of the owner
     * @return rebalancerAddress   The address of the rebalancer contract
     */
    function _getRebalancerEnsureCreated(address owner) private view returns (address rebalancerAddress) {
        rebalancerAddress = rebalancers[owner];
        if (rebalancerAddress == address(0)) {
            revert RebalancerNotFound(owner);
        }
    }

    /**
     * @notice Internal function to ensure the destination domain is supported
     * @dev Reverts if the destination domain is not supported
     * @param destinationDomain The destination domain to check
     */
    function _ensureDestinationDomainSupported(uint32 destinationDomain) private view {
        if (
            destinationDomain == thisDestinationDomain ||
            _domainFees[destinationDomain][EncodeKeyLib._getEncodedOperationKey(Operation.REBALANCE_DST_DOMAIN)] == 0
        ) {
            revert DestinationDomainNotSupported(destinationDomain);
        }
    }

    /**
     * @notice Internal function to ensure the pool contract is supported
     * @dev Reverts if the pool contract is not supported
     * @param destinationDomain   The destination domain to check
     * @param poolContract        The address of the pool contract to check
     * @param expectedPool        The expected pool identifier for the contract
     * @param expectedToken       The expected token address for the contract
     */
    function _ensurePoolContractSupported(
        uint32 destinationDomain,
        address poolContract,
        PoolIdentifier expectedPool,
        address expectedToken
    ) private view {
        bool isSupported = _pools[destinationDomain][EncodeKeyLib._getEncodedPoolKey(poolContract, expectedPool, expectedToken)];
        if (!isSupported) {
            revert PoolContractNotSupported(poolContract);
        }
    }

    /**
     * @notice Internal function to verify the approved pools and pool contracts
     * @dev Reverts if any of the following conditions are not met:
     *  1. The pool must be approved in the rebalancing arguments.
     *  2. The pool contract must be approved for the pool in the rebalancing arguments.
     *  3. The destination domain must be approved in the rebalancing arguments.
     *  4. The pool contract must be supported for the token.
     * @param rebalancingArgs         The rebalancing arguments. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     * @param destinationDomain       The destination domain to verify against
     * @param token                   The token address to verify against
     */
    function _verifyPoolsApprovedAndSupported(
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs,
        uint32 destinationDomain,
        address token
    ) private view {
        // 1. validate approved pools and pool contracts
        _verifyConfig(rebalancingArgs, rebalancingConfigArgs, destinationDomain);
        // 2. ensure the pool (vault) is supported for the token
        _ensurePoolContractSupported(destinationDomain, rebalancingArgs.poolContract, rebalancingArgs.pool, token);
    }

    /**
     * @notice Internal function to verify the rebalancing configuration
     * @dev Reverts if any of the following conditions are not met:
     *  1. The pool must be approved in the rebalancing arguments.
     *  2. The pool contract must be approved for the pool in the rebalancing arguments.
     *  3. The destination domain must be approved in the rebalancing arguments.
     * @param rebalancingArgs         The rebalancing arguments. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     * @param destinationDomain       The destination domain to verify against
     */
    function _verifyConfig(
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs,
        uint32 destinationDomain
    ) private pure {
        if (
            rebalancingConfigArgs.approvedPools.length != rebalancingConfigArgs.approvedPoolContracts.length ||
            rebalancingConfigArgs.approvedPools.length != rebalancingConfigArgs.approvedDestinationDomains.length
        ) {
            revert InvalidInputLength();
        }

        uint256 length = rebalancingConfigArgs.approvedPools.length;
        for (uint256 i = 0; i < length; ) {
            PoolIdentifier pool = rebalancingConfigArgs.approvedPools[i];
            address poolContract = rebalancingConfigArgs.approvedPoolContracts[i];
            uint32 domain = rebalancingConfigArgs.approvedDestinationDomains[i];

            if (pool == rebalancingArgs.pool && poolContract == rebalancingArgs.poolContract && domain == destinationDomain) {
                return;
            }

            unchecked {
                ++i;
            }
        }

        revert InvalidOperation();
    }

    /**
     * @notice Internal function to get the signature components from the signature
     * @param signer      The address of the signer
     * @param signature   The signature to extract components from
     * @return v          The v component of the signature
     * @return r          The r component of the signature
     * @return s          The s component of the signature
     */
    function _getSignatureComponents(address signer, bytes memory signature) private pure returns (uint8 v, bytes32 r, bytes32 s) {
        if (signature.length != 65) {
            revert InvalidSignature(signer, signature);
        }

        assembly ("memory-safe") {
            r := mload(add(signature, 0x20))
            s := mload(add(signature, 0x40))
            v := byte(0, mload(add(signature, 0x60)))
        }
    }
}

@openzeppelin/contracts/proxy/Proxy.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
}

@openzeppelin/contracts/utils/Create2.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Create2.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev Not enough balance for performing a CREATE2 deploy.
     */
    error Create2InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev The deployment failed.
     */
    error Create2FailedDeployment();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Create2InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        /// @solidity memory-safe-assembly
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        if (addr == address(0)) {
            revert Create2FailedDeployment();
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := keccak256(start, 85)
        }
    }
}

@openzeppelin/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

import {Strings} from "../Strings.sol";

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

@openzeppelin/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

contracts/interfaces/IEIP6492.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title IEIP6492
 * @author MetaLend
 * @notice Minimal interface for EIP-6492 signature validation.
 * @dev This interface allows for the validation of signatures according to EIP-6492.
 */
interface IEIP6492 {
    /**
     * @notice Validates a signature against a given hash.
     * @dev This function can revert if the underlying call reverts.
     * @param _signer      The address of the signer.
     * @param _hash        The hash to validate against.
     * @param _signature   The signature to validate.
     * @return bool Returns true if the signature is valid, false otherwise.
     */
    function isValidSig(address _signer, bytes32 _hash, bytes calldata _signature) external returns (bool);
}

contracts/lib/EncodeKeyLib.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {Operation} from "../manager/operation/Operation.sol";
import {PoolIdentifier} from "../manager/pool/PoolIdentifier.sol";

/**
 * @title EncodeKeyLib
 * @author MetaLend
 * @notice Library for encoding keys used in mappings
 * @dev This library provides functions to encode keys for mapping bytes32 identifiers
 */
library EncodeKeyLib {
    /**
     * @notice External function to get the encoded pool key
     * @param poolContract   The address of the pool contract
     * @param pool           The pool identifier
     * @param token          The address of the token
     * @return encodedKey    The encoded pool key
     */
    function _getEncodedPoolKey(address poolContract, PoolIdentifier pool, address token) internal pure returns (bytes32 encodedKey) {
        encodedKey = keccak256(abi.encodePacked(poolContract, pool, token));
    }

    /**
     * @notice External function to get the encoded operation key
     * @param operation     The operation type
     * @return encodedKey   The encoded operation key
     */
    function _getEncodedOperationKey(Operation operation) internal pure returns (bytes32 encodedKey) {
        encodedKey = keccak256(abi.encodePacked(operation));
    }
}

contracts/lib/FeesLib.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title IERC20
 * @author MetaLend
 * @notice Minimal interface for ERC20 tokens to get decimals
 * @dev This interface is used to interact with ERC20 tokens to retrieve their decimal places
 */
interface IERC20 {
    /**
     * @notice Get the number of decimal places for the token
     * @return The number of decimals
     */
    function decimals() external view returns (uint8);
}

/**
 * @title FeesLib
 * @author MetaLend
 * @notice Library for managing fees
 * @dev This library provides extension helper functions for fee management
 */
library FeesLib {
    /// @notice The denominator used for fee calculations
    uint256 private constant _DENOMINATOR = 1_000; // supports milli-tokens (0.001)
    /// @notice The frequency at which service percent fees are charged
    uint256 private constant _FEE_FREQUENCY = 7 days; // weekly
    /// @notice The denominator for the rebalancing fee percentage, used for basis points calculations
    uint256 private constant _REBALANCING_FEE_DENOMINATOR = 1_000_000_000; // 0.000000001 or 1e-9 precision
    /// @notice The maximum rebalancing fee percentage allowed
    uint256 public constant MAX_REBALANCING_FEE_PERCENT = 390_000; // 0.039% per week (2% annually)

    /**
     * @notice Convert a fractional human-readable fee to raw token units
     * @param constantFee   The numerator for the fee (e.g. `1` if fee = 0.001 tokens with denominator = 1000)
     * @param token         The ERC20 token address
     * @return rawValue     The fee converted into token smallest units
     */
    function convertConstantFeeToRawValue(uint256 constantFee, address token) external view returns (uint256 rawValue) {
        uint8 decimals = IERC20(token).decimals();
        uint256 base = 10 ** decimals;

        // Scale fee proportionally to token decimals
        rawValue = (constantFee * base) / _DENOMINATOR;
    }

    /**
     * @notice Calculate the rebalancing fee based on amount and elapsed time since last fee
     * @param amount             The amount to calculate the fee on
     * @param timestamp          The unix timestamp when fee was last charged
     * @param weeklyFeePercent   The full-period fee percent (per week)
     * @return rebalanceFee      The calculated rebalancing fee
     */
    function getRebalanceFee(uint256 amount, uint256 timestamp, uint256 weeklyFeePercent) external view returns (uint256 rebalanceFee) {
        if (weeklyFeePercent == 0 || amount == 0) {
            return 0;
        }
        uint256 actualFeePercent = _getActualFeePercent(timestamp, weeklyFeePercent);
        rebalanceFee = (amount * actualFeePercent) / _REBALANCING_FEE_DENOMINATOR;
    }

    /**
     * @notice Returns time-adjusted fee percent based on elapsed time
     * @param timestamp           The unix timestamp when fee was last charged
     * @param weeklyFeePercent    The full-period fee percent (per week)
     * @return actualFeePercent   Time-adjusted fee percent
     */
    function _getActualFeePercent(uint256 timestamp, uint256 weeklyFeePercent) private view returns (uint256 actualFeePercent) {
        uint256 elapsedTime = block.timestamp - timestamp;

        // solhint-disable-next-line gas-strict-inequalities
        if (elapsedTime >= _FEE_FREQUENCY) {
            return weeklyFeePercent;
        }

        // Linear proration for partial week
        actualFeePercent = (weeklyFeePercent * elapsedTime) / _FEE_FREQUENCY;
    }
}

contracts/manager/IRebalancingManager.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {EIP3009Args} from "../manager/args/EIP3009Args.sol";
import {RebalancingArgs} from "../manager/args/RebalancingArgs.sol";
import {RebalancingConfigArgs} from "../manager/args/RebalancingConfigArgs.sol";
import {Operation} from "../manager/operation/Operation.sol";
import {PoolIdentifier} from "../manager/pool/PoolIdentifier.sol";
import {IRebalancingManagerCore} from "./IRebalancingManagerCore.sol";

/**
 * @title IRebalancingManager
 * @author MetaLend
 * @notice This interface defines the functions for the RebalancingManager contract.
 */
interface IRebalancingManager is IRebalancingManagerCore {
    /**
     * @notice Emitted when a deposit with authorization is made to the pool.
     * @param token        The address of the token being deposited.
     * @param onBehalfOf   The address on behalf of which the deposit is made.
     * @param amount       The amount of tokens deposited.
     */
    event DepositWithAuthorization(address indexed token, address indexed onBehalfOf, uint256 indexed amount);

    /**
     * @notice Emitted when a deposit is made to the pool.
     * @param token        The address of the token being deposited.
     * @param onBehalfOf   The address on behalf of which the deposit is made.
     * @param amount       The amount of tokens deposited.
     */
    event Deposit(address indexed token, address indexed onBehalfOf, uint256 indexed amount);

    /**
     * @notice Emitted when a rebalance is initiated from the source domain.
     * @param onBehalfOf          The address on behalf of which the rebalance is made.
     * @param destinationDomain   The destination domain for the rebalance.
     * @param pool                The pool identifier for the rebalance.
     * @param token               The address of the token being rebalanced.
     */
    event RebalanceSrc(address indexed onBehalfOf, uint32 indexed destinationDomain, PoolIdentifier indexed pool, address token);

    /**
     * @notice Emitted when a rebalance is initiated to the destination domain.
     * @param onBehalfOf   The address on behalf of which the rebalance is made.
     * @param pool         The pool identifier for the rebalance.
     * @param token        The address of the token being rebalanced.
     */
    event RebalanceDst(address indexed onBehalfOf, PoolIdentifier indexed pool, address token);

    /**
     * @notice Emitted when Rebalancer contract is deployed.
     * @param owner        The address of the owner of the Rebalancer contract.
     * @param rebalancer   The address of the deployed Rebalancer contract.
     */
    event RebalancerDeployed(address indexed owner, address indexed rebalancer);

    /**
     * @notice Emitted when pool contract is updated to a specific pool and token.
     * @param destinationDomain   The domain supporting the pool contract
     * @param poolContract        The address of the pool contract being updated.
     * @param pool                The pool identifier for which the contract is being updated.
     * @param token               The address of the token associated with the pool.
     * @param supported           Boolean indicating whether the pool contract is supported or not.
     */
    event PoolContractUpdated(uint32 destinationDomain, address indexed poolContract, PoolIdentifier pool, address token, bool supported);

    /**
     * @notice Emitted when a rebalancer's last rebalance timestamp is updated.
     * @param rebalancer               The address of the rebalancer.
     * @param token                    The address of the token for which the timestamp is updated.
     * @param lastRebalanceTimestamp   The last rebalance timestamp.
     */
    event RebalancerLastRebalanceTimestampUpdated(
        address indexed rebalancer,
        address indexed token,
        uint256 indexed lastRebalanceTimestamp
    );

    /**
     * @notice Emitted when the implementation address of the rebalancer contract is updated.
     * @param rebalancerImplementation The address of the new rebalancer implementation contract.
     */
    event RebalancerImplementationUpdated(address indexed rebalancerImplementation);

    /**
     * @notice Emitted when the rebalance fee percent is updated.
     * @param rebalanceFeePercent The new rebalance fee percent.
     */
    event RebalanceFeePercentUpdated(uint256 indexed rebalanceFeePercent);

    /**
     * @notice Emitted when all funds of a token are withdrawn by the operator on behalf of the owner of a rebalancer.
     * @param token        The address of the token withdrawn.
     * @param onBehalfOf   The address on behalf of which the withdrawal is made, receiver of the tokens.
     * @param amount       The amount of tokens transferred to the owner.
     */
    event WithdrawAllToOwner(address indexed token, address indexed onBehalfOf, uint256 amount);

    /// @notice Thrown when Rebalancer contract is not found.
    error RebalancerNotFound(address owner);

    /// @notice Thrown when pool contract is not supported.
    error PoolContractNotSupported(address poolContract);

    /// @notice Thrown when the destination domain is not supported.
    error DestinationDomainNotSupported(uint32 destinationDomain);

    /// @notice Thrown when the signature is invalid.
    error InvalidSignature(address signer, bytes signature);

    /// @notice Thrown when the deadline for the transaction has passed.
    error InvalidDeadline(uint256 deadline);

    /// @notice Thrown when signature is used already.
    error SignatureUsedAlready(bytes signature);

    /// @notice Thrown when the cooldown period for rebalancing has not passed.
    error RebalanceCooldownNotPassed(uint256 lastRebalanceTimestamp, uint256 rebalanceCooldown);

    /// @notice Thrown when the input length is invalid.
    error InvalidInputLength();

    /// @notice Thrown when the operation is not allowed.
    error InvalidOperation();

    /**
     * @notice Initializes the RebalancingManager contract.
     * @param admin_                      The address of the admin.
     * @param rebalancerImplementation_   The address of the rebalancer implementation contract.
     * @param tokenMessenger_             The address of the token messenger contract.
     * @param messageTransmitter_         The address of the message transmitter contract.
     * @param usdcToken_                  The address of the USDC token contract.
     * @param thisDestinationDomain_      The destination domain for this contract.
     * @param universalSigValidator_      The address of the universal signature validator contract.
     */
    function initialize(
        address admin_,
        address rebalancerImplementation_,
        address tokenMessenger_,
        address messageTransmitter_,
        address usdcToken_,
        uint32 thisDestinationDomain_,
        address universalSigValidator_
    ) external;

    /**
     * @notice Gets or deploys a Rebalancer contract for the specified owner. Then calls the rebalancer to deposit tokens to a yield.
     *  When destination domain is other than this domain, the deposit is made directly to bridge for rebalance.
     * @param token                   The address of the token being deposited. Currently only USDC is supported.
     * @param onBehalfOf              The address on behalf of which the deposit is made. Also the payer.
     * @param destinationDomain       The destination domain for the deposit.
     * @param tranferArgs             The transfer arguments for the EIP-3009 transfer. See `EIP3009Args` struct for details.
     * @param rebalancingArgs         The rebalancing arguments for the deposit. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     */
    function depositWithAuthorization(
        address token,
        address onBehalfOf,
        uint32 destinationDomain,
        EIP3009Args calldata tranferArgs,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external;

    /**
     * @notice Gets or deploys a Rebalancer contract for the specified owner. Then calls the rebalancer to deposit tokens to a yield.
     *  When destination domain is other than this domain, the deposit is made directly to bridge for rebalance.
     * @dev The rebalancer contract must be pre-approved to spend the tokens on behalf of the owner.
     *  This is used for deposits with contract wallets. USDC token does not support EIP-6492 signature validation.
     *  That means contract wallets that are not deployed yet cannot have their signatures validated by USDC token.
     * @param token                   The address of the token being deposited. Currently only USDC is supported.
     * @param onBehalfOf              The address on behalf of which the deposit is made. Also the payer.
     * @param destinationDomain       The destination domain for the deposit.
     * @param rebalancingArgs         The rebalancing arguments for the deposit. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     */
    function deposit(
        address token,
        address onBehalfOf,
        uint32 destinationDomain,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external;

    /**
     * @notice Gets a Rebalancer contract for the specified owner. Then calls the rebalancer to rebalance tokens from the source domain.
     * @dev In this case the Rebalancer must already exist.
     * @param onBehalfOf              The address on behalf of which the rebalance is made.
     * @param destinationDomain       The destination domain for the rebalance.
     * @param amount                  The amount of tokens being rebalanced. Use MAX_UINT256 for full amount.
     * @param rebalancingArgsFrom     The rebalancing arguments for the rebalance. See `RebalancingArgs` struct for details.
     * @param rebalancingArgsTo       The rebalancing arguments for the destination. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     */
    function rebalanceUsdcSrc(
        address onBehalfOf,
        uint32 destinationDomain,
        uint256 amount,
        RebalancingArgs calldata rebalancingArgsFrom,
        RebalancingArgs calldata rebalancingArgsTo,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external;

    /**
     * @notice Gets or deploys a Rebalancer contract for the specified owner. Then calls the rebalancer to rebalance on destination domain.
     * @param onBehalfOf              The address on behalf of which the rebalance is made.
     * @param rebalancingArgs         The rebalancing arguments for the deposit. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     * @param message                 The message emitted by MessageSent event during depositForBurn.
     * @param attestation             The attestation retrieved from the CCTP API.
     */
    function rebalanceUsdcDst(
        address onBehalfOf,
        RebalancingArgs calldata rebalancingArgs,
        RebalancingConfigArgs calldata rebalancingConfigArgs,
        bytes calldata message,
        bytes calldata attestation
    ) external;

    /**
     * @notice Gets a Rebalancer contract for the specified owner. Then calls the rebalancer to rebalance token on this domain.
     * @dev In this case the Rebalancer must already exist.
     * @param onBehalfOf              The address on behalf of which the rebalance is made.
     * @param token                   The address of the token being rebalanced.
     * @param rebalancingArgsFrom     The rebalancing arguments for the source pool. See `RebalancingArgs` struct for details.
     * @param rebalancingArgsTo       The rebalancing arguments for the destination pool. See `RebalancingArgs` struct for details.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     */
    function rebalanceThisDomain(
        address onBehalfOf,
        address token,
        RebalancingArgs calldata rebalancingArgsFrom,
        RebalancingArgs calldata rebalancingArgsTo,
        RebalancingConfigArgs calldata rebalancingConfigArgs
    ) external;

    /**
     * @notice Gets a Rebalancer contract for the specified owner. Then calls the rebalancer to fund the owner tokens.
     * @dev In this case the Rebalancer must already exist. Can be called only on Linea domain (11).
     * @param onBehalfOf              The address on behalf of which the funding is made.
     * @param rebalancingConfigArgs   The rebalancing configuration arguments. See `RebalancingConfigArgs` struct for details.
     */
    function fundOwner(address onBehalfOf, RebalancingConfigArgs calldata rebalancingConfigArgs) external;

    /**
     * @notice Gets a Rebalancer contract for the specified owner. Then calls the rebalancer to withdraw tokens from specified pool.
     * @dev In this case the Rebalancer must already exist. Callable by either the owner or by operator on their behalf.
     * @param onBehalfOf     The address on behalf of which the withdrawal is made.
     * @param token          The address of the token being withdrawn.
     * @param pool           The pool identifier from which the tokens are withdrawn.
     * @param poolContract   The address of the pool contract from which the tokens are withdrawn.
     * @param amount         The amount of tokens withdrawn.
     * @param deadline       The timestamp before which the withdrawal is valid. Needed only when done by the operator.
     * @param signature      The signature for the authorization. Necessary only when done by the operator.
     */
    function withdrawFromPool(
        address onBehalfOf,
        address token,
        PoolIdentifier pool,
        address poolContract,
        uint256 amount,
        uint256 deadline,
        bytes calldata signature
    ) external;

    /**
     * @notice Claims rewards from Morpho vaults.
     * @dev Callable by only by owners of rebalancers.
     * @param rewardDistributor   The address of the reward distributor contract.
     * @param rewardToken         The address of the reward token contract.
     * @param claimable           The overall claimable amount of token rewards.
     * @param proof               The Merkle proof array that verifies the claim's validity.
     */
    function claimRewardsMorpho(address rewardDistributor, address rewardToken, uint256 claimable, bytes32[] calldata proof) external;

    /**
     * @notice Claims rewards. Rewards are from Morpho, Merkl, and any other similar reward distributor.
     * @dev Callable by only by owners of rebalancers.
     * @param rewardDistributor    The address of the reward distributor contracts.
     * @param rewardTokens         The addresses of the reward token contracts.
     * @param claimable            The overall claimable amounts of token rewards.
     * @param proofs               The Merkle proof arrays that verify the claims' validity.
     */
    function claimRewards(
        address rewardDistributor,
        address[] calldata rewardTokens,
        uint256[] calldata claimable,
        bytes32[][] calldata proofs
    ) external;

    /**
     * @notice Claims rewards from Aave lending pool.
     * @dev Callable by only by owners of rebalancers.
     * @param rewardsController   The address of the Aave rewards controller contract.
     * @param assets              The list of asset addresses to claim rewards for.
     */
    function claimRewardsAave(address rewardsController, address[] calldata assets) external;

    /**
     * @notice Releases all vested rewards to the owner.
     * @dev Callable by only by owners of rebalancers.
     * @param tokenVesting The address of the token vesting contract.
     */
    function claimRewardsRelease(address tokenVesting) external;

    /**
     * @notice Collects service fees for the specified tokens on behalf of the specified addresses.
     * @dev The length of `onBehalfOf`, `token`, and `rebalancingArgs` must be the same.
     *  Inner arrays of `rebalancingArgs` must not be empty.
     *  Each `rebalancingArgs` inner array corresponds to the respective `onBehalfOf` and `token` at the same index.
     * @param onBehalfOf        The addresses on behalf of which the fees are collected.
     * @param token             The addresses of the tokens for which the fees are collected.
     * @param rebalancingArgs   The rebalancing arguments for the fee collection. See `RebalancingArgs` struct for details.
     */
    function collectFee(address[] calldata onBehalfOf, address[] calldata token, RebalancingArgs[][] calldata rebalancingArgs) external;

    /**
     * @notice Withdraws all funds of the specified tokens from the specified pools on behalf of the specified addresses.
     *  The funds are transferred to the owners of the rebalancers (the `onBehalfOf` addresses), no fee is paid.
     * @dev Callable only by operators, used to return the funds of all users when the service is discontinued.
     *  The length of `onBehalfOf`, `token`, and `rebalancingArgs` must be the same.
     *  Each `rebalancingArgs` inner array corresponds to the respective `onBehalfOf` and `token` at the same index.
     *  Pools without a position are skipped. An empty inner array transfers only the tokens already held by the rebalancer.
     * @param onBehalfOf        The addresses on behalf of which the withdrawals are made.
     * @param token             The addresses of the tokens withdrawn.
     * @param rebalancingArgs   The pools to withdraw from. See `RebalancingArgs` struct for details.
     */
    function withdrawAllToOwner(
        address[] calldata onBehalfOf,
        address[] calldata token,
        RebalancingArgs[][] calldata rebalancingArgs
    ) external;

    /**
     * @notice Claims rewards on behalf of the owner of a rebalancer and transfers them to the owner.
     *  Rewards are from Morpho, Merkl, and any other similar reward distributor. Equivalent of `claimRewards` called by the owner.
     * @dev Callable only by operators, used to return the rewards of all users when the service is discontinued.
     *  The rebalancer must exist. The length of `rewardTokens`, `claimable`, and `proofs` must be the same.
     * @param onBehalfOf          The address on behalf of which the rewards are claimed, receiver of the rewards.
     * @param rewardDistributor   The address of the reward distributor contract.
     * @param rewardTokens        The addresses of the reward token contracts.
     * @param claimable           The overall claimable amounts of token rewards.
     * @param proofs              The Merkle proof arrays that verify the claims' validity.
     */
    function claimRewardsToOwner(
        address onBehalfOf,
        address rewardDistributor,
        address[] calldata rewardTokens,
        uint256[] calldata claimable,
        bytes32[][] calldata proofs
    ) external;

    /**
     * @notice Updates the pool contract addresses to specified pools and associated tokens.
     * @dev This function is only callable by the admin.
     *  The length of `poolContracts`, `pools`, `tokens` and `supported` must be the same.
     * @param destinationDomain   The destination domain for which the pool contracts are being updated.
     * @param poolContracts       The addresses of the pool contracts to be updated.
     * @param pools               The pool identifiers corresponding to the pool contracts.
     * @param tokens              The addresses of the tokens for the pools.
     * @param supported           The boolean array indicating whether the pool contract is supported or not.
     */
    function updatePoolContract(
        uint32 destinationDomain,
        address[] calldata poolContracts,
        PoolIdentifier[] calldata pools,
        address[] calldata tokens,
        bool[] calldata supported
    ) external;

    /**
     * @notice Updates the implementation address of the rebalancer contract.
     * @dev This function is only callable by the admin.
     * @param rebalancerImplementation  The address of the new rebalancer implementation contract.
     */
    function updateRebalancerImplementation(address rebalancerImplementation) external;

    /**
     * @notice Updates the fees for operations on specified domains. Effectively supporting the domain.
     * @dev This function is only callable by the admin.
     *  The value must be a fractional human-readable fee with 3 decimal precision (e.g. `1` if fee = 0.001 tokens with denominator = 1000).
     *  The length of `domains`, `operations` and `fees` must be the same.
     * @param domains              The destination domains for which the fees are being updated.
     * @param operations           The operations for which the fees are being updated.
     * @param fees                 The new fees for the specified domains and operations
     *  > 0 if the operation on destination domain is supported, 0 if not.
     */
    function setDomainFeeForOperation(uint32[] calldata domains, Operation[] calldata operations, uint256[] calldata fees) external;

    /**
     * @notice Updates the rebalance fee percent.
     * @dev This function is only callable by the admin.
     * @param rebalanceFeePercent The new rebalance fee percent.
     */
    function setRebalanceFeePercent(uint256 rebalanceFeePercent) external;

    /**
     * @notice Sets the rebalance cooldown period.
     * @dev This function is only callable by the admin.
     * @param cooldown The new cooldown period for rebalancing in seconds.
     */
    function setRebalanceCooldown(uint256 cooldown) external;

    /**
     * @notice Gets the amount of rebalance fee for a given amount.
     * @param amount          The amount of tokens for which the rebalance fee is being calculated.
     * @param timestamp       The timestamp to consider for fee calculation
     * @return rebalanceFee   The calculated rebalance fee for the specified amount.
     */
    function getRebalanceFee(uint256 amount, uint256 timestamp) external view returns (uint256 rebalanceFee);

    /**
     * @notice Retrieves the transaction fee for operation on a specific destination domain.
     * @param destinationDomain   The destination domain for which the gas transaction fee is being queried.
     * @param token               The address of the token for which the gas transaction fee is being queried.
     * @param operation           The operation for which the gas transaction fee is being queried.
     * @param useThisDomain       Boolean indicating whether to use this domain's fee for same domain operations.
     *  In this case the destinationDomain is ignored.
     * @return gasTransactionFee  The gas transaction fee for the specified destination domain and operation.
     */
    function getDestinationDomainGasTransactionFeeForOperation(
        uint32 destinationDomain,
        address token,
        Operation operation,
        bool useThisDomain
    ) external view returns (uint256 gasTransactionFee);

    /**
     * @notice Retrieves the token messenger contract address.
     * @return tokenMessenger The address of the token messenger contract.
     */
    function getUsdcCctpTokenMessenger() external view returns (address tokenMessenger);

    /**
     * @notice Retrieves the message transmitter contract address.
     * @return messageTransmitter The address of the message transmitter contract.
     */
    function getUsdcCctpMessageTransmitter() external view returns (address messageTransmitter);

    /**
     * @notice Retrieves the USDC token contract address.
     * @return usdcToken The address of the USDC token contract.
     */
    function getUsdcToken() external view returns (address usdcToken);

    /**
     * @notice Retrieves the pool and token for given pool contract.
     * @param destinationDomain   The destination domain for which the pool contracts is queried.
     * @param poolContract        The address of the pool contract for which the pool and token are queried.
     * @param pool                The pool identifier for which the contract is being queried.
     * @param token               The address of the token associated with the pool contract being queried.
     * @return supported          True if the pool contract is supported, false otherwise.
     */
    function getPoolContractSupported(
        uint32 destinationDomain,
        address poolContract,
        PoolIdentifier pool,
        address token
    ) external view returns (bool supported);

    /**
     * @notice Checks if the current domain is Linea.
     * @return isLinea True if the current domain is Linea, false otherwise.
     */
    function isLineaDomain() external view returns (bool isLinea);

    /**
     * @notice Retrieves the Linea AAVE USDC aToken contract address.
     * @return aToken The address of the Linea AAVE USDC aToken contract.
     */
    function getLineaUsdcAaveToken() external pure returns (address aToken);
}

contracts/manager/IRebalancingManagerCore.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title IRebalancingManagerCore
 * @author MetaLend
 * @notice Core rebalancing manager interface to read rebalancer implementation
 */
interface IRebalancingManagerCore {
    /**
     * @notice Returns the address of the rebalancer implementation contract
     * @dev Use this with _implementation() in the proxy contract to get the implementation address
     * @return rebalancerImplementation The address of the rebalancer implementation contract
     */
    function getRebalancerImplementation() external view returns (address rebalancerImplementation);
}

contracts/manager/access/AccessControl.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";

/**
 * @title AccessControl
 * @author MetaLend
 * @notice Contract module that provides access control mechanisms
 */
abstract contract AccessControl is IAccessControl {
    /// @notice Operator role identifier
    bytes32 private constant _OPERATOR_ROLE = keccak256("OPERATOR_ROLE");

    /// @notice Admin address
    address private _admin;

    /// @notice Operator role mapping
    mapping(address account => bytes32 role) public roles;

    /// @notice Modifier to restrict access to admin
    modifier onlyAdmin() {
        if (msg.sender != _admin) revert Unauthorized();
        _;
    }

    /// @notice Modifier to restrict access to operator
    modifier onlyOperator() {
        if (roles[msg.sender] != _OPERATOR_ROLE) revert Unauthorized();
        _;
    }

    /**
     * @inheritdoc IAccessControl
     */
    function setAdmin(address newAdmin) external override onlyAdmin {
        require(newAdmin != address(0), "AccessControl: new admin is the zero address");
        address oldAdmin = _admin;
        _admin = newAdmin;
        emit AdminChanged(oldAdmin, newAdmin);
    }

    /**
     * @inheritdoc IAccessControl
     */
    function addOperator(address operator) external override onlyAdmin {
        require(operator != address(0), "AccessControl: operator is the zero address");
        roles[operator] = _OPERATOR_ROLE;
        emit OperatorAdded(operator);
    }

    /**
     * @inheritdoc IAccessControl
     */
    function removeOperator(address operator) external override onlyAdmin {
        delete roles[operator];
        emit OperatorRemoved(operator);
    }

    /**
     * @inheritdoc IAccessControl
     */
    function getAdmin() external view override returns (address admin) {
        admin = _admin;
    }

    /**
     * @inheritdoc IAccessControl
     */
    function isOperator(address operator) external view override returns (bool isOpr) {
        isOpr = roles[operator] == _OPERATOR_ROLE;
    }

    /**
     * @notice Initialize the admin address
     * @param admin_ The address of the admin
     */
    function _initializeAdmin(address admin_) internal {
        require(_admin == address(0), "AccessControl: admin already initialized");
        require(admin_ != address(0), "AccessControl: admin is the zero address");
        _admin = admin_;
    }
}

contracts/manager/access/IAccessControl.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title IAccessControl
 * @author MetaLend
 * @notice Interface for access control mechanisms
 */
interface IAccessControl {
    /**
     * @notice Emitted when admin is changed
     * @param oldAdmin Previous admin address
     * @param newAdmin New admin address
     */
    event AdminChanged(address indexed oldAdmin, address indexed newAdmin);

    /**
     * @notice Emitted when operator is added
     * @param operator Operator address
     */
    event OperatorAdded(address indexed operator);

    /**
     * @notice Emitted when operator is removed
     * @param operator Operator address
     */
    event OperatorRemoved(address indexed operator);

    /// @notice Thrown when caller is not authorized
    error Unauthorized();

    /**
     * @notice Set admin address
     * @param newAdmin New admin address
     */
    function setAdmin(address newAdmin) external;

    /**
     * @notice Add operator
     * @param operator Operator address
     */
    function addOperator(address operator) external;

    /**
     * @notice Remove operator
     * @param operator Operator address
     */
    function removeOperator(address operator) external;

    /**
     * @notice Get the admin address
     * @return admin The admin address
     */
    function getAdmin() external view returns (address admin);

    /**
     * @notice Check if the address is an operator
     * @param operator Operator address
     * @return isOpr True if the address is an operator
     */
    function isOperator(address operator) external view returns (bool isOpr);
}

contracts/manager/args/EIP3009Args.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title EIP3009Args
 * @author MetaLend
 * @notice This struct is used to pass arguments for EIP-3009 authorization.
 */
struct EIP3009Args {
    /// @notice The amount of tokens to transfer.
    uint256 value;
    /// @notice After which timestamp the authorization is valid.
    uint256 validAfter;
    /// @notice Before which timestamp the authorization is valid.
    uint256 validBefore;
    /// @notice Unique nonce for the authorization.
    bytes32 nonce;
    /// @notice The signature of the authorization.
    bytes signature;
}

contracts/manager/args/RebalancingArgs.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {PoolIdentifier} from "../pool/PoolIdentifier.sol";

/**
 * @title RebalancingArgs
 * @author MetaLend
 * @notice This struct is used to pass arguments related to a pool and its pool (vault) contract.
 * @dev It is used in rebalancing operations to specify the pool and pool contract.
 *  The `poolContract` is the address of the pool (vault) contract associated with the pool to interact with.
 *  This struct is typically used in conjunction with rebalancing operations to ensure that
 *  the correct pool and its associated contract are targeted for the operation.
 */
struct RebalancingArgs {
    /// @notice The identifier of the pool
    PoolIdentifier pool;
    /// @notice The address of the pool (vault) contract associated with the pool.
    address poolContract;
}

contracts/manager/args/RebalancingConfigArgs.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {PoolIdentifier} from "../pool/PoolIdentifier.sol";

/**
 * @title RebalancingConfigArgs
 * @author MetaLend
 * @notice This struct is used to pass configurations related to rebalancing operations.
 * @dev Use this for validating rebalancing operations by specifying approved pools, pool contracts, and destination domains.
 *  The `approvedPools` is an array of `PoolIdentifier` that represents the pools that are approved for the operation.
 *  The `approvedPoolContracts` is an array of addresses representing the pool (vault) contracts that are approved for the operation.
 *  The `approvedDestinationDomains` is an array of `uint32` representing the domains that are approved for the operation.
 *  The `fundingCap` is a `uint256` that represents maximum configured spendable cap in USDC based on aTokens (AAVE)
 *  in user's wallet on Linea domain (11). This is a special usecase where funds are redirected to Linea domain (11) to top up the
 *  wallet for spending with a MetaMask card. In this case the funds leave the rebalancer and are transferred to the owner.
 *  This signature is created by signing the concatenated bytes of the approved pools, pool contracts, destination domains and `fundingCap`.
 *  This struct is typically used in conjunction with rebalancing operations to ensure that the operation
 *  is valid and authorized for the specified pool, pool contract, destination domain and funding cap.
 *  The length of `approvedPools`, `approvedPoolContracts`, and `approvedDestinationDomains` must match.
 *  Each entry by index in `approvedPools`, `approvedPoolContracts`, and `approvedDestinationDomains`
 *  corresponds to the approved pool, pool contract, and destination domain respectively.
 *  Additionally, `rebalancingManager` specifies the address of the rebalancing manager contract
 *  that is authorized to operate with these configurations.
 */
struct RebalancingConfigArgs {
    /// @notice The address of the rebalancing manager contract
    address rebalancingManager;
    /// @notice The list of approved pools for an operation
    PoolIdentifier[] approvedPools;
    /// @notice The list of all approved pool (vault) contracts for an operation.
    address[] approvedPoolContracts;
    /// @notice The list of all approved destination domains for an operation.
    /// @dev Even for same domain operations, this must be defined to ensure the signature is valid.
    uint32[] approvedDestinationDomains;
    /// @notice The maximum configured spendable cap in USDC based on aTokens (AAVE) in user's wallet on Linea domain (11).
    uint256 fundingCap;
    /// @notice The signature for the approved pools, pool contracts, and destination domains.
    /// @dev Created by signing the concatenated bytes of the approved pools, pool contracts, and destination domains.
    bytes signature;
}

contracts/manager/operation/Operation.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title Operation
 * @author MetaLend
 * @notice Enum representing operations.
 * @dev This enum is used to identify different supported operations in the system.
 */
enum Operation {
    DEPOSIT,
    WITHDRAW,
    REBALANCE_THIS_DOMAIN,
    REBALANCE_SRC_DOMAIN,
    REBALANCE_DST_DOMAIN,
    FUND_OWNER
}

contracts/manager/pool/PoolIdentifier.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title PoolIdentifier
 * @author MetaLend
 * @notice Enum representing different pool identifiers.
 * @dev This enum is used to identify different supported pools in the system.
 *  New entries must only be appended, the numeric values are part of user signed configs and stored pool keys.
 */
enum PoolIdentifier {
    AAVE_POOL,
    MORPHO_POOL,
    EULER_POOL,
    AAVE_V4_VAULT_POOL // Aave V4 TokenizationSpoke, the ERC-4626 vault supplying a single asset directly to an Aave V4 Hub.
}

contracts/manager/pool/PoolToken.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {PoolIdentifier} from "./PoolIdentifier.sol";

/**
 * @title PoolToken
 * @author MetaLend
 * @notice Struct representing a token in a specific pool.
 * @dev This struct is used to associate a token with its corresponding pool identifier.
 *  Used while mapping pool contracts to their tokens.
 */
struct PoolToken {
    /// @notice The identifier of the pool this token belongs to.
    PoolIdentifier pool;
    /// @notice The address of the underlying token of this pool.
    address token;
}

contracts/rebalancer/IRebalancer.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {RebalancingArgs} from "../manager/args/RebalancingArgs.sol";
import {PoolIdentifier} from "../manager/pool/PoolIdentifier.sol";

/**
 * @title IRebalancer
 * @author MetaLend
 * @notice This interface defines the functions for the Rebalancer contract.
 */
interface IRebalancer {
    /**
     * @notice Emitted when the Rebalancer contract pays the rebalance fee.
     * @param token    The address of the token used to pay the rebalance fee.
     * @param owner    The address of the owner who pays the rebalance fee.
     * @param amount   The amount of tokens paid as the rebalance fee.
     */
    event PayRebalanceFee(address indexed token, address indexed owner, uint256 amount);

    /**
     * @notice Emitted when the Rebalancer contract funds the owner with tokens.
     * @param owner    The address of the owner who receives the tokens.
     * @param token    The address of the token transferred to the owner.
     * @param amount   The amount of tokens transferred to the owner.
     */
    event FundOwner(address indexed owner, address indexed token, uint256 amount);

    /**
     * @notice Emitted when deposit to the pool fails and the Rebalancer contract withdraws tokens to the owner.
     * @param token    The address of the token that failed to deposit.
     * @param amount   The amount of tokens that failed to deposit.
     */
    event OnDepositFailureWithdraw(address indexed token, uint256 amount);

    /// @notice Thrown when caller is not authorized
    error Unauthorized();

    /// @notice Thrown if there is not enough tokens to cover the gas transaction fee
    error InsufficientAmountForGasTransactionFee();

    /// @notice Thrown if there is not enough allowance for transferring tokens
    error ERC20InsufficientAllowance(address token);

    /// @notice Thrown if the funding cannot be completed
    error FundingUnavailable();

    /**
     * @notice Approves the pool and deposits the specified amount of tokens.
     * @dev This function is called by the RebalancingManager contract.
     * @param destinationDomain   The domain to which the tokens will be bridged. For same domain, use MAX_UINT32.
     * @param pool                The identifier of the pool to deposit into.
     * @param poolContract        The address of the pool contract to approve and deposit into.
     * @param token               The address of the token to deposit.
     * @param amount              The amount of tokens to deposit.
     * @param validAfter          The timestamp after which the approval is valid.
     * @param validBefore         The timestamp before which the approval is valid.
     * @param nonce               The nonce for the approval.
     * @param v                   v of approval signature
     * @param r                   r of approval signature
     * @param s                   s of approval signature
     */
    function approveAndDeposit(
        uint32 destinationDomain,
        PoolIdentifier pool,
        address poolContract,
        address token,
        uint256 amount,
        uint256 validAfter,
        uint256 validBefore,
        bytes32 nonce,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @notice Approves the pool and deposits the specified amount of tokens.
     * @dev This function is called by the RebalancingManager contract.
     *  This rebalancer must be pre-approved to spend the tokens.
     * @param destinationDomain   The domain to which the tokens will be bridged. For same domain, use MAX_UINT32.
     * @param pool                The identifier of the pool to deposit into.
     * @param poolContract        The address of the pool contract to approve and deposit into.
     * @param token               The address of the token to deposit.
     * @return amount             The amount of tokens deposited.
     */
    function approveAndDeposit(
        uint32 destinationDomain,
        PoolIdentifier pool,
        address poolContract,
        address token
    ) external returns (uint256 amount);

    /**
     * @notice Receives USDC tokens from bridge, approves the pool contract, and deposits the tokens.
     * @dev This function is called by the RebalancingManager contract.
     * @param pool          The identifier of the pool to deposit into.
     * @param poolContract  The address of the pool contract to approve and deposit into.
     * @param message       The message emitted by MessageSent event during depositForBurn.
     * @param attestation   The attestation retrieved from the CCTP API.
     */
    function receiveUsdcApproveAndDeposit(
        PoolIdentifier pool,
        address poolContract,
        bytes calldata message,
        bytes calldata attestation
    ) external;

    /**
     * @notice Withdraws USDC from pool and deposits it for burning on the specified destination domain.
     * @dev This function is called by the RebalancingManager contract.
     * @param amount              The amount of USDC to withdraw and deposit for burning.
     * @param pool                The identifier of the pool to withdraw from.
     * @param poolContract        The address of the pool contract to withdraw from.
     * @param destinationDomain   The domain to which the USDC will be bridged.
     */
    function withdrawAndDepositForBurnUsdc(uint256 amount, PoolIdentifier pool, address poolContract, uint32 destinationDomain) external;

    /**
     * @notice Withdraws tokens from the source pool and redeposits them into the destination pool on the same domain.
     * @dev This function is called by the RebalancingManager contract.
     * @param token              The address of the token to withdraw and deposit.
     * @param srcPool            The identifier of the source pool to withdraw from.
     * @param srcPoolContract    The address of the source pool contract to withdraw from.
     * @param dstPool            The identifier of the destination pool to deposit into.
     * @param dstPoolContract    The address of the destination pool contract to deposit into.
     */
    function withdrawAndRedeposit(
        address token,
        PoolIdentifier srcPool,
        address srcPoolContract,
        PoolIdentifier dstPool,
        address dstPoolContract
    ) external;

    /**
     * @notice Funds the owner with aTokens (AAVE).
     * @dev This function is called by the RebalancingManager contract.
     * @param fundingCap The maximum configured spendable cap in USDC based on aTokens (AAVE) in user's wallet on Linea domain (11).
     */
    function fundOwnerWithUsdcAaveToken(uint256 fundingCap) external;

    /**
     * @notice Withdraws the specified amount of tokens from pool and transfers them to the owner.
     * @dev This function is called by the RebalancingManager contract.
     *  If amount is MAX_UINT256, it withdraws all available tokens.
     * @param token          The address of the token to withdraw.
     * @param pool           The identifier of the pool to withdraw from.
     * @param poolContract   The address of the pool contract to withdraw from.
     * @param amount         The amount of tokens to withdraw.
     * @param payFee         Whether to pay the gas transaction fee. This depends if the tx is called on behalf of the owner or not.
     */
    function withdrawFromPoolToOwner(address token, PoolIdentifier pool, address poolContract, uint256 amount, bool payFee) external;

    /**
     * @notice Withdraws all tokens from the specified pools and transfers the whole token balance of this contract to the owner.
     * @dev This function is called by the RebalancingManager contract. No fee is paid.
     *  Pools without a position are skipped. Tokens already held by this contract are transferred to the owner as well.
     * @param token             The address of the token to withdraw.
     * @param rebalancingArgs   The pools to withdraw from. See `RebalancingArgs` struct for details.
     * @return amount           The amount of tokens transferred to the owner.
     */
    function withdrawAllToOwner(address token, RebalancingArgs[] calldata rebalancingArgs) external returns (uint256 amount);

    /**
     * @notice Claims rewards from Morpho vaults.
     * @dev This function is called by the RebalancingManager contract.
     * @param rewardDistributor   The address of the reward distributor contract.
     * @param rewardToken         The address of the reward token contract.
     * @param claimable           The overall claimable amount of token rewards.
     * @param proof               The Merkle proof array that verifies the claim's validity.
     */
    function claimRewardsMorpho(address rewardDistributor, address rewardToken, uint256 claimable, bytes32[] calldata proof) external;

    /**
     * @notice Claims rewards. Rewards are from Morpho, Merkl, and any other similar reward distributor.
     * @dev This function is called by the RebalancingManager contract. The rewardToken array must be unique addresses.
     * @param rewardDistributor   The address of the reward distributor contract.
     * @param rewardToken         The addresses of the reward token contracts.
     * @param claimable           The overall claimable amounts of token rewards.
     * @param proof               The Merkle proof arrays that verify the claims' validity.
     */
    function claimRewards(
        address rewardDistributor,
        address[] calldata rewardToken,
        uint256[] calldata claimable,
        bytes32[][] calldata proof
    ) external;

    /**
     * @notice Claims rewards from Aave lending pool.
     * @dev This function is called by the RebalancingManager contract.
     * @param rewardsController   The address of the Aave rewards controller contract.
     * @param assets              The list of asset addresses to claim rewards for.
     */
    function claimRewardsAave(address rewardsController, address[] calldata assets) external;

    /**
     * @notice Releases all vested rewards to the owner.
     * @dev This function is called by the RebalancingManager contract.
     * @param tokenVesting The address of the token vesting contract.
     */
    function claimRewardsRelease(address tokenVesting) external;

    /**
     * @notice Collects service fees for the specified token.
     * @dev This function is called by the RebalancingManager contract.
     * @param token             The address of the token for which the fees are collected.
     * @param rebalancingArgs   The rebalancing arguments for the fee collection. See `RebalancingArgs` struct for details.
     */
    function collectFee(address token, RebalancingArgs[] calldata rebalancingArgs) external;

    /**
     * @notice Returns the address of the owner of the Rebalancer contract.
     * @return owner The address of the owner.
     */
    function getOwner() external view returns (address owner);

    /**
     * @notice Returns the timestamp of the last fee collection for the specified token.
     * @param token        The address of the token.
     * @return timestamp   The timestamp of the last fee collection.
     */
    function getFeeCollectionTimestampForToken(address token) external view returns (uint256 timestamp);
}

contracts/rebalancer/RebalancerCore.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/**
 * @title RebalancerCore
 * @author MetaLend
 * @notice Abstract contract that provides default storage layout for proxy and implementation contract
 */
abstract contract RebalancerCore {
    /// @notice Manager contract providing rebalancing functionality and access control and implementation
    address internal _rebalancingManager;

    /// @notice Address of the owner of this rebalancer
    address internal _owner;

    /**
     * @notice Emitted when the rebalancer is initialized
     * @param rebalancer   Address of this rebalancer
     * @param manager      Address of the rebalancing manager
     * @param owner        Address of the owner of this rebalancer
     */
    event RebalancerInitialized(address indexed rebalancer, address indexed manager, address indexed owner);
}

contracts/rebalancer/RebalancerProxy.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {Proxy} from "@openzeppelin/contracts/proxy/Proxy.sol";
import {IRebalancingManagerCore} from "../manager/IRebalancingManagerCore.sol";
import {RebalancerCore} from "./RebalancerCore.sol";

/**
 * @title RebalancerProxy
 * @author MetaLend
 * @notice Proxy contract for the rebalancer
 * @dev This contract is created to be used as a proxy for the rebalancer implementation managed by the rebalancing manager
 */
contract RebalancerProxy is RebalancerCore, Proxy {
    /**
     * @notice Constructor for the RebalancerProxy contract
     * @param manager_   The address of the rebalancing manager
     * @param owner_     The address of the owner of the rebalancer
     */
    constructor(address manager_, address owner_) {
        _rebalancingManager = manager_;
        _owner = owner_;
        emit RebalancerInitialized(address(this), _rebalancingManager, _owner);
    }

    /**
     * @notice Returns the address of the implementation contract
     * @dev This is used by the proxy `_fallback` function to delegate calls to the implementation contract
     */
    function _implementation() internal view override returns (address implementation) {
        return IRebalancingManagerCore(_rebalancingManager).getRebalancerImplementation();
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "none",
    "useLiteralContent": true
  },
  "libraries": {},
  "optimizer": {
    "runs": 999999,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.