// File: contracts/twault/balancer-core-v2/lib/openzeppelin/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @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);
}

// File: contracts/twault/interfaces/ICronV1Pool.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

pragma experimental ABIEncoderV2;

import { ICronV1FactoryOwnerActions } from "./pool/ICronV1FactoryOwnerActions.sol";
import { ICronV1PoolAdminActions } from "./pool/ICronV1PoolAdminActions.sol";
import { ICronV1PoolArbitrageurActions } from "./pool/ICronV1PoolArbitrageurActions.sol";
import { ICronV1PoolEnums } from "./pool/ICronV1PoolEnums.sol";
import { ICronV1PoolEvents } from "./pool/ICronV1PoolEvents.sol";
import { ICronV1PoolHelpers } from "./pool/ICronV1PoolHelpers.sol";
import { IERC20 } from "../balancer-core-v2/lib/openzeppelin/IERC20.sol";

interface ICronV1Pool is
  ICronV1FactoryOwnerActions,
  ICronV1PoolAdminActions,
  ICronV1PoolArbitrageurActions,
  ICronV1PoolEnums,
  ICronV1PoolEvents,
  ICronV1PoolHelpers,
  IERC20
{}

// File: contracts/twault/interfaces/ICronV1PoolFactory.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.7.6;

import { ICronV1Pool } from "../interfaces/ICronV1Pool.sol";

interface ICronV1PoolFactory {
  /// @notice This event tracks pool creations from this factory
  /// @param pool the address of the pool
  /// @param token0 The token 0 in this pool
  /// @param token1 The token 1 in this pool
  /// @param poolType The poolType set for this pool
  event CronV1PoolCreated(
    address indexed pool,
    address indexed token0,
    address indexed token1,
    ICronV1Pool.PoolType poolType
  );

  /// @notice This event tracks pool being set from this factory
  /// @param pool the address of the pool
  /// @param token0 The token 0 in this pool
  /// @param token1 The token 1 in this pool
  /// @param poolType The poolType set for this pool
  event CronV1PoolSet(
    address indexed pool,
    address indexed token0,
    address indexed token1,
    ICronV1Pool.PoolType poolType
  );

  /// @notice This event tracks pool deletions from this factory
  /// @param pool the address of the pool
  /// @param token0 The token 0 in this pool
  /// @param token1 The token 1 in this pool
  /// @param poolType The poolType set for this pool
  event CronV1PoolRemoved(
    address indexed pool,
    address indexed token0,
    address indexed token1,
    ICronV1Pool.PoolType poolType
  );

  /// @notice This event tracks pool creations from this factory
  /// @param oldAdmin the address of the previous admin
  /// @param newAdmin the address of the new admin
  event OwnerChanged(address indexed oldAdmin, address indexed newAdmin);

  // Functions
  function create(
    address _token0,
    address _token1,
    string memory _name,
    string memory _symbol,
    uint256 _poolType
  ) external returns (address);

  function set(
    address _token0,
    address _token1,
    uint256 _poolType,
    address _pool
  ) external;

  function remove(
    address _token0,
    address _token1,
    uint256 _poolType
  ) external;

  function transferOwnership(
    address _newOwner,
    bool _direct,
    bool _renounce
  ) external;

  function claimOwnership() external;

  function owner() external view returns (address);

  function pendingOwner() external view returns (address);

  function getPool(
    address _token0,
    address _token1,
    uint256 _poolType
  ) external view returns (address pool);
}

// File: contracts/twault/interfaces/ICronV1Relayer.sol



// SPDX-License-Identifier: BUSL-1.1

// (c) Copyright 2023, Bad Pumpkin Inc. All Rights Reserved
//

pragma solidity ^0.7.6;
pragma experimental ABIEncoderV2;

import { IVault } from "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import { Order } from "../interfaces/Structs.sol";

/// @title ICronV1Relayer
/// @notice Provides a simplified interface to Cron-Finance Time Weighted Average Market Maker (TWAMM) pools impelemnted
///         in the Balancer Vault, performing additional safety and usability checks along the way.
///
///         IMPORTANT: pool addresses and ids for all calls are determined by the Cron-Finance TWAMM Factory contract,
///                    preventing access to other types of pools in the Balancer Vault for additional safety.
///
interface ICronV1Relayer {
  /// @notice Performs a short-term (atomic) swap of the specified amount of token in to token out on the Cron- Finance
  ///         Time-Weighted Average Market Maker (TWAMM) pool uniquely identified from the addresses of token in, token
  ///         out, and the pool type.
  ///
  ///         The slippage specified in basis points is used to determine how much token out can be lost relative
  ///         to a trade occuring at the current reserve ratio. If the amount of token out is more than the slippage
  ///         percent different than the ideal amount calculated by the current reserve ratio, the trade reverts.
  ///
  ///         A recipient can be specified if the proceeds of the trade are to be directed to an account different
  ///         from the calling account, msg.sender.
  ///
  ///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
  ///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
  ///                    this contract's address.
  ///
  ///         Checks performed on behalf of a user include:
  ///           - Pool specified by token in and out addresses and pool type exists.
  ///           - Pool has been funded and contains minimum liquidity amounts.
  ///           - Swap amount specified is greater than zero and available in the calling account (msg.sender).
  ///           - Trade results in amount of token out within specified slippage percent of the ideal amount
  ///             calculated from the ratio of the pool's virtual reserves.
  ///
  ///         Checks NOT performed for a user include:
  ///           - Validity / sanity of the recipient address.
  ///
  /// @param _tokenIn the address of the token being sold to the pool by the calling account.
  /// @param _tokenOut the address of the token being bought from the pool by the calling account.
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @param _amountIn the amount of the token being sold to the pool by the calling account.
  ///                  Min. > 0, Max. <= (2 ** 112) - 1
  /// @param _minTokenOut is the minimum amount of token out expected from the swap; if at least this amount is
  ///                     not provided, then the transaction reverts. This protects against sandwich
  ///                     and other attacks.
  /// @param _recipient an address to send the proceeds of token out from the swap.
  /// @return swapResult the result of the swap call.
  ///
  function swap(
    address _tokenIn,
    address _tokenOut,
    uint256 _poolType,
    uint256 _amountIn,
    uint256 _minTokenOut,
    address _recipient
  ) external returns (bytes memory swapResult);

  /// @notice Performs a join (mint) to the specified Cron-Fi Time-Weighted Average Market Maker (TWAMM) pool.
  ///         The amount of token A and B provided to the pool is given in liquidity A and B, respectively.
  ///         Specifiying the minimum nominal liquidity provided to the pool in min liquidity A and B for tokens
  ///         A and B, respectively, protects against attacks intended to capture user liquidity from price
  ///         manipulation.
  ///
  ///         Tokens A and B referred to herein are an abstraction atop Balancer Vaults notion of the tokens in
  ///         a two-token pool, tokens 0 and 1. Rather than have the user figure out the correct sort order of
  ///         the tokens and specify token 0 and related values correctly, the user need only specify values for
  ///         a given token address and this periphery relayer will correctly figure out the sort order and call
  ///         the vault low level functions appropriately, matching token A and B to token 0 and 1 as needed.
  ///
  ///         A recipient can be specified if the pool tokens (liquitity provider tokens) are to be directed
  ///         to an account different from the calling account, msg.sender.
  ///
  ///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
  ///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
  ///                    this contract's address.
  ///
  ///         WARNING: The first time liquidity is provided to a Cron-Fi TWAMM pool, a minimum amount of
  ///                  liquidity is retained by the pool, with the corresponding pool tokens not provided to
  ///                  the calling account. (See miscellany/Constants.sol::MINIMUM_LIQUIDITY).
  ///
  ///         Checks performed on behalf of a user include:
  ///           - Specified pool exists.
  ///           - Pool has been funded and contains minimum liquidity amounts.
  ///           - Join liquidity amounts specified are greater than zero and available in the calling account
  ///             (msg.sender).
  ///           - The pro-rata liquidity providing algorithm collects at least both minimum specified liquidity
  ///             amounts to protect against price manipulation attacks.
  ///
  ///         Checks NOT performed for a user include:
  ///           - Validity / sanity of the recipient address.
  ///
  /// @param _tokenA the address of one pool asset.
  /// @param _tokenB the address of the other pool asset.
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @param _liquidityA the amount of tokenA to join the pool with.
  ///                    Min. > 0, Max. <= (2 ** 112) - 1
  /// @param _liquidityB the amount of tokenB to join the pool with.
  ///                    Min. > 0, Max. <= (2 ** 112) - 1
  /// @param _minLiquidityA the minimum amount of tokenA calculated pro-rata for joining the pool (protects against
  ///                       price manipulation, should be close to the amount specified for _liquidityA yet able to
  ///                       tolerate typical/expected price movements).
  ///                       Min. > 0, Max. <= _liquidityA
  /// @param _minLiquidityB the minimum amount of tokenB calculated pro-rata for joining the pool (protects against
  ///                       price manipulation, should be close to the amount specified for _liquidityB yet able to
  ///                       tolerate typical/expected price movements).
  ///                       Min. > 0, Max. <= _liquidityB
  /// @param _recipient is the address to send the pool tokens (liquidity provider tokens) to.
  /// @return joinResult the result of the join call.
  ///
  function join(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _liquidityA,
    uint256 _liquidityB,
    uint256 _minLiquidityA,
    uint256 _minLiquidityB,
    address _recipient
  ) external returns (bytes memory joinResult);

  /// @notice Performs an exit (burn) from the specified Cron-Fi Time-Weighted Average Market Maker (TWAMM) pool.
  ///         The amount of pool tokens (liquidity provider tokens) is specified by numLPTokens. Specifiying minimum
  ///         amounts of token A and B to receive from the pool in exchange for pool tokens can be done with min
  ///         amount out A and B, respectively. This protects against price manipulation and other attacks,
  ///         reverting if the minimums aren't received.
  ///
  ///         Tokens A and B referred to herein are an abstraction atop Balancer Vaults notion of the tokens in
  ///         a two-token pool, tokens 0 and 1. Rather than have the user figure out the correct sort order of
  ///         the tokens and specify token 0 and related values correctly, the user need only specify values for
  ///         a given token address and this periphery relayer will correctly figure out the sort order and call
  ///         the vault low level functions appropriately, matching token A and B to token 0 and 1 as needed.
  ///
  ///         A recipient can be specified if the tokens emitted are to be directed to an account different from the
  ///         calling account, msg.sender.
  ///
  ///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
  ///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
  ///                    this contract's address.
  ///
  ///         Checks performed on behalf of a user include:
  ///           - Specified pool exists.
  ///           - Pool token amount specified is greater than zero and available in the calling account
  ///             (msg.sender).
  ///           - The specified minimum amounts of token A and B are received in the exchange for pool tokens or
  ///             the transaction reverts.
  ///
  ///         Checks NOT performed for a user include:
  ///           - Validity / sanity of the recipient address.
  ///
  /// @param _tokenA the address of pool asset tokenA
  /// @param _tokenB the address of pool asset tokenB
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @param _numLPTokens is the number of pool tokens (liquidity provider tokens) to redeem in exchange for tokens A
  ///                     and B from the pool.
  ///                     Min. > 0, Max. <= (2 ** 256) - 1
  /// @param _minAmountOutA is the minimum amount of tokenA to accept from the pool in exchange for pool tokens before
  ///                       reverting the transaction.
  ///                       Min. > 0, Max. <= (2 ** 112) - 1
  /// @param _minAmountOutB is the minimum amount of tokenB to accept from the pool in exchange for pool tokens before
  ///                       reverting the transaction.
  ///                       Min. > 0, Max. <= (2 ** 112) - 1
  /// @param _recipient is the address to send tokens A and B to from the exchanged pool tokens (liquidity provider
  ///                   tokens).
  /// @return exitResult the result of the exit call.
  ///
  function exit(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _numLPTokens,
    uint256 _minAmountOutA,
    uint256 _minAmountOutB,
    address _recipient
  ) external returns (bytes memory exitResult);

  /// @notice Gets a multicall array argument to perform a long-term (non-atomic) swap of the specified amount of token
  ///         in to token out on the Cron-Finance Time-Weighted Average Market Maker (TWAMM) pool uniquely identified
  ///         from the addreses of token in, token out, and the pool type.
  ///
  ///         The intervals specified is the duration over which to perform the long-term swap. An interval is a
  ///         number of blocks, depending on the pool type specified (See miscellany/Constants.sol::{STABLE_OBI,
  ///         LIQUID_OBI, VOLATILE_OBI}). The amount specified is divided by the number of blocks in the duration
  ///         of the trade, known as the sales rate. The sales rate is used to compute the swap when virtual orders are
  ///         executed (usually at block numbers divisible by the block interval, OBI, or at transactions against
  ///         the pool). Any excess amount not divisible by the trade duration is not taken for the trade (i.e. the
  ///         amount in specified is reduced to an amount wholely divisible by the trade duration).
  ///
  ///         A delegate address may be specified. The delegate address has the ability to withdraw or cancel the
  ///         long-term swap to the calling account's address at any time. The delegate cannot withdraw or cancel the
  ///         long-term swap to any address but the calling account's address. The delegate address cannot be modified
  ///         during the duration of the trade--the only mitigation is for the calling account to cancel the trade. If
  ///         the delegate is unspecified or the NULL address, the delegate is considered undefined and there is no such
  ///         role for the long-term swap.
  ///
  ///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
  ///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
  ///                    this contract's address.
  ///
  ///         Checks performed on behalf of a user include:
  ///           - Pool specified by token in and out addresses and pool type exists.
  ///           - Pool has been funded and contains minimum liquidity amounts.
  ///           - Swap amount specified is greater than zero and available in the calling account (msg.sender).
  ///           - Intervals specified are greater than zero.
  ///           - Reducing the swap amount specified to the amount wholely divisible by the trade duration to
  ///             prevent losses due to fixed-precision limitations.
  ///
  ///         Checks NOT performed for a user include:
  ///           - Validity of the delegate address.
  ///
  /// @param _tokenIn the address of the token being sold to the pool by the calling account.
  /// @param _tokenOut the address of the token being bought from the pool by the calling account.
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @param _amountIn the amount of the token being sold to the pool by the calling account.
  ///                  Min. > 0, Max. <= (2 ** 112) - 1
  /// @param _intervals is the number of intervals to execute the long-term swap before expiring. An interval can be 75
  ///                   blocks (Stable Pool), 300 blocks (Liquid Pool) or 1200 blocks (Volatile Pool).
  ///                   Min. = 0, Max. = miscellany/Constants.sol::STABLE_MAX_INTERVALS,
  ///                                    miscellany/Constants.sol::LIQUID_MAX_INTERVALS,
  ///                                    miscellany/Constants.sol::VOLATILE_MAX_INTERVALS
  ///                                    (depending on POOL_TYPE).
  /// @param _delegate is an account that is able to withdraw or cancel the long-term swap on behalf of the
  ///                  calling account, as long as the recipient specified for withdraw or cancellation is the
  ///                  original calling account.
  ///                  If the delegate is set to the calling account, then the delegate is set
  ///                  to the null address (i.e. no delegate role granted).
  ///
  /// @return longTermSwapResult the result of the long term swap call.
  /// @return orderId of the long term order if the long term order was successfully issued.
  ///
  function longTermSwap(
    address _tokenIn,
    address _tokenOut,
    uint256 _poolType,
    uint256 _amountIn,
    uint256 _intervals,
    address _delegate
  ) external returns (bytes memory longTermSwapResult, uint256 orderId);

  /// @notice Performs a withdrawal of a long-term (non-atomic) swap, given the order id of the swap.
  ///
  ///         Multiple withdrawals are possible througout the duration of a long-term swap, with a final withdrawal
  ///         possible after the swap has expired.
  ///
  ///         If a delegate has been specified in the long-term swap and is performing the withdrawal, the _recipient
  ///         address must be the original long-term swap owner (calling account, msg.sender) or the withdrawal will
  ///         revert.
  ///
  ///         If the owner (calling account, msg.sender) is performing the withdrawal, the funds may be directed to
  ///         another account, the address of which is specified in the recipient parameter.
  ///
  ///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
  ///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
  ///                    this contract's address.
  ///
  ///         Tokens A and B referred to herein are an abstraction atop Balancer Vaults notion of the tokens in
  ///         a two-token pool, tokens 0 and 1. Rather than have the user figure out the correct sort order of
  ///         the tokens and specify token 0 and related values correctly, the user need only specify values for
  ///         a given token address and this periphery relayer will correctly figure out the sort order and call
  ///         the vault low level functions appropriately, matching token A and B to token 0 and 1 as needed. Since
  ///         this method need not specify any amounts of either asset token, the two assets are only used to correctly
  ///         identify the pool, given the pool type.
  ///
  ///         Checks performed on behalf of a user include:
  ///           - Specified pool exists.
  ///
  ///         Checks NOT performed for a user include:
  ///           - Validity / sanity of the recipient address.
  ///
  /// @param _tokenA the address of pool asset token A
  /// @param _tokenB the address of pool asset token B
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @param _orderId is the id of the long-term swap order being withdrawn.
  ///                 Min. = 0, Max. = (2 ** 256) - 1
  /// @param _recipient is the address of the order owner (original order calling account, msg.sender) if this withdraw
  ///                   transaction is performed by a delegate. The call will revert if an address other than the order
  ///                   owner is specified. If the withdraw transaction is performed by the order owner, then the
  ///                   recipient can be specified as any account address.
  /// @return withdrawResult the result of the withdraw call.
  ///
  function withdraw(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _orderId,
    address _recipient
  ) external returns (bytes memory withdrawResult);

  /// @notice Performs a cancel of a long-term (non-atomic) swap, given the order id of the swap.
  ///
  ///         Cancellation is possible up until the swap order expiry. Already executed portions of the long-term
  ///         swap are remitted along with any remaining unsold tokens.
  ///
  ///         If a delegate has been specified in the long-term swap and is performing the cancellation, the _recipient
  ///         address must be the original long-term swap owner (calling account, msg.sender) or the cancellation will
  ///         revert.
  ///
  ///         If the owner (calling account, msg.sender) is performing the cancellation, the funds may be directed to
  ///         another account, the address of which is specified in the recipient parameter.
  ///
  ///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
  ///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
  ///                    this contract's address.
  ///
  ///         Tokens A and B referred to herein are an abstraction atop Balancer Vaults notion of the tokens in
  ///         a two-token pool, tokens 0 and 1. Rather than have the user figure out the correct sort order of
  ///         the tokens and specify token 0 and related values correctly, the user need only specify values for
  ///         a given token address and this periphery relayer will correctly figure out the sort order and call
  ///         the vault low level functions appropriately, matching token A and B to token 0 and 1 as needed. Since
  ///         this method need not specify any amounts of either asset token, the two assets are only used to correctly
  ///         identify the pool, given the pool type.
  ///
  ///         Checks performed on behalf of a user include:
  ///           - Specified pool exists.
  ///
  ///         Checks NOT performed for a user include:
  ///           - Validity / sanity of the recipient address.
  ///
  /// @param _tokenA the address of pool asset token A
  /// @param _tokenB the address of pool asset token B
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @param _orderId is the id of the long-term swap order being withdrawn.
  ///                 Min. = 0, Max. = (2 ** 256) - 1
  /// @param _recipient is the address of the order owner (original order calling account, msg.sender) if this cancel
  ///                   transaction is performed by a delegate. The call will revert if an address other than the order
  ///                   owner is specified. If the cancel transaction is performed by the order owner, then the
  ///                   recipient can be specified as any account address.
  /// @return cancelResult the result of the cancel call.
  ///
  function cancel(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _orderId,
    address _recipient
  ) external returns (bytes memory cancelResult);

  /// @notice Gets the Cron-Fi pool address, given the pool's asset token addresses and pool type. This method is
  ///         useful for inspecting the pool that methods in this periphery relayer will be operating on by getting the
  ///         target pool address from the provided parameters.
  ///
  ///         Tokens A and B referred to herein are an abstraction atop Balancer Vaults notion of the tokens in
  ///         a two-token pool, tokens 0 and 1. Rather than have the user figure out the correct sort order of
  ///         the tokens and specify token 0 and related values correctly, the user need only specify values for
  ///         a given token address and this periphery relayer will correctly figure out the sort order and call
  ///         the vault low level functions appropriately, matching token A and B to token 0 and 1 as needed. Since
  ///         this method need not specify any amounts of either asset token, the two assets are only used to correctly
  ///         identify the pool, given the pool type.
  ///
  /// @param _tokenA the address of pool asset token A
  /// @param _tokenB the address of pool asset token B
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @return pool the address of the unique Cron-Fi pool for the provided token addresses and pool type. If
  ///              the value returned is the NULL address (0), there is not Cron-Fi pool matching the provided
  ///              function parameters.
  ///
  function getPoolAddress(
    address _tokenA,
    address _tokenB,
    uint256 _poolType
  ) external view returns (address pool);

  /// @notice A convenience for getting the order data for a given order id in a pool specified by the provided token
  ///         addresses and pool type.
  ///
  ///         If the pool cannot be identified or does not exist given the provided parameters, the call
  ///         reverts with a non-existing pool error code.
  ///
  ///         Tokens A and B referred to herein are an abstraction atop Balancer Vaults notion of the tokens in
  ///         a two-token pool, tokens 0 and 1. Rather than have the user figure out the correct sort order of
  ///         the tokens and specify token 0 and related values correctly, the user need only specify values for
  ///         a given token address and this periphery relayer will correctly figure out the sort order and call
  ///         the vault low level functions appropriately, matching token A and B to token 0 and 1 as needed. Since
  ///         this method need not specify any amounts of either asset token, the two assets are only used to correctly
  ///         identify the pool, given the pool type.
  ///
  ///         NOTE: It is more gas efficient to call the method of the same name on the target Cron-Fi pool contract.
  ///               This method is provided as a convenience for users of web interfaces like Etherscan or Gnosis Safe.
  ///
  /// @param _tokenA the address of pool asset token A
  /// @param _tokenB the address of pool asset token B
  /// @param _poolType a number mapping to the PoolType enumeration (see ICronV1PoolEnums.sol::PoolType for the
  ///                  enumeration definition):
  ///                  Stable = 0
  ///                  Liquid = 1
  ///                  Volatile = 2
  ///                  Min. = 0, Max. = 2
  /// @return pool the address of the unique Cron-Fi pool for the provided token addresses and pool type. If
  ///              the value returned is the NULL address (0), there is not Cron-Fi pool matching the provided
  ///              function parameters.
  /// @return order is the data for the specified order id. See ICronV1PoolEnums.sol for details on the Order
  ///               struct. If there the order id specified is invalid or expired and withdrawn, then the order
  ///               struct fields will be zero.
  ///
  function getOrder(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _orderId
  ) external view returns (address pool, Order memory order);

  /// @notice Gets the library address that this periphery relayer delegate calls
  ///         to perform Cron-Fi pool operations on behalf of the calling account.
  /// @return the address of this periphery relayer's library of functions that
  ///         operate directly on the Balancer Vault.
  ///
  function getLibrary() external view returns (address);

  /// @notice Gets the Balancer Vault that this periphery relayer is serving.
  /// @return a Balancer Vault instance.
  ///
  function getVault() external view returns (IVault);
}

// File: contracts/twault/interfaces/Structs.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.7.6;

/// @dev Conventions in the methods, variables and constants are as follows:
///
///      Prefixes:
///
///      - In constants, the prefix "Sn", where 1 <= n <= 4, denotes which slot the constant
///        pertains too. There are four storage slots that are bitpacked. For example,
///        "S2_OFFSET_ORACLE_TIMESTAMP" refers to the offset of the oracle timestamp in bit-
///        packed storage slot 2.
///
///      Suffixes:
///
///      - The suffix of a variable name denotes the type contained within the variable.
///        For instance "uint256 _incrementU96" is a 256-bit unsigned container representing
///        the 96-bit value "_increment".
///        In the case of "uint256 _balancerFeeDU1F18", the 256-bit unsigned container is
///        representing a 19 digit decimal value with 18 fractional digits. In this scenario,
///        the D=Decimal, U=Unsigned, F=Fractional.
///        Finally, "uint128 valueU128F64" is a 128-bit container representing a 128-bit value
///        with 64 fractional bits.
///
///      - The suffix of a function name denotes what slot it is proprietary too as a
///        matter of convention. While unchecked at run-time or by the compiler, the naming
///        convention easily aids in understanding what slot a packed value is stored within.
///        For instance the function "unpackFeeShiftS3" unpacks the fee shift from slot 3. If
///        the value of slot 2 were passed to this method, the unpacked value would be
///        incorrect.

//
// Structs Related to Virtual Orders
////////////////////////////////////////////////////////////////////////////////

/// @notice Virtual Order details for a single user's Long-Term (LT) swap. An LT swap from
///         Token0 to Token1 is described as a user selling Token0 to the pool to buy Token1
///         from the pool.  Vice-versa if the swap is from Token1 to Token0.
/// @member token0To1 Swap direction, true swapping Token0 for Token1. False otherwise.
/// @member salesRate Amount of token sold to the pool per block for LT swap duration.
/// @member scaledProceedsAtSubmissionU128 The normalized proceeds of the pool for the token
///                                        being purchased at the block the order is
///                                        submitted. For example, for an LT swap of Token0
///                                        for Token1, this value would be the normalized
///                                        proceeds of Token1 for the pool. The normalized
///                                        value is also scaled for precision reasons.
///                                        Min. = 0, Max. = (2**128) - 1
/// @member owner The address issuing the LT swap virtual order; exclusively able to cancel or
///               withdraw the order.
/// @member delegate Is an address that is able to withdraw or cancel the LT swap on behalf
///                  of owner account, as long as the recipient specified is the owner
///                  account.
/// @member orderExpiry is the block in which this order expires.
struct Order {
  bool token0To1;
  uint112 salesRate;
  uint128 scaledProceedsAtSubmissionU128;
  address owner;
  address delegate;
  uint256 orderExpiry;
}

/// @notice This struct abstracts two order pools representing pooled Long-Term (LT) swaps in
///         each swap direction along with the current proceeds and a mapping of the sales
///         rate of each token at the end of a block. This allows the grouping of swaps in
///         the two swap directions for gas efficient execution when virutal orders are
///         executed. It is an adaptation of the staking algorithm desribed here:
///         - https://uploads-ssl.webflow.com/5ad71ffeb79acc67c8bcdaba/5ad8d1193a40977462982470_scalable-reward-distribution-paper.pdf
/// @member currentSalesRates stores the current sales rate of both Token0 and Token1 per block
///                           as 112-bit numbers packed into the 256-bit container. Token0
///                           occupies bits 224 downto 113 and Token1 bits 112 downto 1.
/// @member scaledProceeds stores the normalized, scaled, proceeds of each order pool together as
///                        128-bit numbers packed into the 256-bit container. Scaled proceeds0
///                        occupies bits 256 downto 129 and scaled proceeds1 occupies
///                        bits 128 downto 1.
///                        WARNING: Scaled proceeds0 and scaled proceeds1 described above are
///                        not the proceeds of Token0 and Token1 as would be expected, but rather
///                        the proceeds of order pool 0 and order pool 1 respectively. This means
///                        that scaled proceeds0 is actually the amount of Token1 obtained for
///                        users selling Token0 to the pool and vice-versa for proceeds1.
/// @member salesRateEndingPerBlock is a mapping of a block number to the sales rates of Token0
///                                 and Token1 expiring on that block number for each order pool.
///                                 The 112-bit sales rates are stored in a single 256-bit slot
///                                 together for efficiency. The sales rate for Token0 occupies
///                                 bits 224 downto 113 while the sales rate for Token1 occupies
///                                 bits 112 townto 1.
///
struct OrderPools {
  uint256 currentSalesRates;
  uint256 scaledProceeds;
  mapping(uint256 => uint256) salesRatesEndingPerBlock;
}

/// @notice This struct contains the order pool data for virtual orders comprising of sales of
///         Token0 for Token1 and vice-versa over multiple blocks. Each order pool is stored
///         herein, tracking the current sales rates and proceeds along with expiring sales
///         rates.
///         This struct also stores the scaled proceeds at each block, allowing an individual
///         user's proceeds to be calculated for a given interval. Each user's order is stored
///         with a mapping to their order id and the most recently executed virtual order block
///         and next order id are also stored herein.
/// @member orderPools is a struct containing the sale rate and proceeds for each of the two
///                    order pools along with expiring orders sales rates mapped by block.
/// @member scaledProceedsAtBlock is a mapping of a block number to the normalized, scaled,
///                               proceeds of each order pool together as 128-bit numbers packed
///                               into the 256-bit container. Scaled proceeds0 occupies
///                               bits 256 downto 129 and scaled proceeds1 occupies
///                               bits 128 downto 1.
///                               WARNING: Scaled proceeds0 and scaled proceeds1 described above are
///                               not the proceeds of Token0 and Token1 as would be expected, but rather
///                               the proceeds of order pool 0 and order pool 1 respectively. This means
///                               that scaled proceeds0 is actually the amount of Token1 obtained for
///                               users selling Token0 to the pool and vice-versa for proceeds1.
/// @dev The values contained in scaledProceedsAtBlock are always increasing and are expected to
///      overflow. Their difference when measured between two blocks, determines the proceeds in a
///      particular time-interval. A user's sales rate multiplying that amount determines the user's
///      share of the proceeds (scaledProceeds are normalized by the total sales rate and scaled up for
///      maintaining precision). The subtraction of the two points is also expected to underflow.
/// @member orderMap maps a particular order id to information about that order.
/// @member lastVirtualOrderBlock The ethereum block number before the last virtual orders were executed.
/// @member nextOrderId Is the next order id issued when a user places a Long-Term swap virtual order.
///
struct VirtualOrders {
  OrderPools orderPools;
  mapping(uint256 => uint256) scaledProceedsAtBlock;
  mapping(uint256 => Order) orderMap;
  uint256 lastVirtualOrderBlock;
  uint256 nextOrderId;
}

//
// Structs Related to Other Pool Features
////////////////////////////////////////////////////////////////////////////////

/// @notice The cumulative prices of Token0 and Token1 as of the start of the
///         last executed block (the timestamp of which can be fetched using
///         getOracleTimeStamp).
/// @member token0U256F112 The cumulative price of Token0 measured in amount of
///                        Token1 seconds.
/// @member token1U256F112 The cumulative price of Token1 measured in amount of
///                        Token0 seconds.
/// @dev These values have 112 fractional bits and are expected to overflow.
///      Behavior is identical to the price oracle introduced in Uniswap V2 with
///      similar limitations and vulnerabilities.
/// @dev The average price over an interval can be obtained by sampling these
///      values and their measurement times (see getOracleTimeStamp) and
///      computing the difference over the given interval.
struct PriceOracle {
  uint256 token0U256F112;
  uint256 token1U256F112;
}

//
// Structs for Gas Efficiency / Stack Depth Limitations
////////////////////////////////////////////////////////////////////////////////

/// @notice Struct for executing virtual orders across functions efficiently.
/// @member token0ReserveU112 reserves of Token0 in the TWAMM pool.
/// @member token1ReserveU112 reserves of Token1 in the TWAMM pool.
/// @member lpFeeU60 This is the portion of fees to be distributed to Liquidity Providers
///                  (LPs) after Balancer's portion is collected. The portioning is based
///                  on fractions of 10**18 and the value is computed by subtracting
///                  Balancer's portion from 10**18. If Cron-Fi fees are being collected
///                  this value is used to compute the fee share, feeShareU60.
/// @member feeShareU60 If Cron-Fi fees are being collected, this amount represents a
///                     single share of the fees remaining after Balancer's portion. A
///                     single share goes to Cron-Fi and multiples of a single share go
///                     to the Liquidity Providers (LPs) based on the fee shift value,
///                     feeShiftU3.
/// @member feeShiftU3 If Cron-Fi fees are being collected, this represents the amount of
///                    bits shifted to partition fees between Liquidity Providers (LPs)
///                    and Cron-Fi. For example, if this is 1, then 2 shares of fees
///                    collected after Balancer's portion go to the LPs and 1 share goes
///                    to Cron-Fi. If it is 2, then 4 shares go to the LPs and 1 share
///                    goes to Cron-Fi.
/// @member orderPool0ProceedsScaling is the amount to scale proceeds of order pool 0 (Long-
///                                   Term swaps of Token 0 to Token 1) based on the number
///                                   of decimal places in Token 0.
/// @member orderPool0ProceedsScaling is the amount to scale proceeds of order pool 1 (Long-
///                                   Term swaps of Token 1 to Token 0) based on the number
///                                   of decimal places in Token 1.
/// @member token0BalancerFeesU96 Balancer fees collected for Token0-->Token1 swaps.
/// @member token1BalancerFeesU96 Balancer fees collected for Token1-->Token0 swaps.
/// @member token0CronFiFeesU96 Cron-Fi fees collected for Token0-->Token1 Long-Term swaps.
/// @member token1CronFiFeesU96 Cron-Fi fees collected for Token1-->Token0 Long-Term swaps.
/// @member token0OrdersU112 Amount of Token0 sold to the pool in virtual orders.
/// @member token1OrdersU112 Amount of Token1 sold to the pool in virtual orders.
/// @member token0ProceedsU112 Amount of Token0 bought from the pool in virtual orders.
/// @member token1ProceedsU112 Amount of Token1 bought from the pool in virtual orders.
/// @member token0OracleU256F112 The computed increment for the price oracle for Token 0.
/// @member token1OracleU256F112 The computed increment for the price oracle for Token 1.
/// @member oracleTimeStampU32 The oracle time stamp.
///
struct ExecVirtualOrdersMem {
  uint256 token0ReserveU112;
  uint256 token1ReserveU112;
  uint256 lpFeeU60;
  uint256 feeShareU60;
  uint256 feeShiftU3;
  uint256 token0BalancerFeesU96;
  uint256 token1BalancerFeesU96;
  uint256 token0CronFiFeesU96;
  uint256 token1CronFiFeesU96;
  uint256 token0OrdersU112;
  uint256 token1OrdersU112;
  uint256 token0ProceedsU112;
  uint256 token1ProceedsU112;
  uint256 token0OracleU256F112;
  uint256 token1OracleU256F112;
}

/// @notice Struct for executing the virtual order loop efficiently (reduce
///         storage reads/writes). Advantages increase when pool is inactive
///         for longer multiples of the Order Block Interval.
/// @member lastVirtualOrderBlock The ethereum block number before the last virtual orders were
///                               executed.
/// @member scaledProceeds0U128 The normalized scaled proceeds of order pool 0 in Token1. For
///                             example, for an LT swap of Token0 for Token1, this value
///                             would be the normalized proceeds of Token1 for the pool. The
///                             normalized value is also scaled for precision reasons.
///                             Min. = 0, Max. = (2**128) - 1
/// @member scaledProceeds1U128 The normalized scaled proceeds of order pool 1 in Token0.
///                             Min. = 0, Max. = (2**128) - 1
/// @member currentSalesRate0U112 The current sales rate of Token0 per block.
///                               Min. = 0, Max. = (2**112) - 1
/// @member currentSalesRate1U112 The current sales rate of Token1 per block.
///                               Min. = 0, Max. = (2**112) - 1
///
struct LoopMem {
  // Block Numbers:
  uint256 lastVirtualOrderBlock;
  // Order Pool Items:
  uint256 scaledProceeds0U128;
  uint256 scaledProceeds1U128;
  uint256 currentSalesRate0U112;
  uint256 currentSalesRate1U112;
}

// File: contracts/twault/interfaces/pool/ICronV1FactoryOwnerActions.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

interface ICronV1FactoryOwnerActions {
  function setAdminStatus(address _admin, bool _status) external;

  function setFeeAddress(address _feeDestination) external;

  function setFeeShift(uint256 _feeShift) external;

  function setCollectBalancerFees(bool _collectValue) external;
}

// File: contracts/twault/interfaces/pool/ICronV1PoolAdminActions.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

interface ICronV1PoolAdminActions {
  function setPause(bool _pauseValue) external;

  function setParameter(uint256 _paramTypeU, uint256 _value) external;

  function setArbitragePartner(address _arbPartner, address _arbitrageList) external;
}

// File: contracts/twault/interfaces/pool/ICronV1PoolArbitrageurActions.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

interface ICronV1PoolArbitrageurActions {
  function updateArbitrageList() external returns (address);

  function executeVirtualOrdersToBlock(uint256 _maxBlock) external;
}

// File: contracts/twault/interfaces/pool/ICronV1PoolEnums.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

interface ICronV1PoolEnums {
  /// @notice Enumeration for the type of TWAMM pool created; the type determines the default fees and the immutable block
  ///         interval that the pool will operate with for it's lifetime. Each enumeration value is described in more
  ///         detail below (Fee Points = FP):
  ///
  ///           Stable:
  ///
  ///             - Intended for pool tokens that trade frequently; features lower fees and more frequent Long-Term order
  ///               expiries in exchange for higher gas use.
  ///             Short-Term Swap Fee  = 10 FP (0.010%)
  ///             Arbitrageur Swap Fee =  5 FP (0.005%)
  ///             Long-Term Swap Fee   = 30 FP (0.030%)
  ///             Order Block Interval = 75 blocks (~15 minutes)
  ///
  ///           Liquid:
  ///
  ///             - The middle ground setting between tokens that trade frequently and those that trade infrequently with
  ///               low-liquidity. Mid-range fees and order expiry frequency.
  ///             Short-Term Swap Fee  =  50 FP (0.050%)
  ///             Arbitrageur Swap Fee =  25 FP (0.025%)
  ///             Long-Term Swap Fee   = 150 FP (0.150%)
  ///             Order Block Interval = 300 blocks (~1 hour)
  ///
  ///           Volatile:
  ///
  ///             - Intended for pool tokens that trade infrequently with low-liquidity; features higher fees and less
  ///               frequent Long-Term order expiries in exchange for reduced gas use.
  ///             Short-Term Swap Fee  = 100 FP (0.100%)
  ///             Arbitrageur Swap Fee =  50 FP (0.050%)
  ///             Long-Term Swap Fee   = 300 FP (0.300%)
  ///             Order Block Interval = 1200 blocks (~ 4 hours)
  ///
  enum PoolType {
    Stable, // 0
    Liquid, // 1
    Volatile // 2
  }

  /// @notice Enumeration for functionality when joining the pool:
  ///         - Join performs the standard Join/Mint functionality, taking the provided tokens in exchange for
  ///           pool Liquidity Provider (LP) tokens.
  ///         - Reward performs a donation of the provided tokens to the pool with no LP tokens provided in return.
  ///
  enum JoinType {
    Join, // 0
    Reward // 1
  }

  /// @notice Enumeration for functionality when swapping with the pool:
  ///         - RegularSwap performs a standard swap of the specified token for its opposing token using the Constant
  ///           Product Automated Market Maker (CPAMM) formula.
  ///         - LongTermSwap performs a swap of the spcified token for its opposing token over more than one block.
  ///         - PartnerSwap performs a reduced fee RegularSwap with registered arbitrage partner's arbitrageurs.
  ///
  enum SwapType {
    RegularSwap, // 0
    LongTermSwap, // 1
    PartnerSwap // 2
  }

  /// @notice Enumeration for functionality when exiting the pool:
  ///         - Exit performs a standard exit or burn functionality, taking provided LP tokens in exchange for the
  ///           proportional amount of pool tokens.
  ///         - Withdraw performs a Long-Term swap order proceeds withdrawl.
  ///         - Cancel performs a Long-Term swap order cancellation, remitting proceeds and refunding unspent deposits.
  ///         - FeeWithdraw performs a withdraw of Cron-Fi fees to the fee address if enabled.
  ///
  enum ExitType {
    Exit, // 0
    Withdraw, // 1
    Cancel, // 2
    FeeWithdraw // 3
  }

  /// @notice Enumeration for shared parameterization setting function to specify parameter being set:
  ///         - SwapFeeFP is the short term swap fee in Fee Points (FP).
  ///         - PartnerFeeFP is the arbitrage partner swap fee in FP.
  ///         - LongSwapFeeFP is the Long-Term swap fee in FP.
  /// @dev NOTE: Total FP = 100,000. Thus a fee portion is the number of FP out of 100,000.
  ///
  enum ParamType {
    // Slot 1:
    SwapFeeFP, // 0
    PartnerFeeFP, // 1
    LongSwapFeeFP // 2
  }

  /// @notice Enumeration for shared event log for boolean parameter state changes. The event
  ///         BoolParameterChange will contain one of the following enum values to indicate a
  ///         change to the respective one--the pool's paused state or collection of balancer fees.
  ///
  enum BoolParamType {
    Paused, // 0
    CollectBalancerFees // 1
  }
}

// File: contracts/twault/interfaces/pool/ICronV1PoolEvents.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

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

interface ICronV1PoolEvents is ICronV1PoolEnums {
  /// @notice ShortTermSwap event is emitted for Short-Term (ST) swap transactions and
  ///         arbitrage partner ST swap transactions. To differentiate, examine the value of
  ///         swapType in the emitted event.
  ///
  event ShortTermSwap(
    address indexed sender,
    address indexed tokenIn,
    uint256 amountIn,
    uint256 amountOut,
    uint256 swapType
  );

  /// @notice LongTermSwap event is emitted when Long-Term (LT) swaps transaction are issued to
  ///         the pool.
  ///
  event LongTermSwap(
    address indexed sender,
    address indexed delegate,
    address indexed tokenIn,
    uint256 amountIn,
    uint256 intervals,
    uint256 orderId
  );

  /// @notice PoolJoin events are emitted for Join/Mint and Reward transactions. A Reward
  ///         transaction can be identified from a Join/Mint transaction by examining the
  ///         emitted event's poolTokenAmt to see if is zero.
  ///
  event PoolJoin(
    address indexed sender,
    address indexed recipient,
    uint256 token0In,
    uint256 token1In,
    uint256 poolTokenAmt
  );

  /// @notice WithdrawLongTermSwap events are emitted when an LT swap order is withdrawn or cancelled
  ///         in a transaction. To differentiate between the two, only a cancellation will have non-zero
  ///         values for refundOut.
  ///
  event WithdrawLongTermSwap(
    address indexed owner,
    address indexed refundToken,
    uint256 refundOut,
    address indexed proceedsToken,
    uint256 proceedsOut,
    uint256 orderId,
    address sender
  );

  /// @notice FeeWithdraw events are emitted when Cron-Fi fees are withdrawn from the pool.
  ///
  event FeeWithdraw(address indexed sender, uint256 token0Out, uint256 token1Out);

  /// @notice PoolExit events are emitted when a Liquidity Provider (LP) redeems LP tokens for
  ///         their share of tokens remaining in the pool.
  ///
  event PoolExit(address indexed sender, uint256 poolTokenAmt, uint256 token0Out, uint256 token1Out);

  /// @notice AdministratorStatusChange events are emitted when an administrator address, admin,
  ///         is given administrator privileges (status == true) or when they are taken away
  ///         (status == false).
  ///
  event AdministratorStatusChange(address indexed sender, address indexed admin, bool status);

  /// @notice ProtocolFeeTooLarge is emitted if the protocol fee passed in by balancer ever exceeds
  ///         1e18 (in which case the change is ignored and fees continue with the last good value).
  ///
  event ProtocolFeeTooLarge(uint256 suggestedProtocolFee);

  /// @notice ParameterChange is emitted when a parameter value is changed to value. Consult the
  ///         enum ParmType for the parameter undergoing change.
  ///
  event ParameterChange(address indexed sender, ParamType paramType, uint256 value);

  /// @notice FeeAddressChange is emitted when the fee address, feeAddress, is changed.
  ///
  event FeeAddressChange(address indexed sender, address indexed feeAddress);

  /// @notice FeeShiftChange is emitted when the fee shift, feeShift is changed.
  ///
  event FeeShiftChange(address indexed sender, uint256 feeShift);

  /// @notice BoolParameterChange is emitted when a boolean value parameter is changed. Consult the
  ///         enum BoolParmType for the parameter undergoing change.
  ///
  event BoolParameterChange(address indexed sender, BoolParamType boolParam, bool value);

  /// @notice UpdatedArbitragePartner is emitted when an arbitrage partner's arbitrageur list is
  ///         updated to a new contract address.
  ///
  event UpdatedArbitragePartner(address indexed sender, address partner, address list);

  /// @notice UpdatedArbitrageList is emitted when an arbitrage partner's updates their arbitrageur
  ///         list is to a new contract address through the updateArbitrageList function.
  ///
  event UpdatedArbitrageList(address indexed partner, address indexed oldList, address indexed newList);

  /// @notice ExecuteVirtualOrdersEvent is emitted on calls to executeVirtualOrdersToBlock.
  ///
  event ExecuteVirtualOrdersEvent(address indexed sender, uint256 block);
}

// File: contracts/twault/interfaces/pool/ICronV1PoolHelpers.sol



// (c) Copyright 2022, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.6;

pragma experimental ABIEncoderV2;

import { ICronV1PoolEnums } from "./ICronV1PoolEnums.sol";
import { Order, PriceOracle, ExecVirtualOrdersMem } from "../Structs.sol";

interface ICronV1PoolHelpers {
  function getVirtualPriceOracle(uint256 _maxBlock)
    external
    returns (
      uint256 timestamp,
      uint256 token0U256F112,
      uint256 token1U256F112,
      uint256 blockNumber
    );

  function getVirtualReserves(uint256 _maxBlock, bool _paused)
    external
    returns (
      uint256 blockNumber,
      uint256 token0ReserveU112,
      uint256 token1ReserveU112,
      uint256 token0OrdersU112,
      uint256 token1OrdersU112,
      uint256 token0ProceedsU112,
      uint256 token1ProceedsU112,
      uint256 token0BalancerFeesU96,
      uint256 token1BalancerFeesU96,
      uint256 token0CronFiFeesU96,
      uint256 token1CronFiFeesU96
    );

  // solhint-disable-next-line func-name-mixedcase
  function POOL_ID() external view returns (bytes32);

  // solhint-disable-next-line func-name-mixedcase
  function POOL_TYPE() external view returns (ICronV1PoolEnums.PoolType);

  function getPriceOracle()
    external
    view
    returns (
      uint256 timestamp,
      uint256 token0U256F112,
      uint256 token1U256F112
    );

  function getOrderIds(
    address _owner,
    uint256 _offset,
    uint256 _maxResults
  )
    external
    view
    returns (
      uint256[] memory orderIds,
      uint256 numResults,
      uint256 totalResults
    );

  function getOrder(uint256 _orderId) external view returns (Order memory order);

  function getOrderIdCount() external view returns (uint256 nextOrderId);

  function getSalesRates() external view returns (uint256 salesRate0U112, uint256 salesRate1U112);

  function getLastVirtualOrderBlock() external view returns (uint256 lastVirtualOrderBlock);

  function getSalesRatesEndingPerBlock(uint256 _blockNumber)
    external
    view
    returns (uint256 salesRateEndingPerBlock0U112, uint256 salesRateEndingPerBlock1U112);

  function getShortTermFeePoints() external view returns (uint256);

  function getPartnerFeePoints() external view returns (uint256);

  function getLongTermFeePoints() external view returns (uint256);

  function getOrderAmounts() external view returns (uint256 orders0U112, uint256 orders1U112);

  function getProceedAmounts() external view returns (uint256 proceeds0U112, uint256 proceeds1U112);

  function getFeeShift() external view returns (uint256);

  function getCronFeeAmounts() external view returns (uint256 cronFee0U96, uint256 cronFee1U96);

  function isPaused() external view returns (bool);

  function isCollectingCronFees() external view returns (bool);

  function isCollectingBalancerFees() external view returns (bool);

  function getBalancerFee() external view returns (uint256);

  function getBalancerFeeAmounts() external view returns (uint256 balFee0U96, uint256 balFee1U96);
}

// File: contracts/twault/miscellany/Constants.sol



// (c) Copyright 2023, Bad Pumpkin Inc. All Rights Reserved
//
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.7.6;

/// @notice Library of constants used throughout the implementation.
///
/// @dev Conventions in the methods, variables and constants are as follows:
///
///      Prefixes:
///
///      - In constants, the prefix "Sn", where 1 <= n <= 4, denotes which slot the constant
///        pertains too. There are four storage slots that are bitpacked. For example,
///        "S2_OFFSET_ORACLE_TIMESTAMP" refers to the offset of the oracle timestamp in bit-
///        packed storage slot 2.
///
///      Suffixes:
///
///      - The suffix of a variable name denotes the type contained within the variable.
///        For instance "uint256 _incrementU96" is a 256-bit unsigned container representing
///        the 96-bit value "_increment".
///        In the case of "uint256 _balancerFeeDU1F18", the 256-bit unsigned container is
///        representing a 19 digit decimal value with 18 fractional digits. In this scenario,
///        the D=Decimal, U=Unsigned, F=Fractional.
///        Finally, "uint128 valueU128F64" is a 128-bit container representing a 128-bit value
///        with 64 fractional bits.
///
///      - The suffix of a function name denotes what slot it is proprietary too as a
///        matter of convention. While unchecked at run-time or by the compiler, the naming
///        convention easily aids in understanding what slot a packed value is stored within.
///        For instance the function "unpackFeeShiftS3" unpacks the fee shift from slot 3. If
///        the value of slot 2 were passed to this method, the unpacked value would be
///        incorrect.
///
library C {
  //
  // Factory owner and default pool admin address
  ////////////////////////////////////////////////////////////////////////////////
  address internal constant CRON_DEPLOYER_ADMIN = 0xe122Eff60083bC550ACbf31E7d8197A58d436b39;

  //
  // General constants
  ////////////////////////////////////////////////////////////////////////////////
  address internal constant NULL_ADDR = address(0);

  uint256 internal constant FALSE = 0;

  uint256 internal constant MAX_U256 = type(uint256).max;
  uint256 internal constant MAX_U128 = type(uint128).max;
  uint256 internal constant MAX_U112 = type(uint112).max;
  uint256 internal constant MAX_U96 = type(uint96).max;
  uint256 internal constant MAX_U64 = type(uint64).max;
  uint256 internal constant MAX_U60 = 2**60 - 1;
  uint256 internal constant MAX_U32 = type(uint32).max;
  uint256 internal constant MAX_U24 = type(uint24).max;
  uint256 internal constant MAX_U20 = 0xFFFFF;
  uint256 internal constant MAX_U16 = type(uint16).max;
  uint256 internal constant MAX_U10 = 0x3FF;
  uint256 internal constant MAX_U8 = type(uint8).max;
  uint256 internal constant MAX_U3 = 0x7;
  uint256 internal constant MAX_U1 = 0x1;

  uint256 internal constant ONE_DU1_18 = 10**18;
  uint256 internal constant DENOMINATOR_DU1_18 = 10**18;

  uint256 internal constant SECONDS_PER_BLOCK = 12;

  //
  // Array Index constants
  ////////////////////////////////////////////////////////////////////////////////
  uint256 internal constant INDEX_TOKEN0 = 0;
  uint256 internal constant INDEX_TOKEN1 = 1;

  //
  // Bit-Packing constants
  //
  // Dev: Bit-offsets below are the offset from the first bit. For example to get
  //      to bit 250, the offset 249 is used. (The first bit is counted as bit 1).
  ////////////////////////////////////////////////////////////////////////////////

  // Masks:
  uint256 internal constant CLEAR_MASK_PAIR_U96 = ~((MAX_U96 << 96) | MAX_U96);
  uint256 internal constant CLEAR_MASK_PAIR_U112 = ~((MAX_U112 << 112) | MAX_U112);
  uint256 internal constant CLEAR_MASK_ORACLE_TIMESTAMP = ~(MAX_U32 << S2_OFFSET_ORACLE_TIMESTAMP);
  uint256 internal constant CLEAR_MASK_FEE_SHIFT = ~(MAX_U3 << S3_OFFSET_FEE_SHIFT_U3);
  uint256 internal constant CLEAR_MASK_BALANCER_FEE = ~(MAX_U60 << S4_OFFSET_BALANCER_FEE);

  // Slot 1 Offsets:
  uint256 internal constant S1_OFFSET_SHORT_TERM_FEE_FP = 244; // Bits 254-245;
  uint256 internal constant S1_OFFSET_PARTNER_FEE_FP = 234; // Bits 244-235;
  uint256 internal constant S1_OFFSET_LONG_TERM_FEE_FP = 224; // Bits 234-225;

  // Slot 2 Offsets:
  uint256 internal constant S2_OFFSET_ORACLE_TIMESTAMP = 224; // Bits 256-225;

  // Slot 3 Offsets:
  uint256 internal constant S3_OFFSET_FEE_SHIFT_U3 = 222; // Bits 225-223

  // Slot 4 Offsets:
  uint256 internal constant S4_OFFSET_PAUSE = 255; // Bit 256
  uint256 internal constant S4_OFFSET_CRON_FEE_ENABLED = 254; // Bit 255
  uint256 internal constant S4_OFFSET_COLLECT_BALANCER_FEES = 253; // Bit 254
  uint256 internal constant S4_OFFSET_ZERO_CRONFI_FEES = 252; // Bit 253
  uint256 internal constant S4_OFFSET_BALANCER_FEE = 192; // Bits 252-193;

  //
  // Scaling constants
  ////////////////////////////////////////////////////////////////////////////////
  //
  uint256 internal constant MAX_DECIMALS = 22;
  uint256 internal constant MIN_DECIMALS = 2;

  //
  // Pool Specific constants
  ////////////////////////////////////////////////////////////////////////////////
  uint256 internal constant MINIMUM_LIQUIDITY = 10**3;

  uint16 internal constant STABLE_OBI = 75; // ~15m @ 12s/block
  uint16 internal constant LIQUID_OBI = 300; // ~60m @ 12s/block
  uint16 internal constant VOLATILE_OBI = 1200; // ~240m @ 12s/block

  // Maximum long-term swap (5 years, 13149000 blocks @ 12s/block).
  // - Numbers below are 13149000 / OBI (rounded down where noted):
  uint24 internal constant STABLE_MAX_INTERVALS = 175320;
  uint24 internal constant LIQUID_MAX_INTERVALS = 43830;
  uint24 internal constant VOLATILE_MAX_INTERVALS = 10957; // Rounded down from 10957.5

  //
  // Fees constants
  ////////////////////////////////////////////////////////////////////////////////
  //       FP = Total Fee Points
  //       ST = Short-Term Swap
  //       LT = Long-Term Swap
  //       LP = Liquidity Provider
  //       CF = Cron Fi
  //
  // NOTE: Mult-by these constants requires Max. 14-bits (~13.3 bits) headroom to prevent overflow.
  //
  uint256 internal constant TOTAL_FP = 100000;
  uint256 internal constant MAX_FEE_FP = 1000; // 1.000%

  // Short Term Swap Payouts:
  // ----------------------------------------
  uint16 internal constant STABLE_ST_FEE_FP = 10; // 0.010%
  uint16 internal constant LIQUID_ST_FEE_FP = 50; // 0.050%
  uint16 internal constant VOLATILE_ST_FEE_FP = 100; // 0.100%

  // Partner Swap Payouts:
  // ----------------------------------------
  uint16 internal constant STABLE_ST_PARTNER_FEE_FP = 5; // 0.005%
  uint16 internal constant LIQUID_ST_PARTNER_FEE_FP = 25; // 0.025%
  uint16 internal constant VOLATILE_ST_PARTNER_FEE_FP = 50; // 0.050%

  // Long Term Swap Payouts
  // ----------------------------------------
  uint16 internal constant STABLE_LT_FEE_FP = 30; // 0.030%
  uint16 internal constant LIQUID_LT_FEE_FP = 150; // 0.150%
  uint16 internal constant VOLATILE_LT_FEE_FP = 300; // 0.300%

  uint8 internal constant DEFAULT_FEE_SHIFT = 1; // 66% LP to 33% CronFi
}

// File: contracts/twault/miscellany/Errors.sol



// SPDX-License-Identifier: GPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

// NOTE: Adapted from Balancer's BalancerErrors.sol code.

pragma solidity ^0.7.6;

/// @dev Conventions in the methods below are as follows:
///
///      Suffixes:
///
///      - The suffix of a variable name denotes the type contained within the variable.
///        For instance "uint256 _incrementU96" is a 256-bit unsigned container representing
///        a 96-bit value, _increment.
///        In the case of "uint256 _balancerFeeDU1F18", the 256-bit unsigned container is
///        representing a 19 digit decimal value with 18 fractional digits. In this scenario,
///        the D=Decimal, U=Unsigned, F=Fractional.
///
///      - The suffix of a function name denotes what slot it is proprietary too as a
///        matter of convention. While unchecked at run-time or by the compiler, the naming
///        convention easily aids in understanding what slot a packed value is stored within.
///        For instance the function "unpackFeeShiftS3" unpacks the fee shift from slot 3. If
///        the value of slot 2 were passed to this method, the unpacked value would be
///        incorrect.

/// @notice Reverts if the specified condition is not true with the provided error code.
/// @param _condition A condition to test; must resolve to true to not revert.
/// @param _errorCodeD3 An 3 digit decimal error code to present if the condition
///                     resolves to false.
///                     Min. = 0, Max. = 999.
/// @dev WARNING: No checks of _errorCodeD3 are performed for efficiency!
///
// solhint-disable-next-line func-visibility
function requireErrCode(bool _condition, uint256 _errorCodeD3) pure {
  if (!_condition) {
    // We're going to dynamically create a revert string based on the error code, with the following format:
    // 'CFI#{errorCode}'
    // where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
    //
    // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
    // number (8 to 16 bits) than the individual string characters.
    //
    // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
    // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
    // safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
    // solhint-disable-next-line no-inline-assembly
    assembly {
      // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
      // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
      // the '0' character.

      let units := add(mod(_errorCodeD3, 10), 0x30)

      _errorCodeD3 := div(_errorCodeD3, 10)
      let tenths := add(mod(_errorCodeD3, 10), 0x30)

      _errorCodeD3 := div(_errorCodeD3, 10)
      let hundreds := add(mod(_errorCodeD3, 10), 0x30)

      // With the individual characters, we can now construct the full string. The "CFI#" part is a known constant
      // (0x43464923): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
      // characters to it, each shifted by a multiple of 8.
      // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
      // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
      // array).

      let revertReason := shl(200, add(0x43464923000000, add(add(units, shl(8, tenths)), shl(16, hundreds))))

      // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
      // message will have the following layout:
      // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]

      // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
      // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
      mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
      // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
      mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
      // The string length is fixed: 7 characters.
      mstore(0x24, 7)
      // Finally, the string itself is stored.
      mstore(0x44, revertReason)

      // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
      // the encoded message is therefore 4 + 32 + 32 + 32 = 100.
      revert(0, 100)
    }
  }
}

library CronErrors {
  //
  // Permissions
  ////////////////////////////////////////////////////////////////////////////////

  uint256 internal constant SENDER_NOT_FACTORY = 0;
  uint256 internal constant SENDER_NOT_FACTORY_OWNER = 1;
  uint256 internal constant SENDER_NOT_ADMIN = 2;
  uint256 internal constant SENDER_NOT_ARBITRAGE_PARTNER = 3;
  uint256 internal constant NON_VAULT_CALLER = 4;
  uint256 internal constant SENDER_NOT_PARTNER = 5;
  uint256 internal constant SENDER_NOT_FEE_ADDRESS = 7;
  uint256 internal constant SENDER_NOT_ORDER_OWNER_OR_DELEGATE = 8;
  uint256 internal constant CANNOT_TRANSFER_TO_SELF_OR_NULL = 9;
  uint256 internal constant RECIPIENT_NOT_OWNER = 10;
  // A cleared order can be one that:
  //   - was cancelled
  //   - was withdrawn after expiry
  //   - never existed (i.e. empty blockchain state in the future)
  uint256 internal constant CLEARED_ORDER = 11;

  //
  // Modifiers
  ////////////////////////////////////////////////////////////////////////////////

  uint256 internal constant POOL_PAUSED = 100;

  //
  // Configuration & Parameterization
  ////////////////////////////////////////////////////////////////////////////////

  uint256 internal constant UNSUPPORTED_SWAP_KIND = 201;
  uint256 internal constant INSUFFICIENT_LIQUIDITY = 204;
  uint256 internal constant INCORRECT_POOL_ID = 206;
  uint256 internal constant ZERO_SALES_RATE = 208;
  uint256 internal constant NO_FUNDS_AVAILABLE = 212;
  uint256 internal constant MAX_ORDER_LENGTH_EXCEEDED = 223;
  uint256 internal constant NO_FEES_AVAILABLE = 224;
  uint256 internal constant UNSUPPORTED_TOKEN_DECIMALS = 225;
  uint256 internal constant NULL_RECIPIENT_ON_JOIN = 226;
  uint256 internal constant CANT_CANCEL_COMPLETED_ORDER = 227;
  uint256 internal constant MINIMUM_NOT_SATISFIED = 228;

  //
  // General
  ////////////////////////////////////////////////////////////////////////////////

  uint256 internal constant VALUE_EXCEEDS_CONTAINER_SZ = 400;
  uint256 internal constant OVERFLOW = 401;
  uint256 internal constant UNDERFLOW = 402;
  uint256 internal constant PARAM_ERROR = 403;

  //
  // Factory
  ////////////////////////////////////////////////////////////////////////////////

  uint256 internal constant ZERO_TOKEN_ADDRESSES = 500;
  uint256 internal constant IDENTICAL_TOKEN_ADDRESSES = 501;
  uint256 internal constant EXISTING_POOL = 502;
  uint256 internal constant INVALID_FACTORY_OWNER = 503;
  uint256 internal constant INVALID_PENDING_OWNER = 504;
  uint256 internal constant NON_EXISTING_POOL = 505;

  //
  // Periphery Relayer
  ////////////////////////////////////////////////////////////////////////////////
  uint256 internal constant P_ETH_TRANSFER = 600;
  uint256 internal constant P_NULL_USER_ADDRESS = 602;
  uint256 internal constant P_INSUFFICIENT_LIQUIDITY = 603;
  uint256 internal constant P_INSUFFICIENT_TOKEN_A_USER_BALANCE = 604;
  uint256 internal constant P_INSUFFICIENT_TOKEN_B_USER_BALANCE = 605;
  uint256 internal constant P_INVALID_POOL_TOKEN_AMOUNT = 606;
  uint256 internal constant P_INSUFFICIENT_POOL_TOKEN_USER_BALANCE = 607;
  uint256 internal constant P_INVALID_INTERVAL_AMOUNT = 608;
  uint256 internal constant P_DELEGATE_WITHDRAW_RECIPIENT_NOT_OWNER = 609;
  uint256 internal constant P_INVALID_OR_EXPIRED_ORDER_ID = 610;
  uint256 internal constant P_WITHDRAW_BY_ORDER_OR_DELEGATE_ONLY = 611;
  uint256 internal constant P_DELEGATE_CANCEL_RECIPIENT_NOT_OWNER = 612;
  uint256 internal constant P_CANCEL_BY_ORDER_OR_DELEGATE_ONLY = 613;
  uint256 internal constant P_INVALID_TOKEN_IN_ADDRESS = 614;
  uint256 internal constant P_INVALID_TOKEN_OUT_ADDRESS = 615;
  uint256 internal constant P_INVALID_POOL_TYPE = 616;
  uint256 internal constant P_NON_EXISTING_POOL = 617;
  uint256 internal constant P_INVALID_POOL_ADDRESS = 618;
  uint256 internal constant P_INVALID_AMOUNT_IN = 619;
  uint256 internal constant P_INSUFFICIENT_TOKEN_IN_USER_BALANCE = 620;
  uint256 internal constant P_POOL_HAS_NO_LIQUIDITY = 621;
  uint256 internal constant P_MAX_ORDER_LENGTH_EXCEEDED = 622;
  uint256 internal constant P_NOT_IMPLEMENTED = 624;
  uint256 internal constant P_MULTICALL_NOT_SUPPORTED = 625;
}

// File: contracts/twault/periphery/CronV1Relayer.sol



// SPDX-License-Identifier: BUSL-1.1
//
// (c) Copyright 2023, Bad Pumpkin Inc. All Rights Reserved
//
pragma solidity ^0.7.6;
pragma experimental ABIEncoderV2;

import { IVault } from "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import { IERC20 } from "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";

import { Address } from "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import { ReentrancyGuard } from "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol";

import { ICronV1Relayer } from "../interfaces/ICronV1Relayer.sol";
import { ICronV1Pool } from "../interfaces/ICronV1Pool.sol";
import { ICronV1PoolFactory } from "../interfaces/ICronV1PoolFactory.sol";
import { Order } from "../interfaces/Structs.sol";

import { C } from "../miscellany/Constants.sol";
import { requireErrCode, CronErrors } from "../miscellany/Errors.sol";

/// @title CronFi Relayer / Periphery Contract
/// @author Zero Slippage (0slippage) & 0x70626a.eth, Based upon example Balancer relayer designs.
/// @notice A periphery contract for the CronFi V1 Time-Weighted Average Market Maker (TWAMM) pools built
///         upon Balancer Vault. While this contract's interface to the CronFi TWAMM pools increases gas use,
///         it provides reasonable safety checks on behalf of the user that the core contract does not. It is also
///         convenient for users within Etherscan, Gnosis Safe and other contract web interfaces, eliminating the need
///         for the construction of complex Solidity data types that are cumbersome in that environment.
///
///         For usage details, see the online CronFi documentation at https://docs.cronfi.com/.
///
///         IMPORTANT: Users must approve this contract on the Balancer Vault before any transactions can be used.
///                    This can be done by calling setRelayerApproval on the Balancer Vault contract and specifying
///                    this contract's address.
///
///
contract CronV1Relayer is ICronV1Relayer, ReentrancyGuard {
  using Address for address payable;
  using Address for address;

  IVault private immutable VAULT;
  address private immutable LIB_ADDR;
  ICronV1PoolFactory private immutable FACTORY;

  /// @notice Creates an instance of the CronFi Time-Weighted Average Market Maker (TWAMM) periphery relayer
  ///         contract.
  ///
  /// @dev IMPORTANT: This contract is not meant to be deployed directly by an EOA, but rather during construction
  ///                 of a library contract derived from `BaseRelayerLibrary`, which will provide its own address
  ///                 as this periphery relayer's library address, LIB_ADDR.
  ///
  /// @param _vault is the Balancer Vault instance this periphery relayer contract services.
  /// @param _libraryAddress is the address of the library contract this periphery relayer uses to interact
  ///                        with the Vault instance. Note as mentioned above in the "dev" note, the library contract
  ///                        is instantiated first and then constructs this contract with its address, _libraryAddress,
  ///                        as an argument.
  /// @param _factory is the CronFi factory contract instance.
  ///
  constructor(
    IVault _vault,
    address _libraryAddress,
    ICronV1PoolFactory _factory
  ) {
    VAULT = _vault;
    LIB_ADDR = _libraryAddress;
    FACTORY = _factory;
  }

  /// @notice Do not accept ETH transfers from anyone. The relayer and CronFi Time Weighted Average Market
  ///         Maker (TWAMM) pools do not work with raw ETH.
  ///
  ///         NOTE: Unlike other Balancer relayer examples, the refund ETH functionality has been removed to prevent
  ///               self-destruct attacks, causing transactions to revert, since CronFi TWAMM doesn't support
  ///               raw ETH.
  ///
  receive() external payable {
    requireErrCode(false, CronErrors.P_ETH_TRANSFER);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function swap(
    address _tokenIn,
    address _tokenOut,
    uint256 _poolType,
    uint256 _amountIn,
    uint256 _minTokenOut,
    address _recipient
  ) external override(ICronV1Relayer) nonReentrant returns (bytes memory swapResult) {
    bytes memory data = abi.encodeWithSignature(
      "swap(address,uint256,address,uint256,uint256,address,address)",
      _tokenIn,
      _amountIn,
      _tokenOut,
      _minTokenOut,
      _poolType,
      msg.sender,
      _recipient
    );
    swapResult = _delegateCallFn(data);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function join(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _liquidityA,
    uint256 _liquidityB,
    uint256 _minLiquidityA,
    uint256 _minLiquidityB,
    address _recipient
  ) external override(ICronV1Relayer) nonReentrant returns (bytes memory joinResult) {
    bytes memory data = abi.encodeWithSignature(
      "join(address,address,uint256,uint256,uint256,uint256,uint256,address,address)",
      _tokenA,
      _tokenB,
      _poolType,
      _liquidityA,
      _liquidityB,
      _minLiquidityA,
      _minLiquidityB,
      msg.sender,
      _recipient
    );
    joinResult = _delegateCallFn(data);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function exit(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _numLPTokens,
    uint256 _minAmountOutA,
    uint256 _minAmountOutB,
    address _recipient
  ) external override(ICronV1Relayer) nonReentrant returns (bytes memory exitResult) {
    bytes memory data = abi.encodeWithSignature(
      "exit(address,address,uint256,uint256,uint256,uint256,address,address)",
      _tokenA,
      _tokenB,
      _poolType,
      _numLPTokens,
      _minAmountOutA,
      _minAmountOutB,
      msg.sender,
      _recipient
    );
    exitResult = _delegateCallFn(data);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function longTermSwap(
    address _tokenIn,
    address _tokenOut,
    uint256 _poolType,
    uint256 _amountIn,
    uint256 _intervals,
    address _delegate
  ) external override(ICronV1Relayer) nonReentrant returns (bytes memory longTermSwapResult, uint256 orderId) {
    requireErrCode(_tokenIn != C.NULL_ADDR, CronErrors.P_INVALID_TOKEN_IN_ADDRESS);
    requireErrCode(_tokenOut != C.NULL_ADDR, CronErrors.P_INVALID_TOKEN_OUT_ADDRESS);

    requireErrCode(_poolType < 3, CronErrors.P_INVALID_POOL_TYPE);
    address pool = FACTORY.getPool(_tokenIn, _tokenOut, _poolType);
    requireErrCode(pool != C.NULL_ADDR, CronErrors.P_NON_EXISTING_POOL);

    bytes32 poolId = ICronV1Pool(pool).POOL_ID();
    requireErrCode(poolId != "", CronErrors.P_INVALID_POOL_ADDRESS);

    orderId = ICronV1Pool(pool).getOrderIdCount();

    bytes memory data = abi.encodeWithSignature(
      "longTermSwap(address,address,uint256,uint256,uint256,address,address)",
      _tokenIn,
      _tokenOut,
      _poolType,
      _amountIn,
      _intervals,
      msg.sender,
      _delegate
    );
    longTermSwapResult = _delegateCallFn(data);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function withdraw(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _orderId,
    address _recipient
  ) external override(ICronV1Relayer) nonReentrant returns (bytes memory withdrawResult) {
    bytes memory data = abi.encodeWithSignature(
      "withdraw(address,address,uint256,uint256,address,address)",
      _tokenA,
      _tokenB,
      _poolType,
      _orderId,
      msg.sender,
      _recipient
    );
    withdrawResult = _delegateCallFn(data);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function cancel(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _orderId,
    address _recipient
  ) external override(ICronV1Relayer) nonReentrant returns (bytes memory cancelResult) {
    bytes memory data = abi.encodeWithSignature(
      "cancel(address,address,uint256,uint256,address,address)",
      _tokenA,
      _tokenB,
      _poolType,
      _orderId,
      msg.sender,
      _recipient
    );
    cancelResult = _delegateCallFn(data);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function getVault() external view override(ICronV1Relayer) returns (IVault) {
    return VAULT;
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function getLibrary() external view override(ICronV1Relayer) returns (address) {
    return LIB_ADDR;
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function getPoolAddress(
    address _tokenA,
    address _tokenB,
    uint256 _poolType
  ) external view override(ICronV1Relayer) returns (address pool) {
    pool = FACTORY.getPool(_tokenA, _tokenB, _poolType);
    requireErrCode(pool != C.NULL_ADDR, CronErrors.P_NON_EXISTING_POOL);
  }

  /// @notice see documentation in ICronV1Relayer.sol
  ///
  function getOrder(
    address _tokenA,
    address _tokenB,
    uint256 _poolType,
    uint256 _orderId
  ) external view override(ICronV1Relayer) returns (address pool, Order memory order) {
    pool = FACTORY.getPool(_tokenA, _tokenB, _poolType);
    requireErrCode(pool != C.NULL_ADDR, CronErrors.P_NON_EXISTING_POOL);

    order = ICronV1Pool(pool).getOrder(_orderId);
  }

  /// @notice Performs delegate calls from provided encoded data on this periphery relayer's
  ///         library contract.
  /// @param _data is encoded delegate call data for functions of this periphery relayer's library
  ///              contract.
  /// @return result is the result of the delegate call.
  ///
  function _delegateCallFn(bytes memory _data) private returns (bytes memory result) {
    result = LIB_ADDR.functionDelegateCall(_data);
  }
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

// solhint-disable

/**
 * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
 * supported.
 * Uses the default 'BAL' prefix for the error code
 */
function _require(bool condition, uint256 errorCode) pure {
    if (!condition) _revert(errorCode);
}

/**
 * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are
 * supported.
 */
function _require(
    bool condition,
    uint256 errorCode,
    bytes3 prefix
) pure {
    if (!condition) _revert(errorCode, prefix);
}

/**
 * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
 * Uses the default 'BAL' prefix for the error code
 */
function _revert(uint256 errorCode) pure {
    _revert(errorCode, 0x42414c); // This is the raw byte representation of "BAL"
}

/**
 * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
 */
function _revert(uint256 errorCode, bytes3 prefix) pure {
    uint256 prefixUint = uint256(uint24(prefix));
    // We're going to dynamically create a revert string based on the error code, with the following format:
    // 'BAL#{errorCode}'
    // where the code is left-padded with zeroes to three digits (so they range from 000 to 999).
    //
    // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a
    // number (8 to 16 bits) than the individual string characters.
    //
    // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a
    // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a
    // safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
    assembly {
        // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999
        // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for
        // the '0' character.

        let units := add(mod(errorCode, 10), 0x30)

        errorCode := div(errorCode, 10)
        let tenths := add(mod(errorCode, 10), 0x30)

        errorCode := div(errorCode, 10)
        let hundreds := add(mod(errorCode, 10), 0x30)

        // With the individual characters, we can now construct the full string.
        // We first append the '#' character (0x23) to the prefix. In the case of 'BAL', it results in 0x42414c23 ('BAL#')
        // Then, we shift this by 24 (to provide space for the 3 bytes of the error code), and add the
        // characters to it, each shifted by a multiple of 8.
        // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
        // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
        // array).
        let formattedPrefix := shl(24, add(0x23, shl(8, prefixUint)))

        let revertReason := shl(200, add(formattedPrefix, add(add(units, shl(8, tenths)), shl(16, hundreds))))

        // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded
        // message will have the following layout:
        // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ]

        // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We
        // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten.
        mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
        // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away).
        mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
        // The string length is fixed: 7 characters.
        mstore(0x24, 7)
        // Finally, the string itself is stored.
        mstore(0x44, revertReason)

        // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of
        // the encoded message is therefore 4 + 32 + 32 + 32 = 100.
        revert(0, 100)
    }
}

library Errors {
    // Math
    uint256 internal constant ADD_OVERFLOW = 0;
    uint256 internal constant SUB_OVERFLOW = 1;
    uint256 internal constant SUB_UNDERFLOW = 2;
    uint256 internal constant MUL_OVERFLOW = 3;
    uint256 internal constant ZERO_DIVISION = 4;
    uint256 internal constant DIV_INTERNAL = 5;
    uint256 internal constant X_OUT_OF_BOUNDS = 6;
    uint256 internal constant Y_OUT_OF_BOUNDS = 7;
    uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8;
    uint256 internal constant INVALID_EXPONENT = 9;

    // Input
    uint256 internal constant OUT_OF_BOUNDS = 100;
    uint256 internal constant UNSORTED_ARRAY = 101;
    uint256 internal constant UNSORTED_TOKENS = 102;
    uint256 internal constant INPUT_LENGTH_MISMATCH = 103;
    uint256 internal constant ZERO_TOKEN = 104;
    uint256 internal constant INSUFFICIENT_DATA = 105;

    // Shared pools
    uint256 internal constant MIN_TOKENS = 200;
    uint256 internal constant MAX_TOKENS = 201;
    uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202;
    uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203;
    uint256 internal constant MINIMUM_BPT = 204;
    uint256 internal constant CALLER_NOT_VAULT = 205;
    uint256 internal constant UNINITIALIZED = 206;
    uint256 internal constant BPT_IN_MAX_AMOUNT = 207;
    uint256 internal constant BPT_OUT_MIN_AMOUNT = 208;
    uint256 internal constant EXPIRED_PERMIT = 209;
    uint256 internal constant NOT_TWO_TOKENS = 210;
    uint256 internal constant DISABLED = 211;

    // Pools
    uint256 internal constant MIN_AMP = 300;
    uint256 internal constant MAX_AMP = 301;
    uint256 internal constant MIN_WEIGHT = 302;
    uint256 internal constant MAX_STABLE_TOKENS = 303;
    uint256 internal constant MAX_IN_RATIO = 304;
    uint256 internal constant MAX_OUT_RATIO = 305;
    uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306;
    uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307;
    uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308;
    uint256 internal constant INVALID_TOKEN = 309;
    uint256 internal constant UNHANDLED_JOIN_KIND = 310;
    uint256 internal constant ZERO_INVARIANT = 311;
    uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312;
    uint256 internal constant ORACLE_NOT_INITIALIZED = 313;
    uint256 internal constant ORACLE_QUERY_TOO_OLD = 314;
    uint256 internal constant ORACLE_INVALID_INDEX = 315;
    uint256 internal constant ORACLE_BAD_SECS = 316;
    uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317;
    uint256 internal constant AMP_ONGOING_UPDATE = 318;
    uint256 internal constant AMP_RATE_TOO_HIGH = 319;
    uint256 internal constant AMP_NO_ONGOING_UPDATE = 320;
    uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321;
    uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322;
    uint256 internal constant RELAYER_NOT_CONTRACT = 323;
    uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324;
    uint256 internal constant REBALANCING_RELAYER_REENTERED = 325;
    uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326;
    uint256 internal constant SWAPS_DISABLED = 327;
    uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328;
    uint256 internal constant PRICE_RATE_OVERFLOW = 329;
    uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330;
    uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331;
    uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332;
    uint256 internal constant UPPER_TARGET_TOO_HIGH = 333;
    uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334;
    uint256 internal constant OUT_OF_TARGET_RANGE = 335;
    uint256 internal constant UNHANDLED_EXIT_KIND = 336;
    uint256 internal constant UNAUTHORIZED_EXIT = 337;
    uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338;
    uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339;
    uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340;
    uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341;
    uint256 internal constant INVALID_INITIALIZATION = 342;
    uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343;
    uint256 internal constant FEATURE_DISABLED = 344;
    uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345;
    uint256 internal constant SET_SWAP_FEE_DURING_FEE_CHANGE = 346;
    uint256 internal constant SET_SWAP_FEE_PENDING_FEE_CHANGE = 347;
    uint256 internal constant CHANGE_TOKENS_DURING_WEIGHT_CHANGE = 348;
    uint256 internal constant CHANGE_TOKENS_PENDING_WEIGHT_CHANGE = 349;
    uint256 internal constant MAX_WEIGHT = 350;
    uint256 internal constant UNAUTHORIZED_JOIN = 351;
    uint256 internal constant MAX_MANAGEMENT_AUM_FEE_PERCENTAGE = 352;
    uint256 internal constant FRACTIONAL_TARGET = 353;
    uint256 internal constant ADD_OR_REMOVE_BPT = 354;
    uint256 internal constant INVALID_CIRCUIT_BREAKER_BOUNDS = 355;
    uint256 internal constant CIRCUIT_BREAKER_TRIPPED = 356;
    uint256 internal constant MALICIOUS_QUERY_REVERT = 357;
    uint256 internal constant JOINS_EXITS_DISABLED = 358;

    // Lib
    uint256 internal constant REENTRANCY = 400;
    uint256 internal constant SENDER_NOT_ALLOWED = 401;
    uint256 internal constant PAUSED = 402;
    uint256 internal constant PAUSE_WINDOW_EXPIRED = 403;
    uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404;
    uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405;
    uint256 internal constant INSUFFICIENT_BALANCE = 406;
    uint256 internal constant INSUFFICIENT_ALLOWANCE = 407;
    uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408;
    uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409;
    uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410;
    uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411;
    uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412;
    uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413;
    uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414;
    uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415;
    uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416;
    uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417;
    uint256 internal constant SAFE_ERC20_CALL_FAILED = 418;
    uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419;
    uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420;
    uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421;
    uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422;
    uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423;
    uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424;
    uint256 internal constant BUFFER_PERIOD_EXPIRED = 425;
    uint256 internal constant CALLER_IS_NOT_OWNER = 426;
    uint256 internal constant NEW_OWNER_IS_ZERO = 427;
    uint256 internal constant CODE_DEPLOYMENT_FAILED = 428;
    uint256 internal constant CALL_TO_NON_CONTRACT = 429;
    uint256 internal constant LOW_LEVEL_CALL_FAILED = 430;
    uint256 internal constant NOT_PAUSED = 431;
    uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432;
    uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433;
    uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434;
    uint256 internal constant INVALID_OPERATION = 435;
    uint256 internal constant CODEC_OVERFLOW = 436;
    uint256 internal constant IN_RECOVERY_MODE = 437;
    uint256 internal constant NOT_IN_RECOVERY_MODE = 438;
    uint256 internal constant INDUCED_FAILURE = 439;
    uint256 internal constant EXPIRED_SIGNATURE = 440;
    uint256 internal constant MALFORMED_SIGNATURE = 441;
    uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_UINT64 = 442;
    uint256 internal constant UNHANDLED_FEE_TYPE = 443;
    uint256 internal constant BURN_FROM_ZERO = 444;

    // Vault
    uint256 internal constant INVALID_POOL_ID = 500;
    uint256 internal constant CALLER_NOT_POOL = 501;
    uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502;
    uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503;
    uint256 internal constant INVALID_SIGNATURE = 504;
    uint256 internal constant EXIT_BELOW_MIN = 505;
    uint256 internal constant JOIN_ABOVE_MAX = 506;
    uint256 internal constant SWAP_LIMIT = 507;
    uint256 internal constant SWAP_DEADLINE = 508;
    uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509;
    uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510;
    uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511;
    uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512;
    uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513;
    uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514;
    uint256 internal constant INVALID_POST_LOAN_BALANCE = 515;
    uint256 internal constant INSUFFICIENT_ETH = 516;
    uint256 internal constant UNALLOCATED_ETH = 517;
    uint256 internal constant ETH_TRANSFER = 518;
    uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519;
    uint256 internal constant TOKENS_MISMATCH = 520;
    uint256 internal constant TOKEN_NOT_REGISTERED = 521;
    uint256 internal constant TOKEN_ALREADY_REGISTERED = 522;
    uint256 internal constant TOKENS_ALREADY_SET = 523;
    uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524;
    uint256 internal constant NONZERO_TOKEN_BALANCE = 525;
    uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526;
    uint256 internal constant POOL_NO_TOKENS = 527;
    uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528;

    // Fees
    uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600;
    uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601;
    uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602;
    uint256 internal constant AUM_FEE_PERCENTAGE_TOO_HIGH = 603;

    // FeeSplitter
    uint256 internal constant SPLITTER_FEE_PERCENTAGE_TOO_HIGH = 700;

    // Misc
    uint256 internal constant UNIMPLEMENTED = 998;
    uint256 internal constant SHOULD_NOT_HAPPEN = 999;
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/IAuthentication.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

interface IAuthentication {
    /**
     * @dev Returns the action identifier associated with the external function described by `selector`.
     */
    function getActionId(bytes4 selector) external view returns (bytes32);
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/ISignaturesValidator.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Interface for the SignatureValidator helper, used to support meta-transactions.
 */
interface ISignaturesValidator {
    /**
     * @dev Returns the EIP712 domain separator.
     */
    function getDomainSeparator() external view returns (bytes32);

    /**
     * @dev Returns the next nonce used by an address to sign messages.
     */
    function getNextNonce(address user) external view returns (uint256);
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/ITemporarilyPausable.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Interface for the TemporarilyPausable helper.
 */
interface ITemporarilyPausable {
    /**
     * @dev Emitted every time the pause state changes by `_setPaused`.
     */
    event PausedStateChanged(bool paused);

    /**
     * @dev Returns the current paused state.
     */
    function getPausedState()
        external
        view
        returns (
            bool paused,
            uint256 pauseWindowEndTime,
            uint256 bufferPeriodEndTime
        );
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/solidity-utils/misc/IWETH.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

import "../openzeppelin/IERC20.sol";

/**
 * @dev Interface for WETH9.
 * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol
 */
interface IWETH is IERC20 {
    function deposit() external payable;

    function withdraw(uint256 amount) external;
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @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);
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
 * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
 * types.
 *
 * This concept is unrelated to a Pool's Asset Managers.
 */
interface IAsset {
    // solhint-disable-previous-line no-empty-blocks
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/vault/IAuthorizer.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

interface IAuthorizer {
    /**
     * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`.
     */
    function canPerform(
        bytes32 actionId,
        address account,
        address where
    ) external view returns (bool);
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/vault/IFlashLoanRecipient.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;

// Inspired by Aave Protocol's IFlashLoanReceiver.

import "../solidity-utils/openzeppelin/IERC20.sol";

interface IFlashLoanRecipient {
    /**
     * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient.
     *
     * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this
     * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the
     * Vault, or else the entire flash loan will revert.
     *
     * `userData` is the same value passed in the `IVault.flashLoan` call.
     */
    function receiveFlashLoan(
        IERC20[] memory tokens,
        uint256[] memory amounts,
        uint256[] memory feeAmounts,
        bytes memory userData
    ) external;
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/vault/IProtocolFeesCollector.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;

import "../solidity-utils/openzeppelin/IERC20.sol";

import "./IVault.sol";
import "./IAuthorizer.sol";

interface IProtocolFeesCollector {
    event SwapFeePercentageChanged(uint256 newSwapFeePercentage);
    event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage);

    function withdrawCollectedFees(
        IERC20[] calldata tokens,
        uint256[] calldata amounts,
        address recipient
    ) external;

    function setSwapFeePercentage(uint256 newSwapFeePercentage) external;

    function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external;

    function getSwapFeePercentage() external view returns (uint256);

    function getFlashLoanFeePercentage() external view returns (uint256);

    function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts);

    function getAuthorizer() external view returns (IAuthorizer);

    function vault() external view returns (IVault);
}

// File: node_modules/@balancer-labs/v2-interfaces/contracts/vault/IVault.sol



// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma experimental ABIEncoderV2;

import "../solidity-utils/openzeppelin/IERC20.sol";
import "../solidity-utils/helpers/IAuthentication.sol";
import "../solidity-utils/helpers/ISignaturesValidator.sol";
import "../solidity-utils/helpers/ITemporarilyPausable.sol";
import "../solidity-utils/misc/IWETH.sol";

import "./IAsset.sol";
import "./IAuthorizer.sol";
import "./IFlashLoanRecipient.sol";
import "./IProtocolFeesCollector.sol";

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that
 * don't override one of these declarations.
 */
interface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication {
    // Generalities about the Vault:
    //
    // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are
    // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling
    // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by
    // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning
    // a boolean value: in these scenarios, a non-reverting call is assumed to be successful.
    //
    // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g.
    // while execution control is transferred to a token contract during a swap) will result in a revert. View
    // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results.
    // Contracts calling view functions in the Vault must make sure the Vault has not already been entered.
    //
    // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools.

    // Authorizer
    //
    // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists
    // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller
    // can perform a given action.

    /**
     * @dev Returns the Vault's Authorizer.
     */
    function getAuthorizer() external view returns (IAuthorizer);

    /**
     * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this.
     *
     * Emits an `AuthorizerChanged` event.
     */
    function setAuthorizer(IAuthorizer newAuthorizer) external;

    /**
     * @dev Emitted when a new authorizer is set by `setAuthorizer`.
     */
    event AuthorizerChanged(IAuthorizer indexed newAuthorizer);

    // Relayers
    //
    // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their
    // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions,
    // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield
    // this power, two things must occur:
    //  - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This
    //    means that Balancer governance must approve each individual contract to act as a relayer for the intended
    //    functions.
    //  - Each user must approve the relayer to act on their behalf.
    // This double protection means users cannot be tricked into approving malicious relayers (because they will not
    // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised
    // Authorizer or governance drain user funds, since they would also need to be approved by each individual user.

    /**
     * @dev Returns true if `user` has approved `relayer` to act as a relayer for them.
     */
    function hasApprovedRelayer(address user, address relayer) external view returns (bool);

    /**
     * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise.
     *
     * Emits a `RelayerApprovalChanged` event.
     */
    function setRelayerApproval(
        address sender,
        address relayer,
        bool approved
    ) external;

    /**
     * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`.
     */
    event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved);

    // Internal Balance
    //
    // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later
    // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination
    // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced
    // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users.
    //
    // Internal Balance management features batching, which means a single contract call can be used to perform multiple
    // operations of different kinds, with different senders and recipients, at once.

    /**
     * @dev Returns `user`'s Internal Balance for a set of tokens.
     */
    function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory);

    /**
     * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
     * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
     * it lets integrators reuse a user's Vault allowance.
     *
     * For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
     */
    function manageUserBalance(UserBalanceOp[] memory ops) external payable;

    /**
     * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
     without manual WETH wrapping or unwrapping.
     */
    struct UserBalanceOp {
        UserBalanceOpKind kind;
        IAsset asset;
        uint256 amount;
        address sender;
        address payable recipient;
    }

    // There are four possible operations in `manageUserBalance`:
    //
    // - DEPOSIT_INTERNAL
    // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding
    // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`.
    //
    // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped
    // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is
    // relevant for relayers).
    //
    // Emits an `InternalBalanceChanged` event.
    //
    //
    // - WITHDRAW_INTERNAL
    // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`.
    //
    // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send
    // it to the recipient as ETH.
    //
    // Emits an `InternalBalanceChanged` event.
    //
    //
    // - TRANSFER_INTERNAL
    // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`.
    //
    // Reverts if the ETH sentinel value is passed.
    //
    // Emits an `InternalBalanceChanged` event.
    //
    //
    // - TRANSFER_EXTERNAL
    // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by
    // relayers, as it lets them reuse a user's Vault allowance.
    //
    // Reverts if the ETH sentinel value is passed.
    //
    // Emits an `ExternalBalanceTransfer` event.

    enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL }

    /**
     * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through
     * interacting with Pools using Internal Balance.
     *
     * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH
     * address.
     */
    event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta);

    /**
     * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account.
     */
    event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount);

    // Pools
    //
    // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
    // functionality:
    //
    //  - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
    // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
    // which increase with the number of registered tokens.
    //
    //  - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
    // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
    // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
    // independent of the number of registered tokens.
    //
    //  - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
    // minimal swap info Pools, these are called via IMinimalSwapInfoPool.

    enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }

    /**
     * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which
     * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be
     * changed.
     *
     * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`,
     * depending on the chosen specialization setting. This contract is known as the Pool's contract.
     *
     * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words,
     * multiple Pools may share the same contract.
     *
     * Emits a `PoolRegistered` event.
     */
    function registerPool(PoolSpecialization specialization) external returns (bytes32);

    /**
     * @dev Emitted when a Pool is registered by calling `registerPool`.
     */
    event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization);

    /**
     * @dev Returns a Pool's contract address and specialization setting.
     */
    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);

    /**
     * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
     *
     * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,
     * exit by receiving registered tokens, and can only swap registered tokens.
     *
     * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length
     * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in
     * ascending order.
     *
     * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset
     * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`,
     * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore
     * expected to be highly secured smart contracts with sound design principles, and the decision to register an
     * Asset Manager should not be made lightly.
     *
     * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset
     * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a
     * different Asset Manager.
     *
     * Emits a `TokensRegistered` event.
     */
    function registerTokens(
        bytes32 poolId,
        IERC20[] memory tokens,
        address[] memory assetManagers
    ) external;

    /**
     * @dev Emitted when a Pool registers tokens by calling `registerTokens`.
     */
    event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers);

    /**
     * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract.
     *
     * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total
     * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens
     * must be deregistered in the same `deregisterTokens` call.
     *
     * A deregistered token can be re-registered later on, possibly with a different Asset Manager.
     *
     * Emits a `TokensDeregistered` event.
     */
    function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external;

    /**
     * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`.
     */
    event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens);

    /**
     * @dev Returns detailed information for a Pool's registered token.
     *
     * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens
     * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token`
     * equals the sum of `cash` and `managed`.
     *
     * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`,
     * `managed` or `total` balance to be greater than 2^112 - 1.
     *
     * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a
     * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for
     * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a
     * change for this purpose, and will update `lastChangeBlock`.
     *
     * `assetManager` is the Pool's token Asset Manager.
     */
    function getPoolTokenInfo(bytes32 poolId, IERC20 token)
        external
        view
        returns (
            uint256 cash,
            uint256 managed,
            uint256 lastChangeBlock,
            address assetManager
        );

    /**
     * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
     * the tokens' `balances` changed.
     *
     * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
     * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
     *
     * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
     * order as passed to `registerTokens`.
     *
     * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
     * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
     * instead.
     */
    function getPoolTokens(bytes32 poolId)
        external
        view
        returns (
            IERC20[] memory tokens,
            uint256[] memory balances,
            uint256 lastChangeBlock
        );

    /**
     * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
     * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
     * Pool shares.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
     * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
     * these maximums.
     *
     * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
     * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
     * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
     * back to the caller (not the sender, which is important for relayers).
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
     * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
     * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
     *
     * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
     * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
     * withdrawn from Internal Balance: attempting to do so will trigger a revert.
     *
     * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
     * directly to the Pool's contract, as is `recipient`.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function joinPool(
        bytes32 poolId,
        address sender,
        address recipient,
        JoinPoolRequest memory request
    ) external payable;

    struct JoinPoolRequest {
        IAsset[] assets;
        uint256[] maxAmountsIn;
        bytes userData;
        bool fromInternalBalance;
    }

    /**
     * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
     * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
     * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
     * `getPoolTokenInfo`).
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
     * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
     * it just enforces these minimums.
     *
     * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
     * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
     * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
     * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
     * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
     *
     * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
     * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
     * do so will trigger a revert.
     *
     * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
     * `tokens` array. This array must match the Pool's registered tokens.
     *
     * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
     * passed directly to the Pool's contract.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function exitPool(
        bytes32 poolId,
        address sender,
        address payable recipient,
        ExitPoolRequest memory request
    ) external;

    struct ExitPoolRequest {
        IAsset[] assets;
        uint256[] minAmountsOut;
        bytes userData;
        bool toInternalBalance;
    }

    /**
     * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively.
     */
    event PoolBalanceChanged(
        bytes32 indexed poolId,
        address indexed liquidityProvider,
        IERC20[] tokens,
        int256[] deltas,
        uint256[] protocolFeeAmounts
    );

    enum PoolBalanceChangeKind { JOIN, EXIT }

    // Swaps
    //
    // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this,
    // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be
    // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote.
    //
    // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence.
    // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'),
    // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out').
    // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together
    // individual swaps.
    //
    // There are two swap kinds:
    //  - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the
    // `onSwap` hook) the amount of tokens out (to send to the recipient).
    //  - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines
    // (via the `onSwap` hook) the amount of tokens in (to receive from the sender).
    //
    // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with
    // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated
    // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended
    // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at
    // the final intended token.
    //
    // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal
    // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes
    // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost
    // much less gas than they would otherwise.
    //
    // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple
    // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only
    // updating the Pool's internal accounting).
    //
    // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token
    // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the
    // minimum amount of tokens to receive (by passing a negative value) is specified.
    //
    // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after
    // this point in time (e.g. if the transaction failed to be included in a block promptly).
    //
    // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do
    // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be
    // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the
    // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers).
    //
    // Finally, Internal Balance can be used when either sending or receiving tokens.

    enum SwapKind { GIVEN_IN, GIVEN_OUT }

    /**
     * @dev Performs a swap with a single Pool.
     *
     * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
     * taken from the Pool, which must be greater than or equal to `limit`.
     *
     * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
     * sent to the Pool, which must be less than or equal to `limit`.
     *
     * Internal Balance usage and the recipient are determined by the `funds` struct.
     *
     * Emits a `Swap` event.
     */
    function swap(
        SingleSwap memory singleSwap,
        FundManagement memory funds,
        uint256 limit,
        uint256 deadline
    ) external payable returns (uint256);

    /**
     * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
     * the `kind` value.
     *
     * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
     * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
     *
     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
     * used to extend swap behavior.
     */
    struct SingleSwap {
        bytes32 poolId;
        SwapKind kind;
        IAsset assetIn;
        IAsset assetOut;
        uint256 amount;
        bytes userData;
    }

    /**
     * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
     * the amount of tokens sent to or received from the Pool, depending on the `kind` value.
     *
     * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
     * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
     * the same index in the `assets` array.
     *
     * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
     * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
     * `amountOut` depending on the swap kind.
     *
     * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
     * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
     * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
     *
     * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
     * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
     * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
     * or unwrapped from WETH by the Vault.
     *
     * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies
     * the minimum or maximum amount of each token the vault is allowed to transfer.
     *
     * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
     * equivalent `swap` call.
     *
     * Emits `Swap` events.
     */
    function batchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        IAsset[] memory assets,
        FundManagement memory funds,
        int256[] memory limits,
        uint256 deadline
    ) external payable returns (int256[] memory);

    /**
     * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
     * `assets` array passed to that function, and ETH assets are converted to WETH.
     *
     * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
     * from the previous swap, depending on the swap kind.
     *
     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
     * used to extend swap behavior.
     */
    struct BatchSwapStep {
        bytes32 poolId;
        uint256 assetInIndex;
        uint256 assetOutIndex;
        uint256 amount;
        bytes userData;
    }

    /**
     * @dev Emitted for each individual swap performed by `swap` or `batchSwap`.
     */
    event Swap(
        bytes32 indexed poolId,
        IERC20 indexed tokenIn,
        IERC20 indexed tokenOut,
        uint256 amountIn,
        uint256 amountOut
    );

    /**
     * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
     * `recipient` account.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
     * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
     * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
     * `joinPool`.
     *
     * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
     * transferred. This matches the behavior of `exitPool`.
     *
     * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
     * revert.
     */
    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }

    /**
     * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
     * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
     *
     * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
     * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
     * receives are the same that an equivalent `batchSwap` call would receive.
     *
     * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
     * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
     * approve them for the Vault, or even know a user's address.
     *
     * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
     * eth_call instead of eth_sendTransaction.
     */
    function queryBatchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        IAsset[] memory assets,
        FundManagement memory funds
    ) external returns (int256[] memory assetDeltas);

    // Flash Loans

    /**
     * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,
     * and then reverting unless the tokens plus a proportional protocol fee have been returned.
     *
     * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount
     * for each token contract. `tokens` must be sorted in ascending order.
     *
     * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the
     * `receiveFlashLoan` call.
     *
     * Emits `FlashLoan` events.
     */
    function flashLoan(
        IFlashLoanRecipient recipient,
        IERC20[] memory tokens,
        uint256[] memory amounts,
        bytes memory userData
    ) external;

    /**
     * @dev Emitted for each individual flash loan performed by `flashLoan`.
     */
    event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount);

    // Asset Management
    //
    // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's
    // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see
    // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly
    // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the
    // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore
    // not constrained to the tokens they are managing, but extends to the entire Pool's holdings.
    //
    // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit,
    // for example by lending unused tokens out for interest, or using them to participate in voting protocols.
    //
    // This concept is unrelated to the IAsset interface.

    /**
     * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates.
     *
     * Pool Balance management features batching, which means a single contract call can be used to perform multiple
     * operations of different kinds, with different Pools and tokens, at once.
     *
     * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`.
     */
    function managePoolBalance(PoolBalanceOp[] memory ops) external;

    struct PoolBalanceOp {
        PoolBalanceOpKind kind;
        bytes32 poolId;
        IERC20 token;
        uint256 amount;
    }

    /**
     * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged.
     *
     * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged.
     *
     * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total.
     * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss).
     */
    enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE }

    /**
     * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`.
     */
    event PoolBalanceManaged(
        bytes32 indexed poolId,
        address indexed assetManager,
        IERC20 indexed token,
        int256 cashDelta,
        int256 managedDelta
    );

    // Protocol Fees
    //
    // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by
    // permissioned accounts.
    //
    // There are two kinds of protocol fees:
    //
    //  - flash loan fees: charged on all flash loans, as a percentage of the amounts lent.
    //
    //  - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including
    // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather,
    // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the
    // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as
    // exiting a Pool in debt without first paying their share.

    /**
     * @dev Returns the current protocol fee module.
     */
    function getProtocolFeesCollector() external view returns (IProtocolFeesCollector);

    /**
     * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an
     * error in some part of the system.
     *
     * The Vault can only be paused during an initial time period, after which pausing is forever disabled.
     *
     * While the contract is paused, the following features are disabled:
     * - depositing and transferring internal balance
     * - transferring external balance (using the Vault's allowance)
     * - swaps
     * - joining Pools
     * - Asset Manager interactions
     *
     * Internal Balance can still be withdrawn, and Pools exited.
     */
    function setPaused(bool paused) external;

    /**
     * @dev Returns the Vault's WETH instance.
     */
    function WETH() external view returns (IWETH);
    // solhint-disable-previous-line func-name-mixedcase
}

// File: node_modules/@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol



// SPDX-License-Identifier: MIT

// Based on the Address library from OpenZeppelin Contracts, altered by removing the `isContract` checks on
// `functionCall` and `functionDelegateCall` in order to save gas, as the recipients are known to be contracts.

pragma solidity ^0.7.0;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    // solhint-disable max-line-length

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        _require(address(this).balance >= amount, Errors.ADDRESS_INSUFFICIENT_BALANCE);

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        _require(success, Errors.ADDRESS_CANNOT_SEND_VALUE);
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call(data);
        return verifyCallResult(success, returndata);
    }

    // solhint-enable max-line-length

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but passing some native ETH as msg.value to the call.
     *
     * _Available since v3.4._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return verifyCallResult(success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling up the
     * revert reason or using the one provided.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly
                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                _revert(Errors.LOW_LEVEL_CALL_FAILED);
            }
        }
    }
}

// File: node_modules/@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT

// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size.
// Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using
// private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size.

pragma solidity ^0.7.0;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol";

/**
 * @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 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;

    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 make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _enterNonReentrant();
        _;
        _exitNonReentrant();
    }

    function _enterNonReentrant() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        _require(_status != _ENTERED, Errors.REENTRANCY);

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

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