Factory

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/Factory.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/Create2.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Vault.sol";
import "./PrivateVault.sol";

/**
 * @title Factory
 * @dev Factory for deploying deterministic one-time Vault contracts using CREATE2
 * @notice Creates vaults for automatic token swaps via 0x aggregator
 */
contract Factory is Ownable(msg.sender) {
    event VaultCreated(
        address indexed vault,
        address indexed creator,
        address tokenIn,
        address tokenOut,
        uint256 expectedAmount,
        address destination,
        uint256 deadline,
        uint256 minOut
    );

    event PrivateVaultCreated(
        address indexed vault,
        address indexed creator,
        address indexed privacyPool,
        address tokenIn,
        address tokenOut,
        uint256 expectedAmount,
        uint256 minOut
    );

    /**
     * @dev Create a new deterministic vault
     * @param tokenIn The input token address (address(0) for ETH)
     * @param tokenOut The output token address
     * @param expectedAmount The expected amount of tokenIn to be deposited
     * @param destination The address to receive swapped tokens
     * @param deadline The deadline for the swap execution
     * @param minOut The minimum amount of tokenOut to receive
     * @return vault The address of the created vault
     */
    function createVault(
        address tokenIn,
        address tokenOut,
        uint256 expectedAmount,
        address destination,
        uint256 deadline,
        uint256 minOut
    ) external returns (address vault) {
        require(tokenIn != address(0) || tokenOut != address(0), "Invalid tokens");
        require(expectedAmount > 0, "Invalid amount");
        require(destination != address(0), "Invalid destination");
        require(deadline > block.timestamp, "Invalid deadline");

        // Create deterministic salt for CREATE2
        bytes32 salt = keccak256(
            abi.encodePacked(
                msg.sender,
                tokenIn,
                tokenOut,
                expectedAmount,
                destination,
                deadline,
                minOut,
                block.chainid,
                block.timestamp
            )
        );

        // Deploy using CREATE2 with constructor arguments
        Vault newVault = new Vault{salt: salt}(
            tokenIn,
            tokenOut,
            expectedAmount,
            destination,
            minOut,
            deadline,
            msg.sender
        );
        vault = address(newVault);

        emit VaultCreated(
            vault,
            msg.sender,
            tokenIn,
            tokenOut,
            expectedAmount,
            destination,
            deadline,
            minOut
        );
    }

    /**
     * @dev Create a new private vault for privacy-enhanced swaps
     * @param tokenIn The input token address (address(0) for ETH)
     * @param tokenOut The output token address
     * @param expectedAmount The expected amount of tokenIn to be deposited
     * @param minOut The minimum amount of tokenOut to receive
     * @param privacyPool The privacy pool contract to join
     * @param maxDelay The maximum delay in seconds before execution (1-86400)
     * @return vault The address of the created private vault
     */
    function createPrivateVault(
        address tokenIn,
        address tokenOut,
        uint256 expectedAmount,
        uint256 minOut,
        address privacyPool,
        uint256 maxDelay
    ) external returns (address vault) {
        require(tokenIn != address(0) || tokenOut != address(0), "Invalid tokens");
        require(expectedAmount > 0, "Invalid amount");
        require(privacyPool != address(0), "Invalid privacy pool");
        require(maxDelay >= 3600 && maxDelay <= 86400, "Invalid delay range"); // 1-24 hours

        // Create deterministic salt for CREATE2 (privacy mode)
        bytes32 salt = keccak256(
            abi.encodePacked(
                msg.sender,
                tokenIn,
                tokenOut,
                expectedAmount,
                minOut,
                privacyPool,
                maxDelay,
                block.chainid,
                block.timestamp,
                "PRIVATE" // Distinguish from standard vaults
            )
        );

        // Deploy private vault using CREATE2
        PrivateVault newPrivateVault = new PrivateVault{salt: salt}(
            tokenIn,
            tokenOut,
            expectedAmount,
            minOut,
            privacyPool,
            maxDelay,
            msg.sender
        );
        vault = address(newPrivateVault);

        emit PrivateVaultCreated(
            vault,
            msg.sender,
            privacyPool,
            tokenIn,
            tokenOut,
            expectedAmount,
            minOut
        );
    }

    /**
     * @dev Predict the vault address for given parameters
     * @param tokenIn The input token address
     * @param tokenOut The output token address
     * @param expectedAmount The expected amount of tokenIn
     * @param destination The destination address
     * @param deadline The deadline for swap execution
     * @param minOut The minimum output amount
     * @param creator The creator address
     * @param timestamp The timestamp used for salt generation
     * @return predicted The predicted vault address
     */
    function predictVaultAddress(
        address tokenIn,
        address tokenOut,
        uint256 expectedAmount,
        address destination,
        uint256 deadline,
        uint256 minOut,
        address creator,
        uint256 timestamp
    ) external view returns (address predicted) {
        bytes32 salt = keccak256(
            abi.encodePacked(
                creator,
                tokenIn,
                tokenOut,
                expectedAmount,
                destination,
                deadline,
                minOut,
                block.chainid,
                timestamp
            )
        );

        // Compute the CREATE2 address
        bytes32 bytecodeHash = keccak256(
            abi.encodePacked(
                type(Vault).creationCode,
                abi.encode(
                    tokenIn,
                    tokenOut,
                    expectedAmount,
                    destination,
                    minOut,
                    deadline,
                    creator
                )
            )
        );

        predicted = Create2.computeAddress(salt, bytecodeHash);
    }

    /**
     * @dev Predict the private vault address for given parameters
     * @param tokenIn The input token address
     * @param tokenOut The output token address
     * @param expectedAmount The expected amount of tokenIn
     * @param minOut The minimum output amount
     * @param privacyPool The privacy pool contract address
     * @param maxDelay The maximum delay in seconds
     * @param creator The creator address
     * @param timestamp The timestamp used for salt generation
     * @return predicted The predicted private vault address
     */
    function predictPrivateVaultAddress(
        address tokenIn,
        address tokenOut,
        uint256 expectedAmount,
        uint256 minOut,
        address privacyPool,
        uint256 maxDelay,
        address creator,
        uint256 timestamp
    ) external view returns (address predicted) {
        bytes32 salt = keccak256(
            abi.encodePacked(
                creator,
                tokenIn,
                tokenOut,
                expectedAmount,
                minOut,
                privacyPool,
                maxDelay,
                block.chainid,
                timestamp,
                "PRIVATE" // Distinguish from standard vaults
            )
        );

        // Compute the CREATE2 address for private vault
        bytes32 bytecodeHash = keccak256(
            abi.encodePacked(
                type(PrivateVault).creationCode,
                abi.encode(
                    tokenIn,
                    tokenOut,
                    expectedAmount,
                    minOut,
                    privacyPool,
                    maxDelay,
                    creator
                )
            )
        );

        predicted = Create2.computeAddress(salt, bytecodeHash);
    }

    /**
     * @dev Get the number of vaults created by a specific creator
     * @param creator The creator address
     * @return count The number of vaults created
     */
    function getVaultCount(address creator) external view returns (uint256 count) {
        // This would require storage to track vaults
        // For MVP, this function returns 0
        return 0;
    }
}"
    },
    "lib/openzeppelin-contracts/contracts/utils/Create2.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)

pragma solidity ^0.8.20;

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

/**
 * @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 There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @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 Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        assembly ("memory-safe") {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
            // if no address was created, and returndata is not empty, bubble revert
            if and(iszero(addr), not(iszero(returndatasize()))) {
                let p := mload(0x40)
                returndatacopy(p, 0, returndatasize())
                revert(p, returndatasize())
            }
        }
        if (addr == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @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) {
        assembly ("memory-safe") {
            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 := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/access/Ownable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
"
    },
    "src/Vault.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/**
 * @title Vault
 * @dev One-time vault for executing token swaps
 * @notice Accepts deposits and executes swaps via 0x aggregator
 */
contract Vault is ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Immutable configuration
    address public immutable tokenIn;
    address public immutable tokenOut;
    address public immutable destination;
    uint256 public immutable expectedAmount;
    uint256 public immutable minOut;
    uint256 public immutable deadline;
    address public immutable creator;

    // State
    bool public executed;

    // Events
    event Deposited(address indexed from, uint256 amount);
    event SwapExecuted(
        address indexed executor,
        address indexed swapTarget,
        uint256 amountIn,
        uint256 amountOut
    );

    // Errors
    error AlreadyExecuted();
    error Expired();
    error InsufficientDeposit();
    error InsufficientOutput();
    error Unauthorized();
    error SwapFailed();

    /**
     * @dev Constructor to initialize vault parameters
     * @param _tokenIn The input token address (address(0) for ETH)
     * @param _tokenOut The output token address
     * @param _expectedAmount The expected amount of tokenIn
     * @param _destination The destination address for output tokens
     * @param _minOut The minimum amount of tokenOut to receive
     * @param _deadline The deadline for swap execution
     * @param _creator The creator of the vault
     */
    constructor(
        address _tokenIn,
        address _tokenOut,
        uint256 _expectedAmount,
        address _destination,
        uint256 _minOut,
        uint256 _deadline,
        address _creator
    ) {
        tokenIn = _tokenIn;
        tokenOut = _tokenOut;
        expectedAmount = _expectedAmount;
        destination = _destination;
        minOut = _minOut;
        deadline = _deadline;
        creator = _creator;
    }

    /**
     * @dev Receive function to accept ETH deposits
     */
    receive() external payable {
        if (tokenIn != address(0)) revert Unauthorized(); // Only accept ETH if tokenIn is ETH
        emit Deposited(msg.sender, msg.value);
    }

    /**
     * @dev Deposit ERC20 tokens
     * @param amount The amount of tokens to deposit
     */
    function depositToken(uint256 amount) external {
        require(tokenIn != address(0), "ETH vault");
        require(amount > 0, "Invalid amount");

        emit Deposited(msg.sender, amount);
        IERC20(tokenIn).transferFrom(msg.sender, address(this), amount);
    }

    /**
     * @dev Execute the swap via 0x aggregator
     * @param swapTarget The target contract to call for the swap
     * @param swapData The calldata to pass to the swap target
     * @param minReturn The minimum amount to receive from the swap
     */
    function executeSwap(
        address swapTarget,
        bytes calldata swapData,
        uint256 minReturn
    ) external nonReentrant {
        if (executed) revert AlreadyExecuted();
        if (block.timestamp > deadline) revert Expired();
        if (msg.sender != creator) revert Unauthorized();
        require(swapTarget != address(0), "Invalid target");

        // Check if we have sufficient deposits
        uint256 balance;
        if (tokenIn == address(0)) {
            balance = address(this).balance;
        } else {
            balance = IERC20(tokenIn).balanceOf(address(this));
        }

        if (balance < expectedAmount) revert InsufficientDeposit();

        executed = true;

        // Approve swap target if using ERC20
        if (tokenIn != address(0)) {
            IERC20(tokenIn).forceApprove(swapTarget, balance);
        }

        // Execute the swap
        uint256 initialOutputBalance;
        if (tokenOut == address(0)) {
            initialOutputBalance = address(this).balance;
        } else {
            initialOutputBalance = IERC20(tokenOut).balanceOf(address(this));
        }

        (bool success, ) = swapTarget.call{value: tokenIn == address(0) ? balance : 0}(swapData);
        if (!success) revert SwapFailed();

        uint256 finalOutputBalance;
        if (tokenOut == address(0)) {
            finalOutputBalance = address(this).balance;
        } else {
            finalOutputBalance = IERC20(tokenOut).balanceOf(address(this));
        }

        uint256 amountOut = finalOutputBalance - initialOutputBalance;

        if (amountOut < minReturn && amountOut < minOut) revert InsufficientOutput();

        // Transfer output to destination
        if (tokenOut == address(0)) {
            payable(destination).transfer(amountOut);
        } else {
            IERC20(tokenOut).safeTransfer(destination, amountOut);
        }

        emit SwapExecuted(msg.sender, swapTarget, balance, amountOut);

        // Note: selfdestruct is deprecated but kept for gas efficiency in MVP
        // In production, consider a different cleanup strategy
        selfdestruct(payable(creator));
    }

    /**
     * @dev Emergency withdraw function for creator
     * @param to The address to send funds to
     */
    function emergencyWithdraw(address to) external {
        if (msg.sender != creator) revert Unauthorized();
        if (block.timestamp <= deadline) revert Expired(); // Only after deadline

        if (tokenIn == address(0)) {
            payable(to).transfer(address(this).balance);
        } else {
            IERC20(tokenIn).safeTransfer(to, IERC20(tokenIn).balanceOf(address(this)));
        }
    }

    /**
     * @dev Get the current balance of the vault
     * @return balance The current balance in tokenIn or ETH
     */
    function getBalance() external view returns (uint256 balance) {
        if (tokenIn == address(0)) {
            return address(this).balance;
        } else {
            return IERC20(tokenIn).balanceOf(address(this));
        }
    }

    /**
     * @dev Check if vault can execute swap
     * @return result Whether the vault can execute the swap
     */
    function canExecute() external view returns (bool result) {
        if (executed) return false;
        if (block.timestamp > deadline) return false;

        uint256 balance;
        if (tokenIn == address(0)) {
            balance = address(this).balance;
        } else {
            balance = IERC20(tokenIn).balanceOf(address(this));
        }

        result = balance >= expectedAmount;
    }
}"
    },
    "src/PrivateVault.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./PrivacyPool.sol";

/**
 * @title PrivateVault
 * @dev Privacy-enhanced vault for executing token swaps with pool-based mixing
 * @notice Accepts deposits and joins privacy pools for anonymous swapping
 */
contract PrivateVault is ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Immutable configuration
    address public immutable tokenIn;
    address public immutable tokenOut;
    address public immutable creator;
    uint256 public immutable expectedAmount;
    uint256 public immutable minOut;
    uint256 public immutable maxDelay;
    address public immutable privacyPool;

    // State
    bool public executed;
    bool public joinedPool;
    uint256 public poolEntryTime;
    uint256 public randomExecutionTime;

    // Events
    event Deposited(address indexed from, uint256 amount);
    event PoolJoined(address indexed vault, address indexed pool, uint256 entryTime);
    event SwapExecuted(
        address indexed executor,
        address indexed swapTarget,
        uint256 amountIn,
        uint256 amountOut
    );

    // Errors
    error AlreadyExecuted();
    error AlreadyJoinedPool();
    error NotInPool();
    error PoolJoinFailed();
    error SwapFailed();
    error InsufficientOutput();
    error Unauthorized();
    error NotReadyForExecution();

    /**
     * @dev Constructor to initialize private vault parameters
     * @param _tokenIn The input token address (address(0) for ETH)
     * @param _tokenOut The output token address
     * @param _expectedAmount The expected amount of tokenIn
     * @param _minOut The minimum amount of tokenOut to receive
     * @param _privacyPool The privacy pool contract to join
     * @param _maxDelay Maximum delay before execution (1-24 hours)
     * @param _creator The creator of the vault
     */
    constructor(
        address _tokenIn,
        address _tokenOut,
        uint256 _expectedAmount,
        uint256 _minOut,
        address _privacyPool,
        uint256 _maxDelay,
        address _creator
    ) {
        tokenIn = _tokenIn;
        tokenOut = _tokenOut;
        expectedAmount = _expectedAmount;
        minOut = _minOut;
        privacyPool = _privacyPool;
        maxDelay = _maxDelay;
        creator = _creator;
    }

    /**
     * @dev Receive function to accept ETH deposits
     */
    receive() external payable {
        if (tokenIn != address(0)) revert Unauthorized(); // Only accept ETH if tokenIn is ETH
        if (executed) revert AlreadyExecuted();
        emit Deposited(msg.sender, msg.value);
    }

    /**
     * @dev Deposit ERC20 tokens
     * @param amount The amount of tokens to deposit
     */
    function depositToken(uint256 amount) external {
        require(tokenIn != address(0), "ETH vault");
        require(amount > 0, "Invalid amount");
        if (executed) revert AlreadyExecuted();

        emit Deposited(msg.sender, amount);
        IERC20(tokenIn).transferFrom(msg.sender, address(this), amount);
    }

    /**
     * @dev Join privacy pool for enhanced privacy
     * Must be called by vault creator after deposit is complete
     */
    function joinPrivacyPool() external {
        if (msg.sender != creator) revert Unauthorized();
        if (executed) revert AlreadyExecuted();
        if (joinedPool) revert AlreadyJoinedPool();

        // Check if we have sufficient deposits
        uint256 balance;
        if (tokenIn == address(0)) {
            balance = address(this).balance;
        } else {
            balance = IERC20(tokenIn).balanceOf(address(this));
        }

        require(balance >= expectedAmount, "Insufficient deposit for pool");

        joinedPool = true;
        poolEntryTime = block.timestamp;

        // Generate random execution time within max delay range
        uint256 randomDelay = (uint256(keccak256(abi.encodePacked(
            block.timestamp,
            block.prevrandao,
            address(this)
        ))) % (maxDelay - 3600)) + 3600; // Random delay between 1 hour and maxDelay

        randomExecutionTime = block.timestamp + randomDelay;

        // Approve privacy pool to transfer tokens
        if (tokenIn != address(0)) {
            IERC20(tokenIn).forceApprove(privacyPool, balance);
        }

        // Join the privacy pool
        bool success = PrivacyPool(privacyPool).joinPool{value: tokenIn == address(0) ? balance : 0}(
            payable(address(this)),
            tokenIn,
            balance
        );
        if (!success) revert PoolJoinFailed();

        emit PoolJoined(address(this), privacyPool, poolEntryTime);
    }

    /**
     * @dev Execute the swap via privacy pool (can only be called by privacy pool)
     * @param swapTarget The target contract to call for the swap
     * @param swapData The calldata to pass to the swap target
     * @param minReturn The minimum amount to receive from the swap
     * @param destination The final destination for swapped tokens
     */
    function executePrivateSwap(
        address swapTarget,
        bytes calldata swapData,
        uint256 minReturn,
        address destination
    ) external nonReentrant {
        if (executed) revert AlreadyExecuted();
        if (msg.sender != privacyPool) revert Unauthorized(); // Only privacy pool can execute
        if (!joinedPool) revert NotInPool();
        if (block.timestamp < randomExecutionTime) revert NotReadyForExecution();

        executed = true;

        // Get current balance (should be in this contract from pool)
        uint256 balance;
        if (tokenIn == address(0)) {
            balance = address(this).balance;
        } else {
            balance = IERC20(tokenIn).balanceOf(address(this));
        }

        // Approve swap target if using ERC20
        if (tokenIn != address(0)) {
            IERC20(tokenIn).forceApprove(swapTarget, balance);
        }

        // Execute the swap
        uint256 initialOutputBalance;
        if (tokenOut == address(0)) {
            initialOutputBalance = address(this).balance;
        } else {
            initialOutputBalance = IERC20(tokenOut).balanceOf(address(this));
        }

        (bool success, ) = swapTarget.call{value: tokenIn == address(0) ? balance : 0}(swapData);
        if (!success) revert SwapFailed();

        uint256 finalOutputBalance;
        if (tokenOut == address(0)) {
            finalOutputBalance = address(this).balance;
        } else {
            finalOutputBalance = IERC20(tokenOut).balanceOf(address(this));
        }

        uint256 amountOut = finalOutputBalance - initialOutputBalance;

        if (amountOut < minReturn && amountOut < minOut) revert InsufficientOutput();

        // Transfer output to destination
        if (tokenOut == address(0)) {
            payable(destination).transfer(amountOut);
        } else {
            IERC20(tokenOut).safeTransfer(destination, amountOut);
        }

        emit SwapExecuted(msg.sender, swapTarget, balance, amountOut);

        // Clean up
        selfdestruct(payable(creator));
    }

    /**
     * @dev Get the current balance of the vault
     * @return balance The current balance in tokenIn or ETH
     */
    function getBalance() external view returns (uint256 balance) {
        if (tokenIn == address(0)) {
            return address(this).balance;
        } else {
            return IERC20(tokenIn).balanceOf(address(this));
        }
    }

    /**
     * @dev Check if vault can execute swap
     * @return result Whether the vault can execute the swap
     */
    function canExecute() external view returns (bool result) {
        if (executed) return false;
        if (!joinedPool) return false;
        if (block.timestamp < randomExecutionTime) return false;

        uint256 balance;
        if (tokenIn == address(0)) {
            balance = address(this).balance;
        } else {
            balance = IERC20(tokenIn).balanceOf(address(this));
        }

        result = balance >= expectedAmount;
    }

    /**
     * @dev Get the remaining time until execution
     * @return remaining The remaining seconds until random execution time
     */
    function getTimeUntilExecution() external view returns (uint256 remaining) {
        if (!joinedPool || executed) return 0;
        if (block.timestamp >= randomExecutionTime) return 0;
        return randomExecutionTime - block.timestamp;
    }

    /**
     * @dev Emergency withdraw function for creator (only after delay period)
     * @param to The address to send funds to
     */
    function emergencyWithdraw(address to) external {
        if (msg.sender != creator) revert Unauthorized();
        if (joinedPool && block.timestamp <= poolEntryTime + maxDelay) {
            revert NotReadyForExecution(); // Can't withdraw during privacy period
        }

        if (tokenIn == address(0)) {
            payable(to).transfer(address(this).balance);
        } else {
            IERC20(tokenIn).safeTransfer(to, IERC20(tokenIn).balanceOf(address(this)));
        }
    }
}"
    },
    "lib/openzeppelin-contracts/contracts/utils/Errors.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

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

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/Context.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
    },
    "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "src/PrivacyPool.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title PrivacyPool
 * @dev Pool manager for private vault mixing and batch execution
 * @notice Groups similar swaps together for enhanced privacy
 */
contract PrivacyPool is Ownable(msg.sender), ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Pool configuration
    uint256 public constant MIN_POOL_SIZE = 3; // Minimum vaults to form a pool
    uint256 public constant MAX_POOL_SIZE = 10; // Maximum vaults per pool
    uint256 public constant BATCH_EXECUTION_DELAY = 3600; // 1 hour between batches

    // Pool state
    struct Pool {
        address tokenIn;
        address tokenOut;
        uint256 totalAmount;
        address[] vaults;
        uint256[] amounts;
        bool active;
        uint256 creationTime;
        uint256 lastExecutionTime;
    }

    // Mapping from pool key to pool
    mapping(bytes32 => Pool) public pools;

    // Array of active pool keys for iteration
    bytes32[] public activePools;

    // Events
    event PoolCreated(bytes32 indexed poolKey, address indexed tokenIn, address indexed tokenOut);
    event VaultJoinedPool(bytes32 indexed poolKey, address indexed vault, uint256 amount);
    event BatchExecuted(bytes32 indexed poolKey, uint256 vaultCount, uint256 totalAmount);
    event VaultExecuted(bytes32 indexed poolKey, address indexed vault, uint256 amountIn, uint256 amountOut);

    // Errors
    error InvalidPoolParameters();
    error PoolNotFound();
    error PoolInactive();
    error InsufficientPoolSize();
    error UnauthorizedPool();
    error SwapExecutionFailed();
    error InvalidVault();

    /**
     * @dev Create pool key for grouping similar swaps
     * @param tokenIn Input token address
     * @param tokenOut Output token address
     * @return poolKey Unique key for the pool
     */
    function createPoolKey(address tokenIn, address tokenOut) public pure returns (bytes32 poolKey) {
        return keccak256(abi.encodePacked(tokenIn, tokenOut));
    }

    /**
     * @dev Join privacy pool (called by PrivateVault)
     * @param vault The vault address joining the pool
     * @param tokenIn Input token address
     * @param amount The amount being deposited
     * @return success Whether the join was successful
     */
    function joinPool(
        address payable vault,
        address tokenIn,
        uint256 amount
    ) external payable nonReentrant returns (bool success) {
        // Validate caller is a contract (should be PrivateVault)
        if (vault.code.length == 0) revert InvalidVault();

        bytes32 poolKey = createPoolKey(tokenIn, address(0)); // For now, pool by input token only

        // Create pool if it doesn't exist
        if (!pools[poolKey].active) {
            pools[poolKey] = Pool({
                tokenIn: tokenIn,
                tokenOut: address(0), // Will be set when executing
                totalAmount: 0,
                vaults: new address[](0),
                amounts: new uint256[](0),
                active: true,
                creationTime: block.timestamp,
                lastExecutionTime: 0
            });
            activePools.push(poolKey);
            emit PoolCreated(poolKey, tokenIn, address(0));
        }

        Pool storage pool = pools[poolKey];

        // Check pool size limits
        require(pool.vaults.length < MAX_POOL_SIZE, "Pool at capacity");

        // Handle ETH vs ERC20 transfers
        if (tokenIn == address(0)) {
            require(msg.value == amount, "Incorrect ETH amount");
        } else {
            require(msg.value == 0, "No ETH for ERC20 pool");
            IERC20(tokenIn).safeTransferFrom(vault, address(this), amount);
        }

        // Add vault to pool
        pool.vaults.push(vault);
        pool.amounts.push(amount);
        pool.totalAmount += amount;

        emit VaultJoinedPool(poolKey, vault, amount);

        // Check if pool is ready for execution
        if (pool.vaults.length >= MIN_POOL_SIZE) {
            _scheduleBatchExecution(poolKey);
        }

        return true;
    }

    /**
     * @dev Schedule batch execution for a pool
     * @param poolKey The pool to schedule execution for
     */
    function _scheduleBatchExecution(bytes32 poolKey) internal {
        // This would typically trigger backend monitoring
        // For the contract, we just mark it as ready
        Pool storage pool = pools[poolKey];

        // Ensure enough time has passed since last execution
        require(
            block.timestamp >= pool.lastExecutionTime + BATCH_EXECUTION_DELAY,
            "Too soon for execution"
        );
    }

    /**
     * @dev Execute batch swaps for a pool (called by authorized backend)
     * @param poolKey The pool to execute
     * @param swapTarget The swap aggregator target
     * @param swapData The swap calldata
     * @param destinations Array of output destinations for each vault
     */
    function executeBatch(
        bytes32 poolKey,
        address swapTarget,
        bytes calldata swapData,
        address[] calldata destinations
    ) external onlyOwner nonReentrant {
        Pool storage pool = pools[poolKey];
        if (!pool.active) revert PoolInactive();
        if (pool.vaults.length < MIN_POOL_SIZE) revert InsufficientPoolSize();

        uint256 totalAmount = pool.totalAmount;
        uint256 vaultCount = pool.vaults.length;

        require(destinations.length == vaultCount, "Destinations length mismatch");

        // Execute the main swap
        uint256 initialBalance;
        if (pool.tokenIn == address(0)) {
            initialBalance = address(this).balance;
        } else {
            initialBalance = IERC20(pool.tokenIn).balanceOf(address(this));
        }

        // Approve tokens for swap
        if (pool.tokenIn != address(0)) {
            IERC20(pool.tokenIn).forceApprove(swapTarget, totalAmount);
        }

        // Execute the swap
        (bool success, ) = swapTarget.call{value: pool.tokenIn == address(0) ? totalAmount : 0}(
            swapData
        );
        if (!success) revert SwapExecutionFailed();

        uint256 finalBalance;
        if (pool.tokenIn == address(0)) {
            finalBalance = address(this).balance;
        } else {
            finalBalance = IERC20(pool.tokenOut).balanceOf(address(this));
        }

        uint256 totalOutput = finalBalance - initialBalance;

        // Distribute outputs proportionally to vaults
        for (uint256 i = 0; i < vaultCount; i++) {
            uint256 vaultAmount = pool.amounts[i];
            uint256 vaultOutput = (totalOutput * vaultAmount) / totalAmount;

            // Transfer output to destination
            if (pool.tokenOut == address(0)) {
                payable(destinations[i]).transfer(vaultOutput);
            } else {
                IERC20(pool.tokenOut).safeTransfer(destinations[i], vaultOutput);
            }

            emit VaultExecuted(poolKey, pool.vaults[i], vaultAmount, vaultOutput);
        }

        // Update pool state
        pool.active = false;
        pool.lastExecutionTime = block.timestamp;

        emit BatchExecuted(poolKey, vaultCount, totalAmount);

        // Remove from active pools
        _removeActivePool(poolKey);
    }

    /**
     * @dev Remove pool from active pools array
     * @param poolKey The pool key to remove
     */
    function _removeActivePool(bytes32 poolKey) internal {
        for (uint256 i = 0; i < activePools.length; i++) {
            if (activePools[i] == poolKey) {
                activePools[i] = activePools[activePools.length - 1];
                activePools.pop();
                break;
            }
        }
    }

    /**
     * @dev Get pool information
     * @param poolKey The pool key to query
     * @return tokenIn Input token address
     * @return tokenOut Output token address
     * @return totalAmount Total amount in pool
     * @return vaultCount Number of vaults in pool
     * @return active Whether pool is active
     * @return creationTime Pool creation timestamp
     */
    function getPoolInfo(bytes32 poolKey) external view returns (
        address tokenIn,
        address tokenOut,
        uint256 totalAmount,
        uint256 vaultCount,
        bool active,
        uint256 creationTime
    ) {
        Pool storage pool = pools[poolKey];
        return (
            pool.tokenIn,
            pool.tokenOut,
            pool.totalAmount,
            pool.vaults.length,
            pool.active,
            pool.creationTime
        );
    }

    /**
     * @dev Get all vaults in a pool
     * @param poolKey The pool key to query
     * @return vaults Array of vault addresses
     * @return amounts Array of corresponding amounts
     */
    function getPoolVaults(bytes32 poolKey) external view returns (
        address[] memory vaults,
        uint256[] memory amounts
    ) {
        Pool storage pool = pools[poolKey];
        return (pool.vaults, pool.amounts);
    }

    /**
     * @dev Check if a pool is ready for execution
     * @param poolKey The pool key to check
     * @return ready Whether the pool has enough vaults for execution
     */
    function isPoolReady(bytes32 poolKey) external view returns (bool ready) {
        Pool storage pool = pools[poolKey];
        return pool.active && pool.vaults.length >= MIN_POOL_SIZE;
    }

    /**
     * @dev Emergency function to pause all pools (owner only)
     */
    function emergencyPause() external onlyOwner {
        for (uint256 i = 0; i < activePools.length; i++) {
            pools[activePools[i]].active = false;
        }
        activePools = new bytes32[](0);
    }

    /**
     * @dev Get the number of active pools
     * @return count Number of active pools
     */
    function getActivePoolCount() external view returns (uint256 count) {
        return activePools.length;
    }
}"
    },
    "lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` 

Tags:
ERC20, ERC165, Multisig, Swap, Upgradeable, Multi-Signature, Factory|addr:0x7c494482be815deac3a728d4245b3948d848dc7f|verified:true|block:23660362|tx:0xb36bf59740146dd5077de07fc4f04cb23fc126c351a392079b7c43a4196197fa|first_check:1761477979

Submitted on: 2025-10-26 12:26:20

Comments

Log in to comment.

No comments yet.