FTM Price: $1.03 (-2.24%)
Gas: 124 GWei

Contract

0x307b5093E125f2Eb15a8c6322EE2B06F101c0013
 

Overview

FTM Balance

Fantom LogoFantom LogoFantom Logo0 FTM

FTM Value

$0.00

Sponsored

Transaction Hash
Method
Block
From
To
Value
0x61018060585113912023-03-27 18:33:09366 days ago1679941989IN
 Contract Creation
0 FTM0.3030565654.64770684

Latest 2 internal transactions

Parent Txn Hash Block From To Value
585113912023-03-27 18:33:09366 days ago1679941989
0x307b5093...F101c0013
 Contract Creation0 FTM
585113912023-03-27 18:33:09366 days ago1679941989  Contract Creation0 FTM
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xb63EFE70...3C2f98883
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
BatchRelayerLibrary

Compiler Version
v0.7.1+commit.f4a555be

Optimization Enabled:
Yes with 9999 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 79 : BatchRelayerLibrary.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;
pragma experimental ABIEncoderV2;

import "./relayer/BaseRelayerLibrary.sol";

import "./relayer/AaveWrapping.sol";
import "./relayer/ERC4626Wrapping.sol";
import "./relayer/EulerWrapping.sol";
import "./relayer/GaugeActions.sol";
import "./relayer/GearboxWrapping.sol";
import "./relayer/LidoWrapping.sol";
import "./relayer/CompoundV2Wrapping.sol";
import "./relayer/UnbuttonWrapping.sol";
import "./relayer/ReaperWrapping.sol";
import "./relayer/TetuWrapping.sol";
import "./relayer/SiloWrapping.sol";
import "./relayer/BeefyWrapping.sol";
import "./relayer/MasterChefStaking.sol";
import "./relayer/FBeetsBarStaking.sol";
import "./relayer/BooMirrorWorldStaking.sol";
import "./relayer/ReliquaryStaking.sol";
import "./relayer/TarotWrapping.sol";
import "./relayer/VaultActions.sol";
import "./relayer/VaultPermit.sol";
import "./relayer/YearnWrapping.sol";

/**
 * @title Batch Relayer Library
 * @notice This contract is not a relayer by itself and calls into it directly will fail.
 * The associated relayer can be found by calling `getEntrypoint` on this contract.
 */
contract BatchRelayerLibrary is
    BaseRelayerLibrary,
    ERC4626Wrapping,
    GearboxWrapping,
    ReaperWrapping,
    BeefyWrapping,
    MasterChefStaking,
    BooMirrorWorldStaking,
    FBeetsBarStaking,
    ReliquaryStaking,
    TarotWrapping,
    VaultActions,
    VaultPermit,
    YearnWrapping
{
    constructor(
        IVault vault,
        IMasterChef masterChef,
        IBooMirrorWorld mirrorWorld,
        IFBeetsBar fBeetsBar,
        IReliquary reliquary
    )
        BaseRelayerLibrary(vault)
        MasterChefStaking(masterChef)
        BooMirrorWorldStaking(mirrorWorld)
        FBeetsBarStaking(fBeetsBar)
        ReliquaryStaking(reliquary)
    {
        // solhint-disable-previous-line no-empty-blocks
    }
}

File 2 of 79 : IBalancerMinter.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 "../solidity-utils/openzeppelin/IERC20.sol";

/**
 * @dev Base minter interface, applicable to Mainnet minter or L2 pseudo minters.
 */
interface IBalancerMinter {
    event Minted(address indexed recipient, address gauge, uint256 minted);

    /**
     * @notice Returns the address of the Balancer Governance Token
     */
    function getBalancerToken() external view returns (IERC20);

    /**
     * @notice Mint everything which belongs to `msg.sender` and send to them
     * @param gauge `LiquidityGauge` address to get mintable amount from
     */
    function mint(address gauge) external returns (uint256);

    /**
     * @notice Mint everything which belongs to `msg.sender` across multiple gauges
     * @param gauges List of `LiquidityGauge` addresses
     */
    function mintMany(address[] calldata gauges) external returns (uint256);

    /**
     * @notice Mint tokens for `user`
     * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf
     * @param gauge `LiquidityGauge` address to get mintable amount from
     * @param user Address to mint to
     */
    function mintFor(address gauge, address user) external returns (uint256);

    /**
     * @notice Mint tokens for `user` across multiple gauges
     * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf
     * @param gauges List of `LiquidityGauge` addresses
     * @param user Address to mint to
     */
    function mintManyFor(address[] calldata gauges, address user) external returns (uint256);

    /**
     * @notice The total number of tokens minted for `user` from `gauge`
     */
    function minted(address user, address gauge) external view returns (uint256);

    /**
     * @notice Whether `minter` is approved to mint tokens for `user`
     */
    function getMinterApproval(address minter, address user) external view returns (bool);

    /**
     * @notice Set whether `minter` is approved to mint tokens on your behalf
     */
    function setMinterApproval(address minter, bool approval) external;

    /**
     * @notice Set whether `minter` is approved to mint tokens on behalf of `user`, who has signed a message authorizing
     * them.
     */
    function setMinterApprovalWithSignature(
        address minter,
        bool approval,
        address user,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    // The below functions are near-duplicates of functions available above.
    // They are included for ABI compatibility with snake_casing as used in vyper contracts.
    // solhint-disable func-name-mixedcase

    /**
     * @notice Whether `minter` is approved to mint tokens for `user`
     */
    function allowed_to_mint_for(address minter, address user) external view returns (bool);

    /**
     * @notice Mint everything which belongs to `msg.sender` across multiple gauges
     * @dev This function is not recommended as `mintMany()` is more flexible and gas efficient
     * @param gauges List of `LiquidityGauge` addresses
     */
    function mint_many(address[8] calldata gauges) external;

    /**
     * @notice Mint tokens for `user`
     * @dev Only possible when `msg.sender` has been approved by `user` to mint on their behalf
     * @param gauge `LiquidityGauge` address to get mintable amount from
     * @param user Address to mint to
     */
    function mint_for(address gauge, address user) external;

    /**
     * @notice Toggle whether `minter` is approved to mint tokens for `user`
     */
    function toggle_approve_mint(address minter) external;
}

File 3 of 79 : IFBeetsBar.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;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-interfaces/contracts/pool-linear/ISushiBar.sol";

interface IFBeetsBar is ISushiBar {
    /**
     * @dev The BEETS token
     */
    function vestingToken() external view returns (IERC20);
}

File 4 of 79 : ILiquidityGauge.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;

// For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case
// naming convention.
// solhint-disable func-name-mixedcase
// solhint-disable func-param-name-mixedcase

interface ILiquidityGauge {
    // solhint-disable-next-line var-name-mixedcase
    event RelativeWeightCapChanged(uint256 new_relative_weight_cap);

    /**
     * @notice Returns BAL liquidity emissions calculated during checkpoints for the given user.
     * @param user User address.
     * @return uint256 BAL amount to issue for the address.
     */
    function integrate_fraction(address user) external view returns (uint256);

    /**
     * @notice Record a checkpoint for a given user.
     * @param user User address.
     * @return bool Always true.
     */
    function user_checkpoint(address user) external returns (bool);

    /**
     * @notice Returns true if gauge is killed; false otherwise.
     */
    function is_killed() external view returns (bool);

    /**
     * @notice Kills the gauge so it cannot mint BAL.
     */
    function killGauge() external;

    /**
     * @notice Unkills the gauge so it can mint BAL again.
     */
    function unkillGauge() external;

    /**
     * @notice Sets a new relative weight cap for the gauge.
     * The value shall be normalized to 1e18, and not greater than MAX_RELATIVE_WEIGHT_CAP.
     * @param relativeWeightCap New relative weight cap.
     */
    function setRelativeWeightCap(uint256 relativeWeightCap) external;

    /**
     * @notice Gets the relative weight cap for the gauge.
     */
    function getRelativeWeightCap() external view returns (uint256);

    /**
     * @notice Returns the gauge's relative weight for a given time, capped to its relative weight cap attribute.
     * @param time Timestamp in the past or present.
     */
    function getCappedRelativeWeight(uint256 time) external view returns (uint256);
}

File 5 of 79 : IMasterChef.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;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";

interface IMasterChef {
    /// @notice Address of the LP token for each MCV pool.
    function lpTokens(uint256 idx) external view returns (IERC20);

    /**
     * @notice Deposit LP tokens to MasterChef for reward allocation.
     * @param _pid The index of the pool. See `poolInfo`.
     * @param _amount LP token amount to deposit.
     * @param _to Address to deposit the tokens on behalf of.
     **/
    function deposit(
        uint256 _pid,
        uint256 _amount,
        address _to
    ) external;

    /**
     * @notice Withdraw LP tokens from MasterChef and harvest proceeds for transaction sender to `_to`.
     * @param _pid The index of the pool. See `poolInfo`.
     * @param _amount LP token amount to withdraw.
     * @param _to Receiver of the LP tokens and BEETS rewards.
     **/
    function withdrawAndHarvest(
        uint256 _pid,
        uint256 _amount,
        address _to
    ) external;
}

File 6 of 79 : IReliquary.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC721Enumerable.sol";

interface IEmissionCurve {
    function getRate(uint256 lastRewardTime) external view returns (uint256 rate);
}

interface INFTDescriptor {
    function constructTokenURI(uint256 relicId) external view returns (string memory);
}

/**
 * @notice Info for each Reliquary position.
 * `amount` LP token amount the position owner has provided.
 * `rewardDebt` Amount of reward token accumalated before the position's entry or last harvest.
 * `rewardCredit` Amount of reward token owed to the user on next harvest.
 * `entry` Used to determine the maturity of the position.
 * `poolId` ID of the pool to which this position belongs.
 * `level` Index of this position's level within the pool's array of levels.
 */
struct PositionInfo {
    uint amount;
    uint rewardDebt;
    uint rewardCredit;
    uint entry; // position owner's relative entry into the pool.
    uint poolId; // ensures that a single Relic is only used for one pool.
    uint level;
}

/**
 * @notice Info of each Reliquary pool.
 * `accRewardPerShare` Accumulated reward tokens per share of pool (1 / 1e12).
 * `lastRewardTime` Last timestamp the accumulated reward was updated.
 * `allocPoint` Pool's individual allocation - ratio of the total allocation.
 * `name` Name of pool to be displayed in NFT image.
 */
struct PoolInfo {
    uint accRewardPerShare;
    uint lastRewardTime;
    uint allocPoint;
    string name;
}

/**
 * @notice Info for each level in a pool that determines how maturity is rewarded.
 * `requiredMaturities` The minimum maturity (in seconds) required to reach each Level.
 * `multipliers` Multiplier for each level applied to amount of incentivized token when calculating rewards in the pool.
 *     This is applied to both the numerator and denominator in the calculation such that the size of a user's position
 *     is effectively considered to be the actual number of tokens times the multiplier for their level.
 *     Also note that these multipliers do not affect the overall emission rate.
 * `balance` Total (actual) number of tokens deposited in positions at each level.
 */
struct LevelInfo {
    uint[] requiredMaturities;
    uint[] multipliers;
    uint[] balance;
}

/**
 * @notice Object representing pending rewards and related data for a position.
 * `relicId` The NFT ID of the given position.
 * `poolId` ID of the pool to which this position belongs.
 * `pendingReward` pending reward amount for a given position.
 */
struct PendingReward {
    uint relicId;
    uint poolId;
    uint pendingReward;
}

interface IReliquary is IERC721Enumerable {
    function setEmissionCurve(address _emissionCurve) external;
    function addPool(
        uint allocPoint,
        address _poolToken,
        address _rewarder,
        uint[] calldata requiredMaturity,
        uint[] calldata allocPoints,
        string memory name,
        address _nftDescriptor
    ) external;
    function modifyPool(
        uint pid,
        uint allocPoint,
        address _rewarder,
        string calldata name,
        address _nftDescriptor,
        bool overwriteRewarder
    ) external;
    function massUpdatePools(uint[] calldata pids) external;
    function updatePool(uint pid) external;
    function deposit(uint amount, uint relicId) external;
    function withdraw(uint amount, uint relicId) external;
    function harvest(uint relicId, address harvestTo) external;
    function withdrawAndHarvest(uint amount, uint relicId, address harvestTo) external;
    function emergencyWithdraw(uint relicId) external;
    function updatePosition(uint relicId) external;
    function getPositionForId(uint) external view returns (PositionInfo memory);
    function getPoolInfo(uint) external view returns (PoolInfo memory);
    function getLevelInfo(uint) external view returns (LevelInfo memory);
    function pendingRewardsOfOwner(address owner) external view returns (PendingReward[] memory pendingRewards);
    function relicPositionsOfOwner(address owner)
        external
        view
        returns (uint[] memory relicIds, PositionInfo[] memory positionInfos);
    function isApprovedOrOwner(address, uint) external view returns (bool);
    function createRelicAndDeposit(address to, uint pid, uint amount) external returns (uint id);
    // function split(uint relicId, uint amount, address to) external returns (uint newId);
    // function shift(uint fromId, uint toId, uint amount) external;
    // function merge(uint fromId, uint toId) external;
    function burn(uint tokenId) external;
    function pendingReward(uint relicId) external view returns (uint pending);
    function levelOnUpdate(uint relicId) external view returns (uint level);
    function poolLength() external view returns (uint);

    function rewardToken() external view returns (address);
    function nftDescriptor(uint) external view returns (address);
    function emissionCurve() external view returns (address);
    function poolToken(uint) external view returns (address);
    function rewarder(uint) external view returns (address);
    function totalAllocPoint() external view returns (uint);
}

File 7 of 79 : IReliquaryRewarder.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";

interface IRewarder {
    function onReward(
        uint256 relicId,
        uint256 rewardAmount,
        address to
    ) external;

    function onDeposit(uint256 relicId, uint256 depositAmount) external;

    function onWithdraw(uint256 relicId, uint256 withdrawalAmount) external;

    function pendingTokens(uint256 relicId, uint256 rewardAmount)
        external
        view
        returns (IERC20[] memory, uint256[] memory);
}

File 8 of 79 : IRewardTokenDistributor.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";

// For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case
// naming convention.
// solhint-disable func-name-mixedcase, var-name-mixedcase

interface IRewardTokenDistributor {
    struct Reward {
        IERC20 token;
        address distributor;
        uint256 period_finish;
        uint256 rate;
        uint256 last_update;
        uint256 integral;
    }

    function reward_tokens(uint256 index) external view returns (IERC20);

    function reward_data(IERC20 token) external view returns (Reward memory);

    function claim_rewards(address user) external;

    function add_reward(IERC20 rewardToken, address distributor) external;

    function set_reward_distributor(IERC20 rewardToken, address distributor) external;

    function deposit_reward_token(IERC20 rewardToken, uint256 amount) external;

    function claimable_reward(address rewardToken, address user) external view returns (uint256);

    function claimable_reward_write(address rewardToken, address user) external returns (uint256);
}

File 9 of 79 : IStakingLiquidityGauge.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 "./ILiquidityGauge.sol";
import "./IRewardTokenDistributor.sol";

// For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case
// naming convention.
// solhint-disable func-name-mixedcase, var-name-mixedcase

interface IStakingLiquidityGauge is IRewardTokenDistributor, ILiquidityGauge, IERC20 {
    function initialize(address lpToken, uint256 relativeWeightCap) external;

    function lp_token() external view returns (IERC20);

    function deposit(uint256 value, address recipient) external;

    function withdraw(uint256 value) external;
}

File 10 of 79 : IBeefyVault.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;

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

// Source: https://github.com/beefyfinance/beefy-contracts/blob/master/contracts/BIFI/vaults/BeefyVaultV6.sol
// Interface definition for the BeefyVaultV6 contract
// pricePerFullShare is always represented with 18 decimals,
// regardless of the underlying token decimals.
// ie: If ppfs === 1e18, 1 USDC === 0.000_000_000_001_000_000 mooUSDC
// ie: If ppfs === 1e18, 1 DAI === 1 mooDAI
interface IBeefyVault is IERC20 {
    /**
     * @dev returns the address of the vault's underlying asset (mainToken)
     */
    function want() external view returns (address);

    /**
     * @dev returns the price for a single Vault share (ie mooUSDT). The getPricePerFullShare is always in 1e18
     */
    function getPricePerFullShare() external view returns (uint256);

    /**
     * @dev total amount of underlying want that is in the Beefy Strategy
     */
    function balance() external view returns (uint256);

    /**
     * @notice Deposits `_amount` `token`, issuing shares to the caller.
     * If Panic is activated, deposits will not be accepted and this call will fail.
     * @param _amount The quantity of tokens to deposit.
     **/
    function deposit(uint256 _amount) external;

    /**
     * @notice Withdraws the calling account's tokens from this Vault,
     * redeeming amount `_shares` for an appropriate amount of tokens.
     **/
    function withdraw(uint256 _shares) external;

    /**
     * @dev returns the number of decimals for this vault token.
     * For beefy vaults, the decimals are fixed to 18.
     */
    function decimals() external view returns (uint8);
}

File 11 of 79 : IBooMirrorWorld.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;

import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import "./ISushiBar.sol";

interface IBooMirrorWorld is ISushiBar {
    /**
     * @dev The BOO token
     */
    function boo() external view returns (IERC20);

    /**
     * @dev returns how much BOO someone gets for redeeming xBOO
     */
    function xBOOForBOO(uint256 amount) external view returns (uint256);
}

File 12 of 79 : ISushiBar.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;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";

interface ISushiBar is IERC20 {
    /**
     * @notice Deposit tokens to the SushiBar and receive xSUSHI tokens in return.
     * @param _amount token amount to deposit.
     **/
    function enter(uint256 _amount) external;

    /**
     * @notice Withdraw LP tokens from MasterChef and harvest proceeds for transaction sender to `_to`.
     * @param _share The amount of x tokens to burn
     **/
    function leave(uint256 _share) external;
}

File 13 of 79 : ITarotSupplyVault.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;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";

import "./ISushiBar.sol";

interface ITarotSupplyVault is ISushiBar {
    function getBorrowablesLength() external view returns (uint256);

    function borrowables(uint256) external view returns (address);

    function underlying() external view returns (IERC20);
}

File 14 of 79 : StablePoolUserData.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;

library StablePoolUserData {
    enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT }
    enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT, EXACT_BPT_IN_FOR_ALL_TOKENS_OUT }

    function joinKind(bytes memory self) internal pure returns (JoinKind) {
        return abi.decode(self, (JoinKind));
    }

    function exitKind(bytes memory self) internal pure returns (ExitKind) {
        return abi.decode(self, (ExitKind));
    }

    // Joins

    function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) {
        (, amountsIn) = abi.decode(self, (JoinKind, uint256[]));
    }

    function exactTokensInForBptOut(bytes memory self)
        internal
        pure
        returns (uint256[] memory amountsIn, uint256 minBPTAmountOut)
    {
        (, amountsIn, minBPTAmountOut) = abi.decode(self, (JoinKind, uint256[], uint256));
    }

    function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) {
        (, bptAmountOut, tokenIndex) = abi.decode(self, (JoinKind, uint256, uint256));
    }

    function allTokensInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut) {
        (, bptAmountOut) = abi.decode(self, (JoinKind, uint256));
    }

    // Exits

    function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) {
        (, bptAmountIn, tokenIndex) = abi.decode(self, (ExitKind, uint256, uint256));
    }

    function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) {
        (, bptAmountIn) = abi.decode(self, (ExitKind, uint256));
    }

    function bptInForExactTokensOut(bytes memory self)
        internal
        pure
        returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn)
    {
        (, amountsOut, maxBPTAmountIn) = abi.decode(self, (ExitKind, uint256[], uint256));
    }
}

File 15 of 79 : WeightedPoolUserData.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 "../solidity-utils/openzeppelin/IERC20.sol";

library WeightedPoolUserData {
    // In order to preserve backwards compatibility, make sure new join and exit kinds are added at the end of the enum.
    enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT }
    enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }

    function joinKind(bytes memory self) internal pure returns (JoinKind) {
        return abi.decode(self, (JoinKind));
    }

    function exitKind(bytes memory self) internal pure returns (ExitKind) {
        return abi.decode(self, (ExitKind));
    }

    // Joins

    function initialAmountsIn(bytes memory self) internal pure returns (uint256[] memory amountsIn) {
        (, amountsIn) = abi.decode(self, (JoinKind, uint256[]));
    }

    function exactTokensInForBptOut(bytes memory self)
        internal
        pure
        returns (uint256[] memory amountsIn, uint256 minBPTAmountOut)
    {
        (, amountsIn, minBPTAmountOut) = abi.decode(self, (JoinKind, uint256[], uint256));
    }

    function tokenInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut, uint256 tokenIndex) {
        (, bptAmountOut, tokenIndex) = abi.decode(self, (JoinKind, uint256, uint256));
    }

    function allTokensInForExactBptOut(bytes memory self) internal pure returns (uint256 bptAmountOut) {
        (, bptAmountOut) = abi.decode(self, (JoinKind, uint256));
    }

    // Exits

    function exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) {
        (, bptAmountIn, tokenIndex) = abi.decode(self, (ExitKind, uint256, uint256));
    }

    function exactBptInForTokensOut(bytes memory self) internal pure returns (uint256 bptAmountIn) {
        (, bptAmountIn) = abi.decode(self, (ExitKind, uint256));
    }

    function bptInForExactTokensOut(bytes memory self)
        internal
        pure
        returns (uint256[] memory amountsOut, uint256 maxBPTAmountIn)
    {
        (, amountsOut, maxBPTAmountIn) = abi.decode(self, (ExitKind, uint256[], uint256));
    }
}

File 16 of 79 : 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 17 of 79 : 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 18 of 79 : 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 19 of 79 : 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 20 of 79 : IERC4626.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";

interface IERC4626 is IERC20 {
    /**
     * @dev `caller` has exchanged `assets` for `shares`, and transferred those `shares` to `owner`.
     */
    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);

    /**
     * @dev `caller` has exchanged `shares`, owned by `owner`, for `assets`,
     *      and transferred those `assets` to `receiver`.
     */
    event Withdraw(
        address indexed caller,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Mints `shares` Vault shares to `receiver` by depositing exactly `amount` of underlying tokens.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Burns exactly `shares` from `owner` and sends `assets` of underlying tokens to `receiver`.
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);

    /**
     * @dev The address of the underlying token that the Vault uses for accounting, depositing, and withdrawing.
     */
    function asset() external view returns (address);

    /**
     * @dev Total amount of the underlying asset that is “managed” by Vault.
     */
    function totalAssets() external view returns (uint256);

    /**
     * @dev The amount of `assets` that the Vault would exchange for the amount
     *      of `shares` provided, in an ideal scenario where all the conditions are met.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev The amount of `shares` that the Vault would exchange for the amount
     *      of `assets` provided, in an ideal scenario where all the conditions are met.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block,
     * given current on-chain conditions. MUST return as close to and no fewer than the exact amount of assets that
     * would be deposited in a mint call in the same transaction. I.e. mint should return the same or fewer assets
     * as previewMint if called in the same transaction.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);
}

File 21 of 79 : 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 22 of 79 : IERC165.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 23 of 79 : 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 24 of 79 : IERC20Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
     * given `owner`'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 25 of 79 : IERC20PermitDAI.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.7.0 <0.9.0;

interface IERC20PermitDAI {
    /**
     * @notice update allowance with a signed permit
     * @param holder    Token owner's address (Authorizer)
     * @param spender   Spender's address
     * @param nonce     The permit nonce
     * @param expiry    The time at which this expires (unix time)
     * @param allowed   Whether the spender is allowed or disallowed from spending
     * @param v         v of the signature
     * @param r         r of the signature
     * @param s         s of the signature
     */
    function permit(
        address holder,
        address spender,
        uint256 nonce,
        uint256 expiry,
        bool allowed,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

File 26 of 79 : IERC721.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "./IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

File 27 of 79 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.2 <0.8.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {

    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

File 28 of 79 : IBalancerRelayer.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 "../vault/IVault.sol";

/**
 * @title IBalancerRelayer
 * @notice Allows safe multicall execution of a relayer's functions
 */
interface IBalancerRelayer {
    function getLibrary() external view returns (address);

    function getVault() external view returns (IVault);

    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

File 29 of 79 : IButtonWrapper.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;

// Source: https://github.com/buttonwood-protocol/button-wrappers/blob/main/contracts/interfaces/IButtonWrapper.sol
// Interface definition for ButtonWrapper contract, which wraps an
// underlying ERC20 token into a new ERC20 with different characteristics.
// NOTE: "uAmount" => underlying token (wrapped) amount and
//       "amount" => wrapper token amount
interface IButtonWrapper {
    //--------------------------------------------------------------------------
    // ButtonWrapper write methods

    /// @notice Transfers underlying tokens from {msg.sender} to the contract and
    ///         mints wrapper tokens.
    /// @param amount The amount of wrapper tokens to mint.
    /// @return The amount of underlying tokens deposited.
    function mint(uint256 amount) external returns (uint256);

    /// @notice Transfers underlying tokens from {msg.sender} to the contract and
    ///         mints wrapper tokens to the specified beneficiary.
    /// @param to The beneficiary account.
    /// @param amount The amount of wrapper tokens to mint.
    /// @return The amount of underlying tokens deposited.
    function mintFor(address to, uint256 amount) external returns (uint256);

    /// @notice Burns wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back.
    /// @param amount The amount of wrapper tokens to burn.
    /// @return The amount of underlying tokens withdrawn.
    function burn(uint256 amount) external returns (uint256);

    /// @notice Burns wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens to the specified beneficiary.
    /// @param to The beneficiary account.
    /// @param amount The amount of wrapper tokens to burn.
    /// @return The amount of underlying tokens withdrawn.
    function burnTo(address to, uint256 amount) external returns (uint256);

    /// @notice Burns all wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back.
    /// @return The amount of underlying tokens withdrawn.
    function burnAll() external returns (uint256);

    /// @notice Burns all wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back.
    /// @param to The beneficiary account.
    /// @return The amount of underlying tokens withdrawn.
    function burnAllTo(address to) external returns (uint256);

    /// @notice Transfers underlying tokens from {msg.sender} to the contract and
    ///         mints wrapper tokens to the specified beneficiary.
    /// @param uAmount The amount of underlying tokens to deposit.
    /// @return The amount of wrapper tokens mint.
    function deposit(uint256 uAmount) external returns (uint256);

    /// @notice Transfers underlying tokens from {msg.sender} to the contract and
    ///         mints wrapper tokens to the specified beneficiary.
    /// @param to The beneficiary account.
    /// @param uAmount The amount of underlying tokens to deposit.
    /// @return The amount of wrapper tokens mint.
    function depositFor(address to, uint256 uAmount) external returns (uint256);

    /// @notice Burns wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back.
    /// @param uAmount The amount of underlying tokens to withdraw.
    /// @return The amount of wrapper tokens burnt.
    function withdraw(uint256 uAmount) external returns (uint256);

    /// @notice Burns wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back to the specified beneficiary.
    /// @param to The beneficiary account.
    /// @param uAmount The amount of underlying tokens to withdraw.
    /// @return The amount of wrapper tokens burnt.
    function withdrawTo(address to, uint256 uAmount) external returns (uint256);

    /// @notice Burns all wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back.
    /// @return The amount of wrapper tokens burnt.
    function withdrawAll() external returns (uint256);

    /// @notice Burns all wrapper tokens from {msg.sender} and transfers
    ///         the underlying tokens back.
    /// @param to The beneficiary account.
    /// @return The amount of wrapper tokens burnt.
    function withdrawAllTo(address to) external returns (uint256);

    //--------------------------------------------------------------------------
    // ButtonWrapper view methods

    /// @return The address of the underlying token.
    function underlying() external view returns (address);

    /// @return The total underlying tokens held by the wrapper contract.
    function totalUnderlying() external view returns (uint256);

    /// @param who The account address.
    /// @return The underlying token balance of the account.
    function balanceOfUnderlying(address who) external view returns (uint256);

    /// @param uAmount The amount of underlying tokens.
    /// @return The amount of wrapper tokens exchangeable.
    function underlyingToWrapper(uint256 uAmount) external view returns (uint256);

    /// @param amount The amount of wrapper tokens.
    /// @return The amount of underlying tokens exchangeable.
    function wrapperToUnderlying(uint256 amount) external view returns (uint256);
}

File 30 of 79 : ICToken.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;

// Interface for MidasCapital. An open interest protocol based on
// modified Fuse contracts. Anyone can create an deploy isolated
// lending and borrowing pools with custom parameters.

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

interface ICToken is IERC20 {
    // Error codes referenced in this file can be found here:
    // https://github.com/compound-finance/compound-protocol/blob/a3214f67b73310d547e00fc578e8355911c9d376/contracts/ErrorReporter.sol
    // solhint-disable-previous-line max-line-length

    /**
     * @dev Underlying asset for this CToken
     */
    function underlying() external view returns (address);

    /**
     * @notice Sender supplies assets into the market and receives cTokens in exchange
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param mintAmount The amount of the underlying asset to supply
     * @return uint 0=success, otherwise an error code (see ErrorReporter.sol link above for details)
     */
    function mint(uint256 mintAmount) external returns (uint256);

    /**
     * @notice Sender redeems cTokens in exchange for the underlying asset
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param redeemTokens The number of cTokens to redeem into underlying
     * @return uint 0=success, otherwise an error code (see ErrorReporter.sol link above for details)
     */
    function redeem(uint256 redeemTokens) external returns (uint256);
}

File 31 of 79 : IEulerToken.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;

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

interface IEulerToken is IERC20 {
    /**
     * @dev Convert an eToken balance to an underlying amount, taking into account current exchange rate
     * @param balance eToken balance, in internal book-keeping units (18 decimals)
     * @return Amount in underlying units, (same decimals as underlying token)
     */
    // https://github.com/euler-xyz/euler-contracts/blob/b1ee3265853628d5a529081d7908c38404201b4e/contracts/modules/EToken.sol#L104
    // solhint-disable-previous-line max-line-length
    function convertBalanceToUnderlying(uint256 balance) external view returns (uint256);

    /**
     * @dev Convert an underlying amount to an eToken balance, taking into account current exchange rate
     * @param underlyingAmount Amount in underlying units (same decimals as underlying token)
     * @return eToken balance, in internal book-keeping units (18 decimals)
     */
    // https://github.com/euler-xyz/euler-contracts/blob/b1ee3265853628d5a529081d7908c38404201b4e/contracts/modules/EToken.sol#L114
    // solhint-disable-previous-line max-line-length
    function convertUnderlyingToBalance(uint256 underlyingAmount) external view returns (uint256);

    /**
     * @dev Transfer underlying tokens from sender to the Euler pool, and increase account's eTokens
     */
    function deposit(uint256 subAccountId, uint256 amount) external;

    /**
     * @dev Transfer underlying tokens from Euler pool to sender, and decrease account's eTokens
     */
    function withdraw(uint256 subAccountId, uint256 amount) external;

    /**
     * @dev Address of underlying asset
     */
    function underlyingAsset() external view returns (address);
}

File 32 of 79 : IGearboxDieselToken.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 "../solidity-utils/openzeppelin/IERC20.sol";

interface IGearboxDieselToken is IERC20 {
    /**
     * @dev returns the address of the vault
     */
    function owner() external view returns (address);
}

interface IGearboxVault {
    /**
     * @dev returns the address of the underlying asset
     */
    function underlyingToken() external view returns (address);

    /**
     * @dev returns a 27 decimal fixed point 'ray' value so a rate of 1 is represented as 1e27
     */
    // solhint-disable-next-line func-name-mixedcase
    function getDieselRate_RAY() external view returns (uint256);

    /**
     * @dev converts diesel token amount to main token amount
     */
    function fromDiesel(uint256) external view returns (uint256);

    /**
     * @dev converts main token amount to diesel token amount
     */
    function toDiesel(uint256) external view returns (uint256);

    /**
     * @dev Adds liquidity to pool and sends diesel (LP) tokens back to the liquidity provider
     * The Referral code can be 0
     */
    function addLiquidity(
        uint256 underlyingAmount,
        address onBehalfOf,
        uint256 referralCode
    ) external;

    /**
     * @dev Removes liquidity from the pool and sends the underlying tokens to the `to` address
     */
    function removeLiquidity(uint256 dieselAmount, address to) external;
}

File 33 of 79 : IReaperTokenVault.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;

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

// Source: https://github.com/Byte-Masons/beet-strat/blob/master/contracts/ReaperVaultv1_4.sol
// Interface definition for the ReaperTokenVault contract, a single strategy vault
// for Reaper Farm crypts. The pricePerFullShare is always represented with 18 decimals,
// regardless of the underlying token decimals.
// ie: If ppfs === 1e18, 1 USDC === 0.000_000_000_001_000_000 rfUSDC
// ie: If ppfs === 1e18, 1 DAI === 1 rfDAI
interface IReaperTokenVault is IERC20 {
    /**
     * @dev returns the address of the vault's underlying asset (mainToken)
     */
    function token() external view returns (address);

    /**
     * @dev returns the balance of mainToken deposited to the vault
     */
    function balance() external view returns (uint256);

    /**
     * @dev returns the price for a single Vault share (ie rf-scfUSDT). The getPricePerFullShare is always in 1e18
     */
    function getPricePerFullShare() external view returns (uint256);

    /**
     * @notice Deposits `_amount` `token`, issuing shares to the caller.
     * If Panic is activated, deposits will not be accepted and this call will fail.
     * @param _amount The quantity of tokens to deposit.
     **/
    function deposit(uint256 _amount) external;

    /**
     * @notice Withdraws the calling account's tokens from this Vault,
     * redeeming amount `_shares` for an appropriate amount of tokens.
     **/
    function withdraw(uint256 _shares) external;

    /**
     * @dev returns the number of decimals for this vault token.
     * For reaper single-strat vaults, the decimals are fixed to 18.
     */
    function decimals() external view returns (uint8);
}

File 34 of 79 : IShareToken.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 "../solidity-utils/openzeppelin/IERC20.sol";

import "./ISilo.sol";

interface IShareToken is IERC20 {
    /**
     * @dev returns the underlying asset
     */
    function asset() external view returns (address);

    /**
     * @dev returns the address of the silo
     */
    function silo() external view returns (ISilo);
}

File 35 of 79 : ISilo.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 "./IShareToken.sol";

interface IBaseSilo {
    /// Storage struct that holds all required data for a single token market
    struct AssetStorage {
        // Token that represents a share in totalDeposits of Silo
        IShareToken collateralToken;
        // Token that represents a share in collateralOnlyDeposits of Silo
        IShareToken collateralOnlyToken;
        // Token that represents a share in totalBorrowAmount of Silo
        IShareToken debtToken;
        // COLLATERAL: Amount of asset token that has been deposited to Silo with interest earned by depositors.
        // It also includes token amount that has been borrowed.
        uint256 totalDeposits;
        // COLLATERAL ONLY: Amount of asset token that has been deposited to Silo that can ONLY be used
        // as collateral. These deposits do NOT earn interest and CANNOT be borrowed.
        uint256 collateralOnlyDeposits;
        // DEBT: Amount of asset token that has been borrowed with accrued interest.
        uint256 totalBorrowAmount;
    }

    /**
     * @dev returns the asset storage struct
     * @dev AssetStorage struct contains necessary information for calculating shareToken exchange rates
     */
    function assetStorage(address _asset) external view returns (AssetStorage memory);
}

interface ISilo is IBaseSilo {
    /**
     * @dev Deposits funds into the Silo
     * @param _asset The address of the token to deposit
     * @param _depositor The address of the recipient of collateral tokens
     * @param _amount The amount of the token to deposit
     * @param _collateralOnly: True means your shareToken is protected (cannot be swapped for interest)
     * @return collateralAmount deposited amount
     * @return collateralShare user collateral shares based on deposited amount
     */
    function depositFor(
        address _asset,
        address _depositor,
        uint256 _amount,
        bool _collateralOnly
    ) external returns (uint256 collateralAmount, uint256 collateralShare);

    /**
     * @dev Withdraw `_amount` of `_asset` tokens from the Silo to `msg.sender`
     * @param _asset The address of the token to withdraw
     * @param _amount The amount of the token to withdraw
     * @param _collateralOnly True if withdrawing collateral only deposit
     * @return withdrawnAmount withdrawn amount that was transferred to user
     * @return withdrawnShare burned share based on `withdrawnAmount`
     */
    function withdraw(
        address _asset,
        uint256 _amount,
        bool _collateralOnly
    ) external returns (uint256 withdrawnAmount, uint256 withdrawnShare);
}

File 36 of 79 : IStaticATokenLM.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;

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

// solhint-disable-next-line max-line-length
// Based on https://github.com/aave/protocol-v2/blob/ac58fea62bb8afee23f66197e8bce6d79ecda292/contracts/interfaces/IStaticATokenLM.sol

interface IStaticATokenLM is IERC20 {
    struct SignatureParams {
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    /**
     * @notice Deposits `ASSET` in the Aave protocol and mints static aTokens to msg.sender
     * @param recipient The address that will receive the static aTokens
     * @param amount The amount of underlying `ASSET` to deposit (e.g. deposit of 100 USDC)
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     * @param fromUnderlying bool
     * - `true` if the msg.sender comes with underlying tokens (e.g. USDC)
     * - `false` if the msg.sender comes already with aTokens (e.g. aUSDC)
     * @return uint256 The amount of StaticAToken minted, static balance
     **/
    function deposit(
        address recipient,
        uint256 amount,
        uint16 referralCode,
        bool fromUnderlying
    ) external returns (uint256);

    /**
     * @notice Burns `amount` of static aToken, with recipient receiving the corresponding amount of `ASSET`
     * @param recipient The address that will receive the amount of `ASSET` withdrawn from the Aave protocol
     * @param amount The amount to withdraw, in static balance of StaticAToken
     * @param toUnderlying bool
     * - `true` for the recipient to get underlying tokens (e.g. USDC)
     * - `false` for the recipient to get aTokens (e.g. aUSDC)
     * @return amountToBurn: StaticATokens burnt, static balance
     * @return amountToWithdraw: underlying/aToken send to `recipient`, dynamic balance
     **/
    function withdraw(
        address recipient,
        uint256 amount,
        bool toUnderlying
    ) external returns (uint256, uint256);

    /**
     * @notice Burns `amount` of static aToken, with recipient receiving the corresponding amount of `ASSET`
     * @param recipient The address that will receive the amount of `ASSET` withdrawn from the Aave protocol
     * @param amount The amount to withdraw, in dynamic balance of aToken/underlying asset
     * @param toUnderlying bool
     * - `true` for the recipient to get underlying tokens (e.g. USDC)
     * - `false` for the recipient to get aTokens (e.g. aUSDC)
     * @return amountToBurn: StaticATokens burnt, static balance
     * @return amountToWithdraw: underlying/aToken send to `recipient`, dynamic balance
     **/
    function withdrawDynamicAmount(
        address recipient,
        uint256 amount,
        bool toUnderlying
    ) external returns (uint256, uint256);

    /**
     * @notice Implements the permit function as for
     * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
     * @param owner The owner of the funds
     * @param spender The spender
     * @param value The amount
     * @param deadline The deadline timestamp, type(uint256).max for max deadline
     * @param v Signature param
     * @param s Signature param
     * @param r Signature param
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @notice Allows to deposit on Aave via meta-transaction
     * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
     * @param depositor Address from which the funds to deposit are going to be pulled
     * @param recipient Address that will receive the staticATokens, in the average case, same as the `depositor`
     * @param value The amount to deposit
     * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
     *   0 if the action is executed directly by the user, without any middle-man
     * @param fromUnderlying bool
     * - `true` if the msg.sender comes with underlying tokens (e.g. USDC)
     * - `false` if the msg.sender comes already with aTokens (e.g. aUSDC)
     * @param deadline The deadline timestamp, type(uint256).max for max deadline
     * @param sigParams Signature params: v,r,s
     * @return uint256 The amount of StaticAToken minted, static balance
     */
    function metaDeposit(
        address depositor,
        address recipient,
        uint256 value,
        uint16 referralCode,
        bool fromUnderlying,
        uint256 deadline,
        SignatureParams calldata sigParams
    ) external returns (uint256);

    /**
     * @notice Allows to withdraw from Aave via meta-transaction
     * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
     * @param owner Address owning the staticATokens
     * @param recipient Address that will receive the underlying withdrawn from Aave
     * @param staticAmount The amount of staticAToken to withdraw. If > 0, `dynamicAmount` needs to be 0
     * @param dynamicAmount The amount of underlying/aToken to withdraw. If > 0, `staticAmount` needs to be 0
     * @param toUnderlying bool
     * - `true` for the recipient to get underlying tokens (e.g. USDC)
     * - `false` for the recipient to get aTokens (e.g. aUSDC)
     * @param deadline The deadline timestamp, type(uint256).max for max deadline
     * @param sigParams Signature params: v,r,s
     * @return amountToBurn: StaticATokens burnt, static balance
     * @return amountToWithdraw: underlying/aToken send to `recipient`, dynamic balance
     */
    function metaWithdraw(
        address owner,
        address recipient,
        uint256 staticAmount,
        uint256 dynamicAmount,
        bool toUnderlying,
        uint256 deadline,
        SignatureParams calldata sigParams
    ) external returns (uint256, uint256);

    /**
     * @notice Utility method to get the current aToken balance of an user, from his staticAToken balance
     * @param account The address of the user
     * @return uint256 The aToken balance
     **/
    function dynamicBalanceOf(address account) external view returns (uint256);

    /**
     * @notice Converts a static amount (scaled balance on aToken) to the aToken/underlying value,
     * using the current liquidity index on Aave
     * @param amount The amount to convert from
     * @return uint256 The dynamic amount
     **/
    function staticToDynamicAmount(uint256 amount) external view returns (uint256);

    /**
     * @notice Converts an aToken or underlying amount to the what it is denominated on the aToken as
     * scaled balance, function of the principal and the liquidity index
     * @param amount The amount to convert from
     * @return uint256 The static (scaled) amount
     **/
    function dynamicToStaticAmount(uint256 amount) external view returns (uint256);

    /**
     * @notice Returns the Aave liquidity index of the underlying aToken, denominated rate here
     * as it can be considered as an ever-increasing exchange rate
     * @return The liquidity index
     **/
    function rate() external view returns (uint256);

    /**
     * @notice Function to return a dynamic domain separator, in order to be compatible with forks changing chainId
     * @return bytes32 The domain separator
     **/
    function getDomainSeparator() external view returns (bytes32);

    /**
     * @notice Claims rewards from `INCENTIVES_CONTROLLER` and updates internal accounting of rewards.
     */
    function collectAndUpdateRewards() external;

    /**
     * @notice Claim rewards on behalf of a user and send them to a receiver
     * @dev Only callable by if sender is onBehalfOf or sender is approved claimer
     * @param onBehalfOf The address to claim on behalf of
     * @param receiver The address to receive the rewards
     * @param forceUpdate Flag to retrieve latest rewards from `INCENTIVES_CONTROLLER`
     */
    function claimRewardsOnBehalf(
        address onBehalfOf,
        address receiver,
        bool forceUpdate
    ) external;

    /**
     * @notice Claim rewards and send them to a receiver
     * @param receiver The address to receive the rewards
     * @param forceUpdate Flag to retrieve latest rewards from `INCENTIVES_CONTROLLER`
     */
    function claimRewards(address receiver, bool forceUpdate) external;

    /**
     * @notice Claim rewards
     * @param forceUpdate Flag to retrieve latest rewards from `INCENTIVES_CONTROLLER`
     */
    function claimRewardsToSelf(bool forceUpdate) external;

    /**
     * @notice Get the total claimable rewards of the contract.
     * @return The current balance + pending rewards from the `_incentivesController`
     */
    function getTotalClaimableRewards() external view returns (uint256);

    /**
     * @notice Get the total claimable rewards for a user in WAD
     * @param user The address of the user
     * @return The claimable amount of rewards in WAD
     */
    function getClaimableRewards(address user) external view returns (uint256);

    /**
     * @notice The unclaimed rewards for a user in WAD
     * @param user The address of the user
     * @return The unclaimed amount of rewards in WAD
     */
    function getUnclaimedRewards(address user) external view returns (uint256);

    function getAccRewardsPerToken() external view returns (uint256);

    function getLifetimeRewardsClaimed() external view returns (uint256);

    function getLifetimeRewards() external view returns (uint256);

    function getLastRewardBlock() external view returns (uint256);

    // solhint-disable-next-line func-name-mixedcase
    function LENDING_POOL() external returns (address);

    // solhint-disable-next-line func-name-mixedcase
    function INCENTIVES_CONTROLLER() external returns (address);

    // solhint-disable-next-line func-name-mixedcase
    function ATOKEN() external returns (IERC20);

    // solhint-disable-next-line func-name-mixedcase
    function ASSET() external returns (IERC20);

    // solhint-disable-next-line func-name-mixedcase
    function REWARD_TOKEN() external returns (IERC20);
}

File 37 of 79 : IstETH.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 "../solidity-utils/openzeppelin/IERC20.sol";

// solhint-disable-next-line max-line-length
// Based on https://github.com/lidofinance/lido-dao/blob/816bf1d0995ba5cfdfc264de4acda34a7fe93eba/contracts/0.4.24/Lido.sol

interface IstETH is IERC20 {
    function submit(address referral) external payable returns (uint256);
}

File 38 of 79 : ITetuSmartVault.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 "../solidity-utils/openzeppelin/IERC20.sol";

interface ITetuSmartVault is IERC20 {
    function deposit(uint256 amount) external;

    function depositFor(uint256 amount, address holder) external;

    function underlyingBalanceInVault() external view returns (uint256);

    function withdraw(uint256 numberOfShares) external;

    function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256);

    function underlying() external view returns (address);

    function underlyingUnit() external view returns (uint256);

    function getPricePerFullShare() external view returns (uint256);

    function strategy() external view returns (address);
}

File 39 of 79 : IUnbuttonToken.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 "../solidity-utils/openzeppelin/IERC20.sol";

import "./IButtonWrapper.sol";

// Balancer only supports ERC20 tokens, so we use this intermediate interface
// to enforce ERC20-ness of UnbuttonTokens.
interface IUnbuttonToken is IButtonWrapper, IERC20 {
    // solhint-disable-previous-line no-empty-blocks
}

File 40 of 79 : IwstETH.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 "../solidity-utils/openzeppelin/IERC20.sol";

import "./IstETH.sol";

// solhint-disable-next-line max-line-length
// Based on https://github.com/lidofinance/lido-dao/blob/2b46615a11dee77d4d22066f942f6c6afab9b87a/contracts/0.6.12/WstETH.sol

/**
 * @title StETH token wrapper with static balances.
 * @dev It's an ERC20 token that represents the account's share of the total
 * supply of stETH tokens. WstETH token's balance only changes on transfers,
 * unlike StETH that is also changed when oracles report staking rewards and
 * penalties. It's a "power user" token for DeFi protocols which don't
 * support rebasable tokens.
 *
 * The contract is also a trustless wrapper that accepts stETH tokens and mints
 * wstETH in return. Then the user unwraps, the contract burns user's wstETH
 * and sends user locked stETH in return.
 *
 * The contract provides the staking shortcut: user can send ETH with regular
 * transfer and get wstETH in return. The contract will send ETH to Lido submit
 * method, staking it and wrapping the received stETH.
 *
 */
interface IwstETH is IERC20 {
    function stETH() external returns (IstETH);

    /**
     * @notice Exchanges stETH to wstETH
     * @param _stETHAmount amount of stETH to wrap in exchange for wstETH
     * @dev Requirements:
     *  - `_stETHAmount` must be non-zero
     *  - msg.sender must approve at least `_stETHAmount` stETH to this
     *    contract.
     *  - msg.sender must have at least `_stETHAmount` of stETH.
     * User should first approve _stETHAmount to the WstETH contract
     * @return Amount of wstETH user receives after wrap
     */
    function wrap(uint256 _stETHAmount) external returns (uint256);

    /**
     * @notice Exchanges wstETH to stETH
     * @param _wstETHAmount amount of wstETH to uwrap in exchange for stETH
     * @dev Requirements:
     *  - `_wstETHAmount` must be non-zero
     *  - msg.sender must have at least `_wstETHAmount` wstETH.
     * @return Amount of stETH user receives after unwrap
     */
    function unwrap(uint256 _wstETHAmount) external returns (uint256);

    /**
     * @notice Get amount of wstETH for a given amount of stETH
     * @param _stETHAmount amount of stETH
     * @return Amount of wstETH for a given stETH amount
     */
    function getWstETHByStETH(uint256 _stETHAmount) external view returns (uint256);

    /**
     * @notice Get amount of stETH for a given amount of wstETH
     * @param _wstETHAmount amount of wstETH
     * @return Amount of stETH for a given wstETH amount
     */
    function getStETHByWstETH(uint256 _wstETHAmount) external view returns (uint256);

    /**
     * @notice Get amount of wstETH for a one stETH
     * @return Amount of stETH for 1 wstETH
     */
    function stEthPerToken() external view returns (uint256);

    /**
     * @notice Get amount of stETH for a one wstETH
     * @return Amount of wstETH for a 1 stETH
     */
    function tokensPerStEth() external view returns (uint256);
}

File 41 of 79 : IYearnTokenVault.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;

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

interface IYearnTokenVault is IERC20 {
    /**
     * @dev returns the address of the vault's underlying asset (mainToken)
     */
    function token() external view returns (address);

    /**
     * @dev returns the price for a single Vault share (ie yvDAI). The pricePerShare is represented
     * in the same decimals as the underlying asset (ie: 6 decimals for USDC)
     */
    function pricePerShare() external view returns (uint256);

    /**
     * @notice Deposits `_amount` `token`, issuing shares to `recipient`.
     * If the Vault is in Emergency Shutdown, deposits will not be accepted and this call will fail.
     * @param _amount The quantity of tokens to deposit, defaults to all.
     * @param recipient The address to issue the shares in this Vault to. Defaults to the caller's address.
     * @return The issued Vault shares.
     */
    function deposit(uint256 _amount, address recipient) external returns (uint256);

    /**
     * @notice Withdraws the calling account's tokens from this Vault,
     * redeeming amount `_shares` for an appropriate amount of tokens.
     * See note on `setWithdrawalQueue` for further details of withdrawal ordering and behavior.
     * @param maxShares How many shares to try and redeem for tokens, defaults to all.
     * @param recipient The address to issue the shares in this Vault to. Defaults to the caller's address.
     * @return redeemed: The quantity of tokens redeemed for `_shares`.
     */
    function withdraw(uint256 maxShares, address recipient) external returns (uint256);
}

File 42 of 79 : 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 43 of 79 : 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 44 of 79 : 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 45 of 79 : 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 46 of 79 : 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 47 of 79 : InputHelpers.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;

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

library InputHelpers {
    function ensureInputLengthMatch(uint256 a, uint256 b) internal pure {
        _require(a == b, Errors.INPUT_LENGTH_MISMATCH);
    }

    function ensureInputLengthMatch(
        uint256 a,
        uint256 b,
        uint256 c
    ) internal pure {
        _require(a == b && b == c, Errors.INPUT_LENGTH_MISMATCH);
    }

    function ensureArrayIsSorted(IERC20[] memory array) internal pure {
        address[] memory addressArray;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            addressArray := array
        }
        ensureArrayIsSorted(addressArray);
    }

    function ensureArrayIsSorted(address[] memory array) internal pure {
        if (array.length < 2) {
            return;
        }

        address previous = array[0];
        for (uint256 i = 1; i < array.length; ++i) {
            address current = array[i];
            _require(previous < current, Errors.UNSORTED_ARRAY);
            previous = current;
        }
    }
}

File 48 of 79 : VaultHelpers.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;

library VaultHelpers {
    /**
     * @dev Returns the address of a Pool's contract.
     *
     * This is the same code the Vault runs in `PoolRegistry._getPoolAddress`.
     */
    function toPoolAddress(bytes32 poolId) internal pure returns (address) {
        // 12 byte logical shift left to remove the nonce and specialization setting. We don't need to mask,
        // since the logical shift already sets the upper bits to zero.
        return address(uint256(poolId) >> (12 * 8));
    }
}

File 49 of 79 : Math.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
 * Adapted from OpenZeppelin's SafeMath library.
 */
library Math {
    // solhint-disable no-inline-assembly

    /**
     * @dev Returns the absolute value of a signed integer.
     */
    function abs(int256 a) internal pure returns (uint256 result) {
        // Equivalent to:
        // result = a > 0 ? uint256(a) : uint256(-a)
        assembly {
            let s := sar(255, a)
            result := sub(xor(a, s), s)
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        _require(c >= a, Errors.ADD_OVERFLOW);
        return c;
    }

    /**
     * @dev Returns the addition of two signed integers, reverting on overflow.
     */
    function add(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a + b;
        _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW);
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        _require(b <= a, Errors.SUB_OVERFLOW);
        uint256 c = a - b;
        return c;
    }

    /**
     * @dev Returns the subtraction of two signed integers, reverting on overflow.
     */
    function sub(int256 a, int256 b) internal pure returns (int256) {
        int256 c = a - b;
        _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW);
        return c;
    }

    /**
     * @dev Returns the largest of two numbers of 256 bits.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256 result) {
        // Equivalent to:
        // result = (a < b) ? b : a;
        assembly {
            result := sub(a, mul(sub(a, b), lt(a, b)))
        }
    }

    /**
     * @dev Returns the smallest of two numbers of 256 bits.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256 result) {
        // Equivalent to `result = (a < b) ? a : b`
        assembly {
            result := sub(a, mul(sub(a, b), gt(a, b)))
        }
    }

    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a * b;
        _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW);
        return c;
    }

    function div(
        uint256 a,
        uint256 b,
        bool roundUp
    ) internal pure returns (uint256) {
        return roundUp ? divUp(a, b) : divDown(a, b);
    }

    function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
        _require(b != 0, Errors.ZERO_DIVISION);
        return a / b;
    }

    function divUp(uint256 a, uint256 b) internal pure returns (uint256 result) {
        _require(b != 0, Errors.ZERO_DIVISION);

        // Equivalent to:
        // result = a == 0 ? 0 : 1 + (a - 1) / b;
        assembly {
            result := mul(iszero(iszero(a)), add(1, div(sub(a, 1), b)))
        }
    }
}

File 50 of 79 : 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 51 of 79 : ERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

import "./SafeMath.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is IERC20 {
    using SafeMath for uint256;

    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _decimals = 18;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
     * called.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}. The total supply should only be read using this function
     *
     * Can be overridden by derived contracts to store the total supply in a different way (e.g. packed with other
     * storage values).
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev Sets a new value for the total supply. It should only be set using this function.
     *
     * * Can be overridden by derived contracts to store the total supply in a different way (e.g. packed with other
     * storage values).
     */
    function _setTotalSupply(uint256 value) internal virtual {
        _totalSupply = value;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(msg.sender, recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(msg.sender, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(
            sender,
            msg.sender,
            _allowances[sender][msg.sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE)
        );
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(
            msg.sender,
            spender,
            _allowances[msg.sender][spender].sub(subtractedValue, Errors.ERC20_DECREASED_ALLOWANCE_BELOW_ZERO)
        );
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        _require(sender != address(0), Errors.ERC20_TRANSFER_FROM_ZERO_ADDRESS);
        _require(recipient != address(0), Errors.ERC20_TRANSFER_TO_ZERO_ADDRESS);

        _beforeTokenTransfer(sender, recipient, amount);

        _balances[sender] = _balances[sender].sub(amount, Errors.ERC20_TRANSFER_EXCEEDS_BALANCE);
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        _beforeTokenTransfer(address(0), account, amount);

        _setTotalSupply(totalSupply().add(amount));
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        _require(account != address(0), Errors.ERC20_BURN_FROM_ZERO_ADDRESS);

        _beforeTokenTransfer(account, address(0), amount);

        _balances[account] = _balances[account].sub(amount, Errors.ERC20_BURN_EXCEEDS_BALANCE);
        _setTotalSupply(totalSupply().sub(amount));
        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal {
        _decimals = decimals_;
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        // solhint-disable-previous-line no-empty-blocks
    }
}

File 52 of 79 : 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;
    }
}

File 53 of 79 : SafeERC20.sol
// SPDX-License-Identifier: MIT

// Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce gas costs.
// The `safeTransfer` and `safeTransferFrom` functions assume that `token` is a contract (an account with code), and
// work differently from the OpenZeppelin version if it is not.

pragma solidity ^0.7.0;

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

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

    function safeApprove(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        // Some contracts need their allowance reduced to 0 before setting it to an arbitrary amount.
        if (value != 0 && token.allowance(address(this), address(to)) != 0) {
            _callOptionalReturn(address(token), abi.encodeWithSelector(token.approve.selector, to, 0));
        }

        _callOptionalReturn(address(token), abi.encodeWithSelector(token.approve.selector, to, value));
    }

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(address(token), abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(address(token), abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     *
     * WARNING: `token` is assumed to be a contract: calls to EOAs will *not* revert.
     */
    function _callOptionalReturn(address token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves.
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = token.call(data);

        // If the low-level call didn't succeed we return whatever was returned from it.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            if eq(success, 0) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
        }

        // Finally we check the returndata size is either zero or true - note that this check will always pass for EOAs
        _require(returndata.length == 0 || abi.decode(returndata, (bool)), Errors.SAFE_ERC20_CALL_FAILED);
    }
}

File 54 of 79 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        _require(c >= a, Errors.ADD_OVERFLOW);

        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return sub(a, b, Errors.SUB_OVERFLOW);
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        uint256 errorCode
    ) internal pure returns (uint256) {
        _require(b <= a, errorCode);
        uint256 c = a - b;

        return c;
    }
}

File 55 of 79 : AssetHelpers.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;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/misc/IWETH.sol";
import "@balancer-labs/v2-interfaces/contracts/vault/IAsset.sol";

abstract contract AssetHelpers {
    // solhint-disable-next-line var-name-mixedcase
    IWETH private immutable _weth;

    // Sentinel value used to indicate WETH with wrapping/unwrapping semantics. The zero address is a good choice for
    // multiple reasons: it is cheap to pass as a calldata argument, it is a known invalid token and non-contract, and
    // it is an address Pools cannot register as a token.
    address private constant _ETH = address(0);

    constructor(IWETH weth) {
        _weth = weth;
    }

    // solhint-disable-next-line func-name-mixedcase
    function _WETH() internal view returns (IWETH) {
        return _weth;
    }

    /**
     * @dev Returns true if `asset` is the sentinel value that represents ETH.
     */
    function _isETH(IAsset asset) internal pure returns (bool) {
        return address(asset) == _ETH;
    }

    /**
     * @dev Translates `asset` into an equivalent IERC20 token address. If `asset` represents ETH, it will be translated
     * to the WETH contract.
     */
    function _translateToIERC20(IAsset asset) internal view returns (IERC20) {
        return _isETH(asset) ? _WETH() : _asIERC20(asset);
    }

    /**
     * @dev Same as `_translateToIERC20(IAsset)`, but for an entire array.
     */
    function _translateToIERC20(IAsset[] memory assets) internal view returns (IERC20[] memory) {
        IERC20[] memory tokens = new IERC20[](assets.length);
        for (uint256 i = 0; i < assets.length; ++i) {
            tokens[i] = _translateToIERC20(assets[i]);
        }
        return tokens;
    }

    /**
     * @dev Interprets `asset` as an IERC20 token. This function should only be called on `asset` if `_isETH` previously
     * returned false for it, that is, if `asset` is guaranteed not to be the ETH sentinel value.
     */
    function _asIERC20(IAsset asset) internal pure returns (IERC20) {
        return IERC20(address(asset));
    }
}

File 56 of 79 : AaveWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IStaticATokenLM.sol";
import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";

import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title AaveWrapping
 * @notice Allows users to wrap and unwrap Aave's aTokens into their StaticAToken wrappers
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract AaveWrapping is IBaseRelayerLibrary {
    using Address for address payable;
    using SafeERC20 for IERC20;

    function wrapAaveDynamicToken(
        IStaticATokenLM staticToken,
        address sender,
        address recipient,
        uint256 amount,
        bool fromUnderlying,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        // Aave's StaticATokens allow wrapping either an aToken or the underlying asset.
        // We can query which token to pull and approve from the wrapper contract.
        IERC20 dynamicToken = fromUnderlying ? staticToken.ASSET() : staticToken.ATOKEN();

        // The wrap caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, dynamicToken, amount);
        }

        dynamicToken.safeApprove(address(staticToken), amount);
        // Use 0 for the referral code
        uint256 result = staticToken.deposit(recipient, amount, 0, fromUnderlying);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, result);
        }
    }

    function unwrapAaveStaticToken(
        IStaticATokenLM staticToken,
        address sender,
        address recipient,
        uint256 amount,
        bool toUnderlying,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        // The unwrap caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, staticToken, amount);
        }

        // No approval is needed here, as the Static Tokens are burned directly from the relayer's account
        (, uint256 result) = staticToken.withdraw(recipient, amount, toUnderlying);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, result);
        }
    }
}

File 57 of 79 : BalancerRelayer.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IBalancerRelayer.sol";

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

/**
 * @title Balancer Relayer
 * @notice Allows safe multicall execution of a relayer's functions
 * @dev
 * Relayers are composed of two contracts:
 *  - This contract, which acts as a single point of entry into the system through a multicall function.
 *  - A library contract, which defines the allowed behaviour of the relayer.
 *
 * The relayer entrypoint can then repeatedly delegatecall into the library's code to perform actions.
 * We can then run combinations of the library contract's functions in the context of the relayer entrypoint,
 * without having to expose all these functions on the entrypoint contract itself. The multicall function is
 * then a single point of entry for all actions, so we can easily prevent reentrancy.
 *
 * This design gives much stronger reentrancy guarantees, as otherwise a malicious contract could reenter
 * the relayer through another function (which must allow reentrancy for multicall logic), and that would
 * potentially allow them to manipulate global state, resulting in loss of funds in some cases:
 * e.g., sweeping any leftover ETH that should have been refunded to the user.
 *
 * NOTE: Only the entrypoint contract should be allowlisted by Balancer governance as a relayer, so that the
 * Vault will reject calls from outside the context of the entrypoint: e.g., if a user mistakenly called directly
 * into the library contract.
 */
contract BalancerRelayer is IBalancerRelayer, ReentrancyGuard {
    using Address for address payable;
    using Address for address;

    IVault private immutable _vault;
    address private immutable _library;

    /**
     * @dev This contract is not meant to be deployed directly by an EOA, but rather during construction of a contract
     * derived from `BaseRelayerLibrary`, which will provide its own address as the relayer's library.
     */
    constructor(IVault vault, address libraryAddress) {
        _vault = vault;
        _library = libraryAddress;
    }

    receive() external payable {
        // Only accept ETH transfers from the Vault. This is expected to happen due to a swap/exit/withdrawal
        // with ETH as an output, should the relayer be listed as the recipient. This may also happen when
        // joining a pool, performing a swap, or if managing a user's balance uses less than the full ETH value
        // provided. Any excess ETH will be refunded to this contract, and then forwarded to the original sender.
        _require(msg.sender == address(_vault), Errors.ETH_TRANSFER);
    }

    function getVault() external view override returns (IVault) {
        return _vault;
    }

    function getLibrary() external view override returns (address) {
        return _library;
    }

    function multicall(bytes[] calldata data) external payable override nonReentrant returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = _library.functionDelegateCall(data[i]);
        }

        _refundETH();
    }

    function _refundETH() private {
        uint256 remainingEth = address(this).balance;
        if (remainingEth > 0) {
            msg.sender.sendValue(remainingEth);
        }
    }
}

File 58 of 79 : BaseRelayerLibrary.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IBalancerRelayer.sol";
import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";

import "./IBaseRelayerLibrary.sol";
import "./BalancerRelayer.sol";

/**
 * @title Base Relayer Library
 * @notice Core functionality of a relayer. Allow users to use a signature to approve this contract
 * to take further actions on their behalf.
 * @dev
 * Relayers are composed of two contracts:
 *  - A `BalancerRelayer` contract, which acts as a single point of entry into the system through a multicall function
 *  - A library contract such as this one, which defines the allowed behaviour of the relayer

 * NOTE: Only the entrypoint contract should be allowlisted by Balancer governance as a relayer, so that the Vault
 * will reject calls from outside the entrypoint context.
 *
 * This contract should neither be allowlisted as a relayer, nor called directly by the user.
 * No guarantees can be made about fund safety when calling this contract in an improper manner.
 */
contract BaseRelayerLibrary is IBaseRelayerLibrary {
    using Address for address;
    using SafeERC20 for IERC20;

    IVault private immutable _vault;
    IBalancerRelayer private immutable _entrypoint;

    constructor(IVault vault) IBaseRelayerLibrary(vault.WETH()) {
        _vault = vault;
        _entrypoint = new BalancerRelayer(vault, address(this));
    }

    function getVault() public view override returns (IVault) {
        return _vault;
    }

    function getEntrypoint() public view returns (IBalancerRelayer) {
        return _entrypoint;
    }

    /**
     * @notice Sets whether a particular relayer is authorised to act on behalf of the user
     */
    function setRelayerApproval(
        address relayer,
        bool approved,
        bytes calldata authorisation
    ) external payable {
        require(relayer == address(this) || !approved, "Relayer can only approve itself");
        bytes memory data = abi.encodePacked(
            abi.encodeWithSelector(_vault.setRelayerApproval.selector, msg.sender, relayer, approved),
            authorisation
        );

        address(_vault).functionCall(data);
    }

    /**
     * @notice Approves the Vault to use tokens held in the relayer
     * @dev This is needed to avoid having to send intermediate tokens back to the user
     */
    function approveVault(IERC20 token, uint256 amount) public payable override {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }
        // TODO: gas golf this a bit
        token.safeApprove(address(getVault()), amount);
    }

    /**
     * @notice Returns the amount referenced by chained reference `ref`.
     * @dev It does not alter the reference (even if it's marked as temporary).
     */
    function peekChainedReferenceValue(uint256 ref) public view override returns (uint256 value) {
        (, value) = _peekChainedReferenceValue(ref);
    }

    function _pullToken(
        address sender,
        IERC20 token,
        uint256 amount
    ) internal override {
        if (amount == 0) return;
        IERC20[] memory tokens = new IERC20[](1);
        tokens[0] = token;
        uint256[] memory amounts = new uint256[](1);
        amounts[0] = amount;

        _pullTokens(sender, tokens, amounts);
    }

    function _pullTokens(
        address sender,
        IERC20[] memory tokens,
        uint256[] memory amounts
    ) internal override {
        IVault.UserBalanceOp[] memory ops = new IVault.UserBalanceOp[](tokens.length);
        for (uint256 i; i < tokens.length; i++) {
            ops[i] = IVault.UserBalanceOp({
                asset: IAsset(address(tokens[i])),
                amount: amounts[i],
                sender: sender,
                recipient: payable(address(this)),
                kind: IVault.UserBalanceOpKind.TRANSFER_EXTERNAL
            });
        }

        getVault().manageUserBalance(ops);
    }

    /**
     * @dev Returns true if `amount` is not actually an amount, but rather a chained reference.
     */
    function _isChainedReference(uint256 amount) internal pure override returns (bool) {
        // First 3 nibbles are enough to determine if it's a chained reference.
        return
            (amount & 0xfff0000000000000000000000000000000000000000000000000000000000000) ==
            0xba10000000000000000000000000000000000000000000000000000000000000;
    }

    /**
     * @dev Returns true if `ref` is temporary reference, i.e. to be deleted after reading it.
     */
    function _isTemporaryChainedReference(uint256 amount) internal pure returns (bool) {
        // First 3 nibbles determine if it's a chained reference.
        // If the 4th nibble is 0 it is temporary; otherwise it is considered read-only.
        // In practice, we shall use '0xba11' for read-only references.
        return
            (amount & 0xffff000000000000000000000000000000000000000000000000000000000000) ==
            0xba10000000000000000000000000000000000000000000000000000000000000;
    }

    /**
     * @dev Stores `value` as the amount referenced by chained reference `ref`.
     */
    function _setChainedReferenceValue(uint256 ref, uint256 value) internal override {
        bytes32 slot = _getStorageSlot(ref);

        // Since we do manual calculation of storage slots, it is easier (and cheaper) to rely on internal assembly to
        // access it.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(slot, value)
        }
    }

    /**
     * @dev Returns the amount referenced by chained reference `ref`.
     * If the reference is temporary, it will be cleared after reading it, so they can each only be read once.
     * If the reference is not temporary (i.e. read-only), it will not be cleared after reading it
     * (see `_isTemporaryChainedReference` function).
     */
    function _getChainedReferenceValue(uint256 ref) internal override returns (uint256) {
        (bytes32 slot, uint256 value) = _peekChainedReferenceValue(ref);

        if (_isTemporaryChainedReference(ref)) {
            // solhint-disable-next-line no-inline-assembly
            assembly {
                sstore(slot, 0)
            }
        }
        return value;
    }

    /**
     * @dev Returns the storage slot for reference `ref` as well as the amount referenced by it.
     * It does not alter the reference (even if it's marked as temporary).
     */
    function _peekChainedReferenceValue(uint256 ref) private view returns (bytes32 slot, uint256 value) {
        slot = _getStorageSlot(ref);

        // Since we do manual calculation of storage slots, it is easier (and cheaper) to rely on internal assembly to
        // access it.
        // solhint-disable-next-line no-inline-assembly
        assembly {
            value := sload(slot)
        }
    }

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private immutable _TEMP_STORAGE_SUFFIX = keccak256("balancer.base-relayer-library");

    function _getStorageSlot(uint256 ref) private view returns (bytes32) {
        // This replicates the mechanism Solidity uses to allocate storage slots for mappings, but using a hash as the
        // mapping's storage slot, and subtracting 1 at the end. This should be more than enough to prevent collisions
        // with other state variables this or derived contracts might use.
        // See https://docs.soliditylang.org/en/v0.8.9/internals/layout_in_storage.html

        return bytes32(uint256(keccak256(abi.encodePacked(_removeReferencePrefix(ref), _TEMP_STORAGE_SUFFIX))) - 1);
    }

    /**
     * @dev Returns a reference without its prefix.
     * Use this function to calculate the storage slot so that it's the same for temporary and read-only references.
     */
    function _removeReferencePrefix(uint256 ref) private pure returns (uint256) {
        return (ref & 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
    }
}

File 59 of 79 : BeefyWrapping.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;
pragma experimental ABIEncoderV2;

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

import "@balancer-labs/v2-interfaces/contracts/pool-linear/IBeefyVault.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title  BeefyWrapping
 * @notice Allows users to wrap and unwrap Beefy's mooTokens into their underlying main tokens
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract BeefyWrapping is IBaseRelayerLibrary {
    using Address for address payable;

    function unwrapBeefyVaultToken(
        IBeefyVault vaultToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        // The unwrap caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, vaultToken, amount);
        }

        IERC20 underlyingToken = IERC20(vaultToken.want());

        // Burn the mooTokens and receive the underlying token.
        vaultToken.withdraw(amount);

        // Determine the amount of underlying returned for the shares burned.
        uint256 withdrawnAmount = underlyingToken.balanceOf(address(this));

        // Send the shares to the recipient
        underlyingToken.transfer(recipient, withdrawnAmount);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, withdrawnAmount);
        }
    }

    function wrapBeefyVaultToken(
        IBeefyVault vaultToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        IERC20 underlyingToken = IERC20(vaultToken.want());

        // The wrap caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, underlyingToken, amount);
        }

        // Approve the vault token to spend the amount specified in the wrap
        underlyingToken.approve(address(vaultToken), amount);

        // Deposit the tokens into the vault
        vaultToken.deposit(amount);

        // Determine the amount of mooTokens gained from depositing
        uint256 sharesGained = vaultToken.balanceOf(address(this));

        // Send the mooTokens to the recipient
        vaultToken.transfer(recipient, sharesGained);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, sharesGained);
        }
    }
}

File 60 of 79 : BooMirrorWorldStaking.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-interfaces/contracts/pool-linear/IBooMirrorWorld.sol";

import "./SushiBarStaking.sol";

/**
 * @title BooMirrorWorldStaking
 * @notice Allows users to deposit and withdraw tokens to/from the BooMirrorWorld contract
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract BooMirrorWorldStaking is SushiBarStaking {
    using Address for address payable;

    IBooMirrorWorld private immutable _mirrorWorld;

    constructor(IBooMirrorWorld mirrorWorld) {
        _mirrorWorld = mirrorWorld;
    }

    function booMirrorWorldEnter(
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        _sushiBarEnter(_mirrorWorld, _mirrorWorld.boo(), sender, recipient, amount, outputReference);
    }

    function booMirrorWorldLeave(
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        _sushiBarLeave(_mirrorWorld, _mirrorWorld.boo(), sender, recipient, amount, outputReference);
    }
}

File 61 of 79 : CompoundV2Wrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/ICToken.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title CompoundV2Wrapping
 * @notice Allows users to wrap and unwrap Compound v2 cTokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract CompoundV2Wrapping is IBaseRelayerLibrary {
    function wrapCompoundV2(
        ICToken wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        IERC20 mainToken = IERC20(wrappedToken.underlying());
        amount = _resolveAmountPullTokenAndApproveSpender(mainToken, address(wrappedToken), amount, sender);

        // The `mint` function deposits `amount` underlying tokens and transfers cTokens to the caller.
        // It returns an error code, where zero indicates success. Other error codes can be found here:
        // https://github.com/compound-finance/compound-protocol/blob/a3214f67b73310d547e00fc578e8355911c9d376/contracts/ErrorReporter.sol
        // solhint-disable-previous-line max-line-length
        require(wrappedToken.mint(amount) == 0, "wrapping failed");

        uint256 receivedWrappedAmount = wrappedToken.balanceOf(address(this));

        _transferAndSetChainedReference(wrappedToken, recipient, receivedWrappedAmount, outputReference);
    }

    function unwrapCompoundV2(
        ICToken wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(wrappedToken, amount, sender);

        IERC20 mainToken = IERC20(wrappedToken.underlying());

        // The `redeem` function burns `amount` cTokens and transfers underlying tokens to the caller.
        // It returns an error code, where zero indicates success. Other error codes can be found here:
        // https://github.com/compound-finance/compound-protocol/blob/a3214f67b73310d547e00fc578e8355911c9d376/contracts/ErrorReporter.sol
        // solhint-disable-previous-line max-line-length
        require(wrappedToken.redeem(amount) == 0, "unwrapping failed");

        uint256 withdrawnMainAmount = mainToken.balanceOf(address(this));

        _transferAndSetChainedReference(mainToken, recipient, withdrawnMainAmount, outputReference);
    }
}

File 62 of 79 : ERC4626Wrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/misc/IERC4626.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title ERC4626Wrapping
 * @notice Allows users to wrap and unwrap ERC4626 tokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract ERC4626Wrapping is IBaseRelayerLibrary {
    function wrapERC4626(
        IERC4626 wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        IERC20 underlying = IERC20(wrappedToken.asset());

        amount = _resolveAmountPullTokenAndApproveSpender(underlying, address(wrappedToken), amount, sender);

        uint256 result = wrappedToken.deposit(amount, recipient);

        _setChainedReference(outputReference, result);
    }

    function unwrapERC4626(
        IERC4626 wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(wrappedToken, amount, sender);

        uint256 result = wrappedToken.redeem(amount, recipient, address(this));

        _setChainedReference(outputReference, result);
    }
}

File 63 of 79 : EulerWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IEulerToken.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title EulerWrapping
 * @notice Allows users to wrap and unwrap Euler tokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract EulerWrapping is IBaseRelayerLibrary {
    //solhint-disable-next-line private-vars-leading-underscore
    uint256 private constant MAX_UINT256 = type(uint256).max;

    function wrapEuler(
        IEulerToken wrappedToken,
        address eulerProtocol,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        IERC20 underlying = IERC20(wrappedToken.underlyingAsset());

        amount = _resolveAmountPullTokenAndApproveSpender(underlying, eulerProtocol, amount, sender);

        // Deposit MainToken into EulerToken
        // 0 for the Euler primary account
        wrappedToken.deposit(0, amount);

        uint256 receivedWrappedAmount = wrappedToken.balanceOf(address(this));

        _transferAndSetChainedReference(wrappedToken, recipient, receivedWrappedAmount, outputReference);
    }

    function unwrapEuler(
        IEulerToken wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(wrappedToken, amount, sender);

        // Euler offers two ways to withdraw:
        //     1. Calculate mainTokenOut via wrappedToken.convertBalanceToUnderlying(wrappedTokenAmount)
        //     2. Redeem the account's full balance of wrappedToken for mainToken
        // Option 1 may leave wrappedToken dust in the relayer, so we choose option 2
        // The 0 argument is for the Euler primary account
        wrappedToken.withdraw(0, MAX_UINT256); //MAX_UINT256 forces option 2

        IERC20 mainToken = IERC20(wrappedToken.underlyingAsset());
        uint256 withdrawnMainAmount = mainToken.balanceOf(address(this));

        _transferAndSetChainedReference(mainToken, recipient, withdrawnMainAmount, outputReference);
    }
}

File 64 of 79 : FBeetsBarStaking.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-interfaces/contracts/liquidity-mining/IFBeetsBar.sol";
import "./SushiBarStaking.sol";

/**
 * @title BooMirrorWorldStaking
 * @notice Allows users to deposit and withdraw tokens to/from the BooMirrorWorld contract
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract FBeetsBarStaking is SushiBarStaking {
    using Address for address payable;

    IFBeetsBar private immutable _fBeetsBar;

    constructor(IFBeetsBar fBeetsBar) {
        _fBeetsBar = fBeetsBar;
    }

    function fBeetsBarEnter(
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        _sushiBarEnter(_fBeetsBar, _fBeetsBar.vestingToken(), sender, recipient, amount, outputReference);
    }

    function fBeetsBarLeave(
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        _sushiBarLeave(_fBeetsBar, _fBeetsBar.vestingToken(), sender, recipient, amount, outputReference);
    }
}

File 65 of 79 : GaugeActions.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/liquidity-mining/IBalancerMinter.sol";
import "@balancer-labs/v2-interfaces/contracts/liquidity-mining/IStakingLiquidityGauge.sol";

import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title GaugeActions
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract GaugeActions is IBaseRelayerLibrary {
    using SafeERC20 for IERC20;

    IBalancerMinter private immutable _balancerMinter;

    /**
     * @dev The zero address may be passed as balancerMinter to safely disable features
     *      which only exist on mainnet
     */
    constructor(IBalancerMinter balancerMinter) {
        _balancerMinter = balancerMinter;
    }

    function gaugeDeposit(
        IStakingLiquidityGauge gauge,
        address sender,
        address recipient,
        uint256 amount
    ) external payable {
        // We can query which token to pull and approve from the wrapper contract.
        IERC20 bptToken = gauge.lp_token();

        amount = _resolveAmountPullTokenAndApproveSpender(bptToken, address(gauge), amount, sender);

        gauge.deposit(amount, recipient);
    }

    function gaugeWithdraw(
        IStakingLiquidityGauge gauge,
        address sender,
        address recipient,
        uint256 amount
    ) external payable {
        amount = _resolveAmountAndPullToken(gauge, amount, sender);

        // No approval is needed here, as the gauge Tokens are burned directly from the relayer's account.
        gauge.withdraw(amount);

        // Gauge does not support withdrawing BPT to another address atomically.
        // If intended recipient is not the relayer then forward the withdrawn BPT on to the recipient.
        if (recipient != address(this)) {
            IERC20 bptToken = gauge.lp_token();

            bptToken.safeTransfer(recipient, amount);
        }
    }

    function gaugeMint(address[] calldata gauges, uint256 outputReference) external payable {
        uint256 balMinted = _balancerMinter.mintManyFor(gauges, msg.sender);

        _setChainedReference(outputReference, balMinted);
    }

    function gaugeSetMinterApproval(
        bool approval,
        address user,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable {
        _balancerMinter.setMinterApprovalWithSignature(address(this), approval, user, deadline, v, r, s);
    }

    function gaugeClaimRewards(IStakingLiquidityGauge[] calldata gauges) external payable {
        uint256 numGauges = gauges.length;
        for (uint256 i; i < numGauges; ++i) {
            gauges[i].claim_rewards(msg.sender);
        }
    }
}

File 66 of 79 : GearboxWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IGearboxDieselToken.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title GearboxWrapping
 * @notice Allows users to wrap and unwrap Gearbox tokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract GearboxWrapping is IBaseRelayerLibrary {
    function wrapGearbox(
        IGearboxDieselToken wrappedToken,
        address sender,
        address recipient,
        uint256 mainAmount,
        uint256 outputReference
    ) external payable {
        IGearboxVault gearboxVault = IGearboxVault(wrappedToken.owner());
        IERC20 underlying = IERC20(gearboxVault.underlyingToken());

        // Main Tokens are not deposited in the dieselToken address. Instead, they're deposited in a gearbox vault
        mainAmount = _resolveAmountPullTokenAndApproveSpender(underlying, address(gearboxVault), mainAmount, sender);

        // The third argument of addLiquidity is a referral code, which will be always 0 for the relayer (no referee)
        gearboxVault.addLiquidity(mainAmount, recipient, 0);

        _setChainedReference(outputReference, gearboxVault.toDiesel(mainAmount));
    }

    function unwrapGearbox(
        IGearboxDieselToken wrappedToken,
        address sender,
        address recipient,
        uint256 dieselAmount,
        uint256 outputReference
    ) external payable {
        dieselAmount = _resolveAmountAndPullToken(IERC20(address(wrappedToken)), dieselAmount, sender);

        // Main Tokens are not deposited in the dieselToken address. Instead, they're deposited in a gearbox vault.
        // Therefore, to remove liquidity, we withdraw tokens from the vault, and not from the wrapped token.
        IGearboxVault gearboxVault = IGearboxVault(wrappedToken.owner());
        gearboxVault.removeLiquidity(dieselAmount, recipient);

        _setChainedReference(outputReference, gearboxVault.fromDiesel(dieselAmount));
    }
}

File 67 of 79 : IBaseRelayerLibrary.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";

import "@balancer-labs/v2-vault/contracts/AssetHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";

/**
 * @title IBaseRelayerLibrary
 */
abstract contract IBaseRelayerLibrary is AssetHelpers {
    using SafeERC20 for IERC20;

    constructor(IWETH weth) AssetHelpers(weth) {
        // solhint-disable-previous-line no-empty-blocks
    }

    function getVault() public view virtual returns (IVault);

    function approveVault(IERC20 token, uint256 amount) public payable virtual;

    function peekChainedReferenceValue(uint256 ref) public view virtual returns (uint256);

    function _pullToken(
        address sender,
        IERC20 token,
        uint256 amount
    ) internal virtual;

    function _pullTokens(
        address sender,
        IERC20[] memory tokens,
        uint256[] memory amounts
    ) internal virtual;

    function _isChainedReference(uint256 amount) internal pure virtual returns (bool);

    function _setChainedReferenceValue(uint256 ref, uint256 value) internal virtual;

    function _getChainedReferenceValue(uint256 ref) internal virtual returns (uint256);

    /**
     * @dev This reuses `_resolveAmountAndPullToken` to adjust the `amount` in case it is a chained reference,
     * then pull that amount of `token` to the relayer. Additionally, it approves the `spender` to enable
     * wrapping operations. The spender is usually a token, but could also be another kind of contract (e.g.,
     * a protocol or gauge).
     */
    function _resolveAmountPullTokenAndApproveSpender(
        IERC20 token,
        address spender,
        uint256 amount,
        address sender
    ) internal returns (uint256 resolvedAmount) {
        resolvedAmount = _resolveAmountAndPullToken(token, amount, sender);

        token.safeApprove(spender, resolvedAmount);
    }

    /**
     * @dev Extract the `amount` (if it is a chained reference), and pull that amount of `token` to
     * this contract.
     */
    function _resolveAmountAndPullToken(
        IERC20 token,
        uint256 amount,
        address sender
    ) internal returns (uint256 resolvedAmount) {
        resolvedAmount = _resolveAmount(amount);

        // The wrap caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, token, resolvedAmount);
        }
    }

    /**
     * @dev Resolve an amount from a possible chained reference. This is internal, since some wrappers
     * call it independently.
     */
    function _resolveAmount(uint256 amount) internal returns (uint256) {
        return _isChainedReference(amount) ? _getChainedReferenceValue(amount) : amount;
    }

    /**
     * @dev Transfer the given `amount` of `token` to `recipient`, then call `_setChainedReference`
     * with that amount, in case it needs to be encoded as an output reference.
     */
    function _transferAndSetChainedReference(
        IERC20 token,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) internal {
        if (recipient != address(this)) {
            token.safeTransfer(recipient, amount);
        }

        _setChainedReference(outputReference, amount);
    }

    /**
     * @dev Check for a chained output reference, and encode the given `amount` if necessary.
     * This is internal, since some wrappers call it independently.
     */
    function _setChainedReference(uint256 outputReference, uint256 amount) internal {
        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, amount);
        }
    }
}

File 68 of 79 : LidoWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IstETH.sol";
import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IwstETH.sol";

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

import "./IBaseRelayerLibrary.sol";

/**
 * @title LidoWrapping
 * @notice Allows users to wrap and unwrap stETH
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract LidoWrapping is IBaseRelayerLibrary {
    using Address for address payable;

    IstETH private immutable _stETH;
    IwstETH private immutable _wstETH;

    /**
     * @dev The zero address may be passed as wstETH to safely disable this module
     * @param wstETH - the address of Lido's wrapped stETH contract
     */
    constructor(IERC20 wstETH) {
        // Safely disable stETH wrapping if no address has been passed for wstETH
        _stETH = wstETH != IERC20(0) ? IwstETH(address(wstETH)).stETH() : IstETH(0);
        _wstETH = IwstETH(address(wstETH));
    }

    function wrapStETH(
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountPullTokenAndApproveSpender(_stETH, address(_wstETH), amount, sender);

        uint256 result = IwstETH(_wstETH).wrap(amount);

        _transferAndSetChainedReference(_wstETH, recipient, result, outputReference);
    }

    function unwrapWstETH(
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(_wstETH, amount, sender);

        // No approval is needed here, as wstETH is burned directly from the relayer's account
        uint256 result = _wstETH.unwrap(amount);

        _transferAndSetChainedReference(_stETH, recipient, result, outputReference);
    }

    function stakeETH(
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmount(amount);

        uint256 result = _stETH.submit{ value: amount }(address(this));

        _transferAndSetChainedReference(_stETH, recipient, result, outputReference);
    }

    function stakeETHAndWrap(
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmount(amount);

        // We must query this separately, since the wstETH contract doesn't return how much wstETH is minted.
        uint256 result = _wstETH.getWstETHByStETH(amount);

        // The fallback function on the wstETH contract automatically stakes and wraps any ETH sent to it.
        // We can then send the ETH safely, and only have to ensure that the call doesn't revert.
        //
        // This would be dangerous if `_wstETH` were set to the zero address. However, in this scenario,
        // this function would have already reverted during the call to `getWstETHByStETH`, preventing loss of funds.
        payable(address(_wstETH)).sendValue(amount);

        _transferAndSetChainedReference(_wstETH, recipient, result, outputReference);
    }
}

File 69 of 79 : MasterChefStaking.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;
pragma experimental ABIEncoderV2;

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

import "@balancer-labs/v2-interfaces/contracts/liquidity-mining/IMasterChef.sol";
import "./IBaseRelayerLibrary.sol";

/**
 * @title MasterChefStaking
 * @notice Allows users to deposit and withdraw BPT to/from a MasterChef contract
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract MasterChefStaking is IBaseRelayerLibrary {
    using Address for address payable;

    IMasterChef private immutable _masterChef;

    constructor(IMasterChef masterChef) {
        _masterChef = masterChef;
    }

    function masterChefDeposit(
        address sender,
        address recipient,
        IERC20 token,
        uint256 pid,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        require(address(_masterChef.lpTokens(pid)) == address(token), "Incorrect token for pid");

        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        // The deposit caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, token, amount);
        }

        // deposit the tokens to the masterchef
        token.approve(address(_masterChef), amount);
        _masterChef.deposit(pid, amount, recipient);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, amount);
        }
    }
}

File 70 of 79 : ReaperWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IReaperTokenVault.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title ReaperWrapping
 * @notice Allows users to wrap and unwrap Reapers's rfTokens into their underlying main tokens
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract ReaperWrapping is IBaseRelayerLibrary {
    function unwrapReaperVaultToken(
        IReaperTokenVault vaultToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(vaultToken, amount, sender);

        // Burn the rf shares and receive the underlying token.
        vaultToken.withdraw(amount);

        IERC20 underlyingToken = IERC20(vaultToken.token());
        // Determine the amount of underlying returned for the shares burned.
        uint256 withdrawnAmount = underlyingToken.balanceOf(address(this));

        _transferAndSetChainedReference(underlyingToken, recipient, withdrawnAmount, outputReference);
    }

    function wrapReaperVaultToken(
        IReaperTokenVault vaultToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        IERC20 underlyingToken = IERC20(vaultToken.token());

        amount = _resolveAmountPullTokenAndApproveSpender(underlyingToken, address(vaultToken), amount, sender);

        // Deposit the tokens into the vault
        vaultToken.deposit(amount);

        // Determine the amount of shares gained from depositing
        uint256 sharesGained = vaultToken.balanceOf(address(this));

        _transferAndSetChainedReference(vaultToken, recipient, sharesGained, outputReference);
    }
}

File 71 of 79 : ReliquaryStaking.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-interfaces/contracts/liquidity-mining/IReliquary.sol";
import "@balancer-labs/v2-interfaces/contracts/liquidity-mining/IReliquaryRewarder.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/SafeERC20.sol";
import "./IBaseRelayerLibrary.sol";

/**
 * @title ReliquaryStaking
 * @notice Allows users to deposit and withdraw BPT to/from relic
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract ReliquaryStaking is IBaseRelayerLibrary {
    using Address for address payable;
    using SafeERC20 for IERC20;

    IReliquary private immutable _reliquary;

    constructor(IReliquary reliquary) {
        _reliquary = reliquary;
    }

    function reliquaryCreateRelicAndDeposit(
        address sender,
        address recipient,
        IERC20 token,
        uint256 poolId,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }
        require(_reliquary.poolToken(poolId) == address(token), "Incorrect token for pid");

        // The deposit caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, token, amount);
        }

        token.approve(address(_reliquary), amount);
        // mint a new relic and deposit the tokens
        _reliquary.createRelicAndDeposit(recipient, poolId, amount);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, amount);
        }
    }

    function reliquaryDeposit(
        address sender,
        IERC20 token,
        uint256 relicId,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }
        PositionInfo memory position = _reliquary.getPositionForId(relicId);
        require(_reliquary.poolToken(position.poolId) == address(token), "Incorrect token for pid");

        // The deposit caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, token, amount);
        }

        token.approve(address(_reliquary), amount);
        // deposit the tokens to an existing relic
        _reliquary.deposit(amount, relicId);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, amount);
        }
    }

    function reliquaryWithdrawAndHarvest(
        address recipient,
        uint256 relicId,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        require(msg.sender == _reliquary.ownerOf(relicId), "Sender not owner of relic");
        PositionInfo memory position = _reliquary.getPositionForId(relicId);
        IERC20 poolToken = IERC20( _reliquary.poolToken(position.poolId));

        _reliquary.withdrawAndHarvest(amount, relicId, recipient);
        poolToken.transfer(recipient, amount);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, amount);
        }
    }

    function reliquaryHarvestAll(uint256[] memory relicIds, address recipient) external payable {
        for (uint256 i = 0; i < relicIds.length; i++) {
            require(msg.sender == _reliquary.ownerOf(relicIds[i]), "Sender not owner of relic");
            _reliquary.harvest(relicIds[i], recipient);
        }
    }
}

File 72 of 79 : SiloWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/ISilo.sol";
import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IShareToken.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title SiloWrapping
 * @notice Allows users to wrap and unwrap Silo shareTokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract SiloWrapping is IBaseRelayerLibrary {
    function wrapShareToken(
        IShareToken wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        // Initialize the token we will be wrapping (underlying asset of shareToken)
        IERC20 underlyingToken = IERC20(wrappedToken.asset());
        // Initialize the corresponding Silo (Liquidity Pool)
        ISilo silo = wrappedToken.silo();

        amount = _resolveAmountPullTokenAndApproveSpender(underlyingToken, address(silo), amount, sender);

        // the collateralOnly param is set to false because we want to receive interest bearing shareTokens
        (, uint256 result) = silo.depositFor(address(underlyingToken), recipient, amount, false);

        _setChainedReference(outputReference, result);
    }

    function unwrapShareToken(
        IShareToken wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(wrappedToken, amount, sender);

        // Initialize the corresponding Silo (Liquidity Pool)
        ISilo silo = wrappedToken.silo();
        IERC20 underlyingToken = IERC20(wrappedToken.asset());

        // No approval is needed here, as the shareTokens are burned directly from the relayer's account.
        // Setting the amount to type(uint256).max informs Silo that we'd like to redeem all the relayer's shares.
        // Ignore the return value which cannot be trusted. It does not include any fees assessed.
        silo.withdraw(address(underlyingToken), type(uint256).max, false);

        uint256 result = underlyingToken.balanceOf(address(this));

        _transferAndSetChainedReference(underlyingToken, recipient, result, outputReference);
    }
}

File 73 of 79 : SushiBarStaking.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-interfaces/contracts/pool-linear/ISushiBar.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title SushiBarStaking
 * @notice Allows users to deposit and withdraw tokens to/from a SushiBar contract
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract SushiBarStaking is IBaseRelayerLibrary {
    using Address for address payable;

    function _sushiBarEnter(
        ISushiBar sushiBar,
        IERC20 token,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) internal {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        //We should be verifying that the token passed in is in fact the correct token for the sushi bar,
        //but xBOO, xTAROT and fBEETS all implement the underlying token with different variables names
        //(xBOO.boo / xTAROT.underlying / fBEETS.vestingToken). Either we implement an extension for each,
        //or we forgo the require check, as both enter and leave are the same interface across all 3.

        // The deposit caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, token, amount);
        }

        //determine the amount of xSUSHI that is present on the batch relayer prior to entering
        //this should always be 0, but we want to be certain
        uint256 xSushiAmountBefore = sushiBar.balanceOf(address(this));

        //deposit the vesting token into the sushi bar
        token.approve(address(sushiBar), amount);
        sushiBar.enter(amount);

        //determine the amount of xSUSHI minted for the amount deposited
        uint256 xSushiAmount = sushiBar.balanceOf(address(this)) - xSushiAmountBefore;

        //transfer the xSUSHI to the recipient
        sushiBar.transfer(recipient, xSushiAmount);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, xSushiAmount);
        }
    }

    function _sushiBarLeave(
        ISushiBar sushiBar,
        IERC20 token,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) internal {
        if (_isChainedReference(amount)) {
            amount = _getChainedReferenceValue(amount);
        }

        // The deposit caller is the implicit sender of tokens, so if the goal is for the tokens
        // to be sourced from outside the relayer, we must first pull them here.
        if (sender != address(this)) {
            require(sender == msg.sender, "Incorrect sender");
            _pullToken(sender, sushiBar, amount);
        }

        //determine the amount of SUSHI that is present on the batch relayer prior to leaving.
        //This should always be 0, but we want to be certain
        uint256 sushiAmountBefore = token.balanceOf(address(this));

        //burn the xSUSHI shares and receive SUSHI
        sushiBar.leave(amount);

        //determine the amount of SUSHI returned for the shares burned
        uint256 sushiAmount = token.balanceOf(address(this)) - sushiAmountBefore;

        //send the SUSHI to the recipient
        token.transfer(recipient, sushiAmount);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, sushiAmount);
        }
    }
}

File 74 of 79 : TarotWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20.sol";
import "./SushiBarStaking.sol";
import "@balancer-labs/v2-interfaces/contracts/pool-linear/ITarotSupplyVault.sol";

/**
 * @title TarotWrapping
 * @notice Allows users to deposit and withdraw tokens to/from a Tarot SupplyVault contract
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH
 */
abstract contract TarotWrapping is SushiBarStaking {
    using Address for address payable;

    function tarotSupplyVaultEnter(
        ITarotSupplyVault supplyVault,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        _sushiBarEnter(supplyVault, supplyVault.underlying(), sender, recipient, amount, outputReference);
    }

    function tarotSupplyVaultLeave(
        ITarotSupplyVault supplyVault,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        _sushiBarLeave(supplyVault, supplyVault.underlying(), sender, recipient, amount, outputReference);
    }
}

File 75 of 79 : TetuWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/ITetuSmartVault.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title TetuWrapping
 * @notice Allows users to wrap and unwrap Tetu tokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract TetuWrapping is IBaseRelayerLibrary {
    function wrapTetu(
        ITetuSmartVault wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        IERC20 underlying = IERC20(wrappedToken.underlying());

        amount = _resolveAmountPullTokenAndApproveSpender(underlying, address(wrappedToken), amount, sender);

        wrappedToken.deposit(amount);
        uint256 receivedWrappedAmount = wrappedToken.balanceOf(address(this));

        _transferAndSetChainedReference(wrappedToken, recipient, receivedWrappedAmount, outputReference);
    }

    function unwrapTetu(
        ITetuSmartVault wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(wrappedToken, amount, sender);

        IERC20 mainToken = IERC20(wrappedToken.underlying());
        wrappedToken.withdraw(amount);
        uint256 withdrawnMainAmount = mainToken.balanceOf(address(this));

        _transferAndSetChainedReference(mainToken, recipient, withdrawnMainAmount, outputReference);
    }
}

File 76 of 79 : UnbuttonWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IUnbuttonToken.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title UnbuttonWrapping
 * @author @aalavandhan1984 ([email protected])
 * @notice Allows users to wrap and unwrap any rebasing elastic balance token into a
 *         a non-rebasing static balance version using the Unbutton wrapper.
 * @dev All functions must be payable so that it can be called as part of a multicall involving ETH.
 *      The rebasing token to be wrapped is called the "underlying" token.
 *      The wrapped non-rebasing token is called the "wrapped" token.
 *      Learn more: https://github.com/buttonwood-protocol/button-wrappers/blob/main/contracts/UnbuttonToken.sol
 */
abstract contract UnbuttonWrapping is IBaseRelayerLibrary {
    /// @param wrapperToken The address of the wrapper.
    /// @param sender The address of sender.
    /// @param sender The address of recepient.
    /// @param uAmount The underling token amount to be deposited into the wrapper.
    /// @param outputReference Chained output reference.
    function wrapUnbuttonToken(
        IUnbuttonToken wrapperToken,
        address sender,
        address recipient,
        uint256 uAmount,
        uint256 outputReference
    ) external payable {
        IERC20 underlyingToken = IERC20(wrapperToken.underlying());

        uAmount = _resolveAmountPullTokenAndApproveSpender(underlyingToken, address(wrapperToken), uAmount, sender);

        uint256 mintAmount = wrapperToken.depositFor(recipient, uAmount);

        _setChainedReference(outputReference, mintAmount);
    }

    /// @param wrapperToken The address of the wrapper.
    /// @param sender The address of sender.
    /// @param sender The address of recepient.
    /// @param amount The amount of wrapped tokens to be burnt for underlying tokens.
    /// @param outputReference Chained output reference.
    function unwrapUnbuttonToken(
        IUnbuttonToken wrapperToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(wrapperToken, amount, sender);

        uint256 withdrawnUAmount = wrapperToken.burnTo(recipient, amount);

        _setChainedReference(outputReference, withdrawnUAmount);
    }
}

File 77 of 79 : VaultActions.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";
import "@balancer-labs/v2-interfaces/contracts/pool-weighted/WeightedPoolUserData.sol";
import "@balancer-labs/v2-interfaces/contracts/pool-stable/StablePoolUserData.sol";

import "@balancer-labs/v2-solidity-utils/contracts/helpers/InputHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/VaultHelpers.sol";
import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title VaultActions
 * @notice Allows users to call the core functions on the Balancer Vault (swaps/joins/exits/user balance management)
 * @dev Since the relayer is not expected to hold user funds, we expect the user to be the recipient of any token
 * transfers from the Vault.
 *
 * All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract VaultActions is IBaseRelayerLibrary {
    using Math for uint256;

    struct OutputReference {
        uint256 index;
        uint256 key;
    }

    function swap(
        IVault.SingleSwap memory singleSwap,
        IVault.FundManagement calldata funds,
        uint256 limit,
        uint256 deadline,
        uint256 value,
        uint256 outputReference
    ) external payable {
        require(funds.sender == msg.sender || funds.sender == address(this), "Incorrect sender");

        if (_isChainedReference(singleSwap.amount)) {
            singleSwap.amount = _getChainedReferenceValue(singleSwap.amount);
        }

        uint256 result = getVault().swap{ value: value }(singleSwap, funds, limit, deadline);

        if (_isChainedReference(outputReference)) {
            _setChainedReferenceValue(outputReference, result);
        }
    }

    function batchSwap(
        IVault.SwapKind kind,
        IVault.BatchSwapStep[] memory swaps,
        IAsset[] calldata assets,
        IVault.FundManagement calldata funds,
        int256[] calldata limits,
        uint256 deadline,
        uint256 value,
        OutputReference[] calldata outputReferences
    ) external payable {
        require(funds.sender == msg.sender || funds.sender == address(this), "Incorrect sender");

        for (uint256 i = 0; i < swaps.length; ++i) {
            uint256 amount = swaps[i].amount;
            if (_isChainedReference(amount)) {
                swaps[i].amount = _getChainedReferenceValue(amount);
            }
        }

        int256[] memory results = getVault().batchSwap{ value: value }(kind, swaps, assets, funds, limits, deadline);

        for (uint256 i = 0; i < outputReferences.length; ++i) {
            require(_isChainedReference(outputReferences[i].key), "invalid chained reference");

            // Batch swap return values are signed, as they are Vault deltas (positive values correspond to assets sent
            // to the Vault, and negative values are assets received from the Vault). To simplify the chained reference
            // value model, we simply store the absolute value.
            // This should be fine for most use cases, as the caller can reason about swap results via the `limits`
            // parameter.
            _setChainedReferenceValue(outputReferences[i].key, Math.abs(results[outputReferences[i].index]));
        }
    }

    function manageUserBalance(IVault.UserBalanceOp[] calldata ops, uint256 value) external payable {
        for (uint256 i = 0; i < ops.length; i++) {
            require(ops[i].sender == msg.sender || ops[i].sender == address(this), "Incorrect sender");
        }
        getVault().manageUserBalance{ value: value }(ops);
    }

    enum PoolKind { WEIGHTED, LEGACY_STABLE, COMPOSABLE_STABLE, COMPOSABLE_STABLE_V2 }

    function joinPool(
        bytes32 poolId,
        PoolKind kind,
        address sender,
        address recipient,
        IVault.JoinPoolRequest memory request,
        uint256 value,
        uint256 outputReference
    ) external payable {
        require(sender == msg.sender || sender == address(this), "Incorrect sender");

        // The output of a join will be the Pool's token contract, typically known as BPT (Balancer Pool Tokens).
        // Since the Vault is unaware of this (BPT tokens are minted directly to the recipient), we manually
        // measure this balance increase: but only if an output reference is provided.
        IERC20 bpt = IERC20(VaultHelpers.toPoolAddress(poolId));
        uint256 maybeInitialRecipientBPT = _isChainedReference(outputReference) ? bpt.balanceOf(recipient) : 0;

        request.userData = _doJoinPoolChainedReferenceReplacements(kind, request.userData);

        getVault().joinPool{ value: value }(poolId, sender, recipient, request);

        if (_isChainedReference(outputReference)) {
            // In this context, `maybeInitialRecipientBPT` is guaranteed to have been initialized, so we can safely read
            // from it. Note that we assume the recipient balance change has a positive sign (i.e. the recipient
            // received BPT).
            uint256 finalRecipientBPT = bpt.balanceOf(recipient);
            _setChainedReferenceValue(outputReference, finalRecipientBPT.sub(maybeInitialRecipientBPT));
        }
    }

    /**
     * @dev Compute the final userData for a join, depending on the PoolKind, performing replacements for chained
     * references as necessary.
     */
    function _doJoinPoolChainedReferenceReplacements(PoolKind kind, bytes memory userData)
        private
        returns (bytes memory)
    {
        if (kind == PoolKind.WEIGHTED) {
            return _doWeightedJoinChainedReferenceReplacements(userData);
        } else if (
            kind == PoolKind.LEGACY_STABLE ||
            kind == PoolKind.COMPOSABLE_STABLE ||
            kind == PoolKind.COMPOSABLE_STABLE_V2
        ) {
            return _doStableJoinChainedReferenceReplacements(userData);
        } else {
            revert("UNHANDLED_POOL_KIND");
        }
    }

    function _doWeightedJoinChainedReferenceReplacements(bytes memory userData) private returns (bytes memory) {
        WeightedPoolUserData.JoinKind kind = WeightedPoolUserData.joinKind(userData);

        if (kind == WeightedPoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
            return _doWeightedExactTokensInForBPTOutReplacements(userData);
        } else {
            // All other join kinds are 'given out' (i.e the parameter is a BPT amount),
            // so we don't do replacements for those.
            return userData;
        }
    }

    function _doWeightedExactTokensInForBPTOutReplacements(bytes memory userData) private returns (bytes memory) {
        (uint256[] memory amountsIn, uint256 minBPTAmountOut) = WeightedPoolUserData.exactTokensInForBptOut(userData);

        // Save gas by only re-encoding the data if we actually performed a replacement
        return
            _replacedAmounts(amountsIn)
                ? abi.encode(WeightedPoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, minBPTAmountOut)
                : userData;
    }

    function _doStableJoinChainedReferenceReplacements(bytes memory userData) private returns (bytes memory) {
        // The only 'given in' join (in which the parameters are the amounts in) is EXACT_TOKENS_IN_FOR_BPT_OUT,
        // so that is the only one where we do replacements. Luckily all versions of Stable Pool share the same
        // enum value for it, so we can treat them all the same, and just use the latest version.

        // Note that ComposableStablePool versions V2 and up support a proportional join kind, which some previous
        // versions did not. While it is not rejected here, if passed to the Pool it will revert.

        StablePoolUserData.JoinKind kind = StablePoolUserData.joinKind(userData);

        if (kind == StablePoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) {
            return _doStableExactTokensInForBPTOutReplacements(userData);
        } else {
            // All other join kinds are 'given out' (i.e the parameter is a BPT amount),
            // so we don't do replacements for those.
            return userData;
        }
    }

    function _doStableExactTokensInForBPTOutReplacements(bytes memory userData) private returns (bytes memory) {
        (uint256[] memory amountsIn, uint256 minBPTAmountOut) = StablePoolUserData.exactTokensInForBptOut(userData);

        // Save gas by only re-encoding the data if we actually performed a replacement
        return
            _replacedAmounts(amountsIn)
                ? abi.encode(StablePoolUserData.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT, amountsIn, minBPTAmountOut)
                : userData;
    }

    // Mutates amountsIn, and returns true if any replacements were made
    function _replacedAmounts(uint256[] memory amountsIn) private returns (bool) {
        bool madeReplacements = false;

        for (uint256 i = 0; i < amountsIn.length; ++i) {
            uint256 amount = amountsIn[i];
            if (_isChainedReference(amount)) {
                amountsIn[i] = _getChainedReferenceValue(amount);
                madeReplacements = true;
            }
        }

        return madeReplacements;
    }

    function exitPool(
        bytes32 poolId,
        PoolKind kind,
        address sender,
        address payable recipient,
        IVault.ExitPoolRequest memory request,
        OutputReference[] calldata outputReferences
    ) external payable {
        require(sender == msg.sender || sender == address(this), "Incorrect sender");

        // To track the changes of internal balances, we need an array of token addresses.
        // We save this here to avoid having to recalculate after the exit.
        IERC20[] memory trackedTokens = new IERC20[](outputReferences.length);

        // Query initial balances for all tokens, and record them as chained references
        uint256[] memory initialRecipientBalances = new uint256[](outputReferences.length);
        for (uint256 i = 0; i < outputReferences.length; i++) {
            require(_isChainedReference(outputReferences[i].key), "invalid chained reference");

            IAsset asset = request.assets[outputReferences[i].index];
            if (request.toInternalBalance) {
                trackedTokens[i] = _asIERC20(asset);
            } else {
                initialRecipientBalances[i] = _isETH(asset) ? recipient.balance : _asIERC20(asset).balanceOf(recipient);
            }
        }
        if (request.toInternalBalance) {
            initialRecipientBalances = getVault().getInternalBalance(recipient, trackedTokens);
        }

        // Exit the Pool
        request.userData = _doExitPoolChainedReferenceReplacements(kind, request.userData);
        getVault().exitPool(poolId, sender, recipient, request);

        // Query final balances for all tokens of interest
        uint256[] memory finalRecipientTokenBalances = new uint256[](outputReferences.length);
        if (request.toInternalBalance) {
            finalRecipientTokenBalances = getVault().getInternalBalance(recipient, trackedTokens);
        } else {
            for (uint256 i = 0; i < outputReferences.length; i++) {
                IAsset asset = request.assets[outputReferences[i].index];
                finalRecipientTokenBalances[i] = _isETH(asset)
                    ? recipient.balance
                    : _asIERC20(asset).balanceOf(recipient);
            }
        }

        // Calculate deltas and save as chained references
        for (uint256 i = 0; i < outputReferences.length; i++) {
            _setChainedReferenceValue(
                outputReferences[i].key,
                finalRecipientTokenBalances[i].sub(initialRecipientBalances[i])
            );
        }
    }

    /**
     * @dev Compute the final userData for an exit, depending on the PoolKind, performing replacements for chained
     * references as necessary.
     */
    function _doExitPoolChainedReferenceReplacements(PoolKind kind, bytes memory userData)
        private
        returns (bytes memory)
    {
        if (kind == PoolKind.WEIGHTED) {
            return _doWeightedExitChainedReferenceReplacements(userData);
        } else {
            if (kind == PoolKind.LEGACY_STABLE) {
                return _doLegacyStableExitChainedReferenceReplacements(userData);
            } else if (kind == PoolKind.COMPOSABLE_STABLE) {
                return _doComposableStableExitChainedReferenceReplacements(userData);
            } else if (kind == PoolKind.COMPOSABLE_STABLE_V2) {
                return _doComposableStableV2ExitChainedReferenceReplacements(userData);
            } else {
                revert("UNHANDLED_POOL_KIND");
            }
        }
    }

    function _doWeightedExitChainedReferenceReplacements(bytes memory userData) private returns (bytes memory) {
        WeightedPoolUserData.ExitKind kind = WeightedPoolUserData.exitKind(userData);

        if (kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) {
            return _doWeightedExactBptInForOneTokenOutReplacements(userData);
        } else if (kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) {
            return _doWeightedExactBptInForTokensOutReplacements(userData);
        } else {
            // All other exit kinds are 'given out' (i.e the parameter is a token amount),
            // so we don't do replacements for those.
            return userData;
        }
    }

    function _doWeightedExactBptInForOneTokenOutReplacements(bytes memory userData) private returns (bytes memory) {
        (uint256 bptAmountIn, uint256 tokenIndex) = WeightedPoolUserData.exactBptInForTokenOut(userData);

        if (_isChainedReference(bptAmountIn)) {
            bptAmountIn = _getChainedReferenceValue(bptAmountIn);
            return abi.encode(WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, bptAmountIn, tokenIndex);
        } else {
            // Save gas by only re-encoding the data if we actually performed a replacement
            return userData;
        }
    }

    function _doWeightedExactBptInForTokensOutReplacements(bytes memory userData) private returns (bytes memory) {
        uint256 bptAmountIn = WeightedPoolUserData.exactBptInForTokensOut(userData);

        if (_isChainedReference(bptAmountIn)) {
            bptAmountIn = _getChainedReferenceValue(bptAmountIn);
            return abi.encode(WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT, bptAmountIn);
        } else {
            // Save gas by only re-encoding the data if we actually performed a replacement
            return userData;
        }
    }

    // Stable Pool version-dependent recoding dispatch functions

    /*
     * While all Stable Pool versions fortuitously support the same join kinds (V2 and higher support one extra),
     * they do NOT all support the same exit kinds. Also, though the encoding of the data associated with the exit
     * is uniform across pool kinds for the same exit method, the ExitKind ID itself may have a different value.
     *
     * For instance, BPT_IN_FOR_EXACT_TOKENS_OUT is 2 in legacy Stable Pools, but 1 in Composable Stable Pools.
     * (See the reference comment and libraries below.)
     *
     * Accordingly, the three do[PoolKind]ExitChainedReferenceReplacements functions below (for LegacyStable,
     * ComposableStable, and CopmosableStableV2) extract the exitKind and pass it through to the shared
     * recoding functions.
     */

    function _doLegacyStableExitChainedReferenceReplacements(bytes memory userData) private returns (bytes memory) {
        uint8 exitKind = uint8(StablePoolUserData.exitKind(userData));

        if (exitKind == uint8(LegacyStablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT)) {
            return _doStableExactBptInForOneTokenOutReplacements(userData, exitKind);
        } else if (exitKind == uint8(LegacyStablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT)) {
            return _doStableExactBptInForTokensOutReplacements(userData, exitKind);
        } else {
            // All other exit kinds are 'given out' (i.e the parameter is a token amount),
            // so we don't do replacements for those.
            return userData;
        }
    }

    // For the first deployment of ComposableStablePool
    function _doComposableStableExitChainedReferenceReplacements(bytes memory userData) private returns (bytes memory) {
        uint8 exitKind = uint8(StablePoolUserData.exitKind(userData));

        if (exitKind == uint8(ComposableStablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT)) {
            return _doStableExactBptInForOneTokenOutReplacements(userData, exitKind);
        } else {
            // All other exit kinds are 'given out' (i.e the parameter is a token amount),
            // so we don't do replacements for those.
            return userData;
        }
    }

    // For ComposableStablePool V2 and V3
    function _doComposableStableV2ExitChainedReferenceReplacements(bytes memory userData)
        private
        returns (bytes memory)
    {
        uint8 exitKind = uint8(StablePoolUserData.exitKind(userData));

        if (exitKind == uint8(StablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT)) {
            return _doStableExactBptInForOneTokenOutReplacements(userData, exitKind);
        } else if (exitKind == uint8(StablePoolUserData.ExitKind.EXACT_BPT_IN_FOR_ALL_TOKENS_OUT)) {
            return _doStableExactBptInForTokensOutReplacements(userData, exitKind);
        } else {
            // All other exit kinds are 'given out' (i.e the parameter is a token amount),
            // so we don't do replacements for those.
            return userData;
        }
    }

    // Shared Stable Exit recoding functions

    // The following two functions perform the actual recoding, which involves parsing and re-encoding the userData.
    // The encoding of the actual arguments is uniform across pool kinds, which allows these recoding functions to be
    // shared. However, the ExitKind ID itself can vary, so it must be passed in from each specific pool kind handler.

    function _doStableExactBptInForOneTokenOutReplacements(bytes memory userData, uint8 exitKind)
        private
        returns (bytes memory)
    {
        (uint256 bptAmountIn, uint256 tokenIndex) = StablePoolUserData.exactBptInForTokenOut(userData);

        if (_isChainedReference(bptAmountIn)) {
            bptAmountIn = _getChainedReferenceValue(bptAmountIn);
            return abi.encode(exitKind, bptAmountIn, tokenIndex);
        } else {
            // Save gas by only re-encoding the data if we actually performed a replacement
            return userData;
        }
    }

    function _doStableExactBptInForTokensOutReplacements(bytes memory userData, uint8 exitKind)
        private
        returns (bytes memory)
    {
        uint256 bptAmountIn = StablePoolUserData.exactBptInForTokensOut(userData);

        if (_isChainedReference(bptAmountIn)) {
            bptAmountIn = _getChainedReferenceValue(bptAmountIn);
            return abi.encode(exitKind, bptAmountIn);
        } else {
            // Save gas by only re-encoding the data if we actually performed a replacement
            return userData;
        }
    }
}

/*
    For reference:

    StablePoolUserData (applies to ComposableStablePool V2+):

    enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT }
    enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT, EXACT_BPT_IN_FOR_ALL_TOKENS_OUT }

    WeightedPoolUserData:

    enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT, ALL_TOKENS_IN_FOR_EXACT_BPT_OUT }
    enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }

    StablePhantomPools can only be exited proportionally when the pool is paused: and the pause window has expired.
    They have their own enum:

    enum ExitKindPhantom { EXACT_BPT_IN_FOR_TOKENS_OUT }
*/

// Applies to StablePool, MetaStablePool, StablePool V2
library LegacyStablePoolUserData {
    enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }
    enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }
}

// Applies to the first deployment of ComposableStablePool (pre-Versioning)
library ComposableStablePoolUserData {
    enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }
    enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT }
}

File 78 of 79 : VaultPermit.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20Permit.sol";
import "@balancer-labs/v2-interfaces/contracts/solidity-utils/openzeppelin/IERC20PermitDAI.sol";
import "@balancer-labs/v2-interfaces/contracts/vault/IVault.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title VaultPermit
 * @notice Allows users to use permit (where supported) to approve the Balancer Vault to use their tokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract VaultPermit is IBaseRelayerLibrary {
    function vaultPermit(
        IERC20Permit token,
        address owner,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public payable {
        token.permit(owner, address(getVault()), value, deadline, v, r, s);
    }

    function vaultPermitDAI(
        IERC20PermitDAI token,
        address holder,
        uint256 nonce,
        uint256 expiry,
        bool allowed,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public payable {
        token.permit(holder, address(getVault()), nonce, expiry, allowed, v, r, s);
    }
}

File 79 of 79 : YearnWrapping.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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-interfaces/contracts/standalone-utils/IYearnTokenVault.sol";

import "./IBaseRelayerLibrary.sol";

/**
 * @title YearnWrapping
 * @notice Allows users to wrap and unwrap Yearn tokens
 * @dev All functions must be payable so they can be called from a multicall involving ETH
 */
abstract contract YearnWrapping is IBaseRelayerLibrary {
    function wrapYearn(
        IYearnTokenVault wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        IERC20 underlying = IERC20(wrappedToken.token());

        amount = _resolveAmountPullTokenAndApproveSpender(underlying, address(wrappedToken), amount, sender);

        uint256 receivedWrappedAmount = wrappedToken.deposit(amount, recipient);

        _setChainedReference(outputReference, receivedWrappedAmount);
    }

    function unwrapYearn(
        IYearnTokenVault wrappedToken,
        address sender,
        address recipient,
        uint256 amount,
        uint256 outputReference
    ) external payable {
        amount = _resolveAmountAndPullToken(IERC20(address(wrappedToken)), amount, sender);

        uint256 mainAmount = wrappedToken.withdraw(amount, recipient);

        _setChainedReference(outputReference, mainAmount);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 9999
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IVault","name":"vault","type":"address"},{"internalType":"contract IMasterChef","name":"masterChef","type":"address"},{"internalType":"contract IBooMirrorWorld","name":"mirrorWorld","type":"address"},{"internalType":"contract IFBeetsBar","name":"fBeetsBar","type":"address"},{"internalType":"contract IReliquary","name":"reliquary","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approveVault","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"enum IVault.SwapKind","name":"kind","type":"uint8"},{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"assetInIndex","type":"uint256"},{"internalType":"uint256","name":"assetOutIndex","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"internalType":"struct IVault.BatchSwapStep[]","name":"swaps","type":"tuple[]"},{"internalType":"contract IAsset[]","name":"assets","type":"address[]"},{"components":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"},{"internalType":"address payable","name":"recipient","type":"address"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct IVault.FundManagement","name":"funds","type":"tuple"},{"internalType":"int256[]","name":"limits","type":"int256[]"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"components":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"uint256","name":"key","type":"uint256"}],"internalType":"struct VaultActions.OutputReference[]","name":"outputReferences","type":"tuple[]"}],"name":"batchSwap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"booMirrorWorldEnter","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"booMirrorWorldLeave","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"enum VaultActions.PoolKind","name":"kind","type":"uint8"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address payable","name":"recipient","type":"address"},{"components":[{"internalType":"contract IAsset[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"minAmountsOut","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct IVault.ExitPoolRequest","name":"request","type":"tuple"},{"components":[{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"uint256","name":"key","type":"uint256"}],"internalType":"struct VaultActions.OutputReference[]","name":"outputReferences","type":"tuple[]"}],"name":"exitPool","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"fBeetsBarEnter","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"fBeetsBarLeave","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"getEntrypoint","outputs":[{"internalType":"contract IBalancerRelayer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getVault","outputs":[{"internalType":"contract IVault","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"enum VaultActions.PoolKind","name":"kind","type":"uint8"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"components":[{"internalType":"contract IAsset[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"maxAmountsIn","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"}],"internalType":"struct IVault.JoinPoolRequest","name":"request","type":"tuple"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"joinPool","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"enum IVault.UserBalanceOpKind","name":"kind","type":"uint8"},{"internalType":"contract IAsset","name":"asset","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address payable","name":"recipient","type":"address"}],"internalType":"struct IVault.UserBalanceOp[]","name":"ops","type":"tuple[]"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"manageUserBalance","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint256","name":"pid","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"masterChefDeposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"ref","type":"uint256"}],"name":"peekChainedReferenceValue","outputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint256","name":"poolId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"reliquaryCreateRelicAndDeposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint256","name":"relicId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"reliquaryDeposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"relicIds","type":"uint256[]"},{"internalType":"address","name":"recipient","type":"address"}],"name":"reliquaryHarvestAll","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"relicId","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"reliquaryWithdrawAndHarvest","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"relayer","type":"address"},{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"bytes","name":"authorisation","type":"bytes"}],"name":"setRelayerApproval","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"enum IVault.SwapKind","name":"kind","type":"uint8"},{"internalType":"contract IAsset","name":"assetIn","type":"address"},{"internalType":"contract IAsset","name":"assetOut","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"internalType":"struct IVault.SingleSwap","name":"singleSwap","type":"tuple"},{"components":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"},{"internalType":"address payable","name":"recipient","type":"address"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct IVault.FundManagement","name":"funds","type":"tuple"},{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"swap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract ITarotSupplyVault","name":"supplyVault","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"tarotSupplyVaultEnter","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract ITarotSupplyVault","name":"supplyVault","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"tarotSupplyVaultLeave","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IBeefyVault","name":"vaultToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"unwrapBeefyVaultToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC4626","name":"wrappedToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"unwrapERC4626","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IGearboxDieselToken","name":"wrappedToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"dieselAmount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"unwrapGearbox","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IReaperTokenVault","name":"vaultToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"unwrapReaperVaultToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IYearnTokenVault","name":"wrappedToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"unwrapYearn","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC20Permit","name":"token","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"vaultPermit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC20PermitDAI","name":"token","type":"address"},{"internalType":"address","name":"holder","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"bool","name":"allowed","type":"bool"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"vaultPermitDAI","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IBeefyVault","name":"vaultToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"wrapBeefyVaultToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IERC4626","name":"wrappedToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"wrapERC4626","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IGearboxDieselToken","name":"wrappedToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"mainAmount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"wrapGearbox","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IReaperTokenVault","name":"vaultToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"wrapReaperVaultToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract IYearnTokenVault","name":"wrappedToken","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"outputReference","type":"uint256"}],"name":"wrapYearn","outputs":[],"stateMutability":"payable","type":"function"}]

Deployed Bytecode

0x6080604052600436106101fe5760003560e01c80638fe4624f1161011d578063d293f290116100b0578063ec98c3cf1161007f578063efe6910811610064578063efe6910814610459578063f3cab6851461046c578063f4dd54b014610499576101fe565b8063ec98c3cf14610433578063ecc0263714610446576101fe565b8063d293f290146103e7578063d80952d5146103fa578063db12b0321461040d578063e8210e3c14610420576101fe565b8063ae298cec116100ec578063ae298cec1461039b578063aeddf95b146103ae578063b6d24737146103c1578063bd5f67a8146103d4576101fe565b80638fe4624f1461034f5780639072d9fe14610362578063959fc17a14610375578063a7faf77f14610388576101fe565b80637532aa491161019557806380db15bd1161016457806380db15bd146103015780638b35ac8d146103145780638d64cfbc146103275780638d928af81461033a576101fe565b80637532aa491461029d57806379e7433e146102b05780637ec783bb146102c35780637fd0e5d5146102d6576101fe565b80634791781f116101d15780634791781f146102515780634f06a70b1461026457806355c6f6f7146102775780636d307ea81461028a576101fe565b8063138fdc2c14610203578063183694461461021857806326a228f51461022b5780632e6272ea1461023e575b600080fd5b610216610211366004614caa565b6104ac565b005b610216610226366004614f11565b6106af565b610216610239366004614870565b6108b8565b61021661024c366004615068565b61097c565b61021661025f366004614caa565b610a9c565b610216610272366004614caa565b610b21565b610216610285366004614870565b610c32565b610216610298366004614caa565b610caf565b6102166102ab36600461480c565b610cea565b6102166102be366004614b05565b610f88565b6102166102d136600461480c565b611117565b3480156102e257600080fd5b506102eb6113bf565b6040516102f891906153ab565b60405180910390f35b61021661030f3660046148b5565b6113e3565b610216610322366004614caa565b6114e7565b610216610335366004614d85565b611581565b34801561034657600080fd5b506102eb6115fb565b61021661035d366004614c1a565b61161f565b610216610370366004614992565b611856565b610216610383366004614d04565b611c06565b610216610396366004614942565b611c83565b6102166103a9366004614caa565b611fda565b6102166103bc366004614caa565b61230a565b6102166103cf366004614df3565b612347565b6102166103e2366004614870565b612381565b6102166103f5366004614caa565b6123fe565b610216610408366004614b71565b612584565b61021661041b366004614870565b612b12565b61021661042e366004614caa565b612b8f565b610216610441366004614caa565b612d30565b610216610454366004614a5c565b612f5c565b610216610467366004614caa565b61305e565b34801561047857600080fd5b5061048c610487366004615156565b61309d565b6040516102f891906159ff565b6102166104a7366004614caa565b6130af565b6000856001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104e757600080fd5b505afa1580156104fb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061051f91906147f0565b90506000816001600160a01b0316632495a5996040518163ffffffff1660e01b815260040160206040518083038186803b15801561055c57600080fd5b505afa158015610570573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061059491906147f0565b90506105a2818386896131db565b6040517f9aa5d4620000000000000000000000000000000000000000000000000000000081529094506001600160a01b03831690639aa5d462906105ef9087908990600090600401615a3e565b600060405180830381600087803b15801561060957600080fd5b505af115801561061d573d6000803e3d6000fd5b505050506106a683836001600160a01b0316634d778ad1876040518263ffffffff1660e01b815260040161065191906159ff565b60206040518083038186803b15801561066957600080fd5b505afa15801561067d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106a1919061516e565b613206565b50505050505050565b336106bd60208901896147d4565b6001600160a01b031614806106e65750306106db60208901896147d4565b6001600160a01b0316145b61070b5760405162461bcd60e51b81526004016107029061582a565b60405180910390fd5b60005b8a518110156107705760008b828151811061072557fe5b602002602001015160600151905061073c8161321e565b156107675761074a81613269565b8c838151811061075657fe5b602002602001015160600181815250505b5060010161070e565b50606061077b6115fb565b6001600160a01b031663945bcec9858e8e8e8e8e8e8e8e6040518a63ffffffff1660e01b81526004016107b5989796959493929190615721565b6000604051808303818588803b1580156107ce57600080fd5b505af11580156107e2573d6000803e3d6000fd5b50505050506040513d6000823e601f3d908101601f1916820160405261080b91908101906149cc565b905060005b828110156108a95761083684848381811061082757fe5b9050604002016020013561321e565b6108525760405162461bcd60e51b81526004016107029061593d565b6108a184848381811061086157fe5b9050604002016020013561089c8487878681811061087b57fe5b905060400201600001358151811061088f57fe5b6020026020010151613294565b6132a0565b600101610810565b50505050505050505050505050565b6109767f000000000000000000000000fcef8a994209d6916eb2c86cdd2afd60aa6f54b17f000000000000000000000000fcef8a994209d6916eb2c86cdd2afd60aa6f54b16001600160a01b03166319d152fa6040518163ffffffff1660e01b815260040160206040518083038186803b15801561093557600080fd5b505afa158015610949573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061096d91906147f0565b868686866132b3565b50505050565b3361098a60208701876147d4565b6001600160a01b031614806109b35750306109a860208701876147d4565b6001600160a01b0316145b6109cf5760405162461bcd60e51b81526004016107029061582a565b6109dc866080015161321e565b156109f4576109ee8660800151613269565b60808701525b60006109fe6115fb565b6001600160a01b03166352bbbe2984898989896040518663ffffffff1660e01b8152600401610a309493929190615974565b6020604051808303818588803b158015610a4957600080fd5b505af1158015610a5d573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190610a82919061516e565b9050610a8d8261321e565b156106a6576106a682826132a0565b610b1a85866001600160a01b0316636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b158015610ad957600080fd5b505afa158015610aed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b1191906147f0565b868686866135d7565b5050505050565b6000856001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b5c57600080fd5b505afa158015610b70573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9491906147f0565b9050610ba2818785886131db565b92506000866001600160a01b0316636e553f6585876040518363ffffffff1660e01b8152600401610bd4929190615a08565b602060405180830381600087803b158015610bee57600080fd5b505af1158015610c02573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c26919061516e565b90506106a68382613206565b6109767f000000000000000000000000a48d959ae2e88f1daa7d5f611e01908106de75987f000000000000000000000000a48d959ae2e88f1daa7d5f611e01908106de75986001600160a01b0316634b3df2006040518163ffffffff1660e01b815260040160206040518083038186803b158015610ad957600080fd5b6000856001600160a01b03166338d52e0f6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b5c57600080fd5b836001600160a01b03167f0000000000000000000000008166994d9ebbe5829ec86bd81258149b87facfd36001600160a01b0316631bb5e2dc856040518263ffffffff1660e01b8152600401610d4091906159ff565b60206040518083038186803b158015610d5857600080fd5b505afa158015610d6c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9091906147f0565b6001600160a01b031614610db65760405162461bcd60e51b815260040161070290615861565b610dbf8261321e565b15610dd057610dcd82613269565b91505b6001600160a01b0386163014610e13576001600160a01b0386163314610e085760405162461bcd60e51b81526004016107029061582a565b610e138685846137f6565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000081526001600160a01b0385169063095ea7b390610e7a907f0000000000000000000000008166994d9ebbe5829ec86bd81258149b87facfd39086906004016154fd565b602060405180830381600087803b158015610e9457600080fd5b505af1158015610ea8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ecc9190614b55565b506040517f8dbdbe6d0000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000008166994d9ebbe5829ec86bd81258149b87facfd31690638dbdbe6d90610f3690869086908a90600401615a5d565b600060405180830381600087803b158015610f5057600080fd5b505af1158015610f64573d6000803e3d6000fd5b50505050610f718161321e565b15610f8057610f8081836132a0565b505050505050565b60005b8251811015611112577f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec6001600160a01b0316636352211e848381518110610fcf57fe5b60200260200101516040518263ffffffff1660e01b8152600401610ff391906159ff565b60206040518083038186803b15801561100b57600080fd5b505afa15801561101f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061104391906147f0565b6001600160a01b0316336001600160a01b0316146110735760405162461bcd60e51b815260040161070290615898565b7f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec6001600160a01b03166318fccc768483815181106110ae57fe5b6020026020010151846040518363ffffffff1660e01b81526004016110d4929190615a08565b600060405180830381600087803b1580156110ee57600080fd5b505af1158015611102573d6000803e3d6000fd5b505060019092019150610f8b9050565b505050565b6111208261321e565b156111315761112e82613269565b91505b836001600160a01b03167f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec6001600160a01b0316636e7d4019856040518263ffffffff1660e01b815260040161118791906159ff565b60206040518083038186803b15801561119f57600080fd5b505afa1580156111b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111d791906147f0565b6001600160a01b0316146111fd5760405162461bcd60e51b815260040161070290615861565b6001600160a01b0386163014611240576001600160a01b03861633146112355760405162461bcd60e51b81526004016107029061582a565b6112408685846137f6565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000081526001600160a01b0385169063095ea7b3906112a7907f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec9086906004016154fd565b602060405180830381600087803b1580156112c157600080fd5b505af11580156112d5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112f99190614b55565b506040517f6705fcf30000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec1690636705fcf39061136390889087908790600401615516565b602060405180830381600087803b15801561137d57600080fd5b505af1158015611391573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113b5919061516e565b50610f718161321e565b7f000000000000000000000000c048a505c570f47d8ada5046a148021d5dc3420e90565b6001600160a01b0384163014806113f8575082155b6114145760405162461bcd60e51b8152600401610702906158cf565b606063fa6e671d60e01b338686604051602401611433939291906153bf565b60408051601f19818403018152918152602080830180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff0000000000000000000000000000000000000000000000000000000090951694909417909352516114a2928691869101615378565b60408051601f198184030181529190529050610f806001600160a01b037f00000000000000000000000020dd72ed959b6147912c2e529f0a0c651c33c9ce1682613892565b6114f285838661390c565b91506000856001600160a01b031662f714ce84866040518363ffffffff1660e01b8152600401611523929190615a08565b602060405180830381600087803b15801561153d57600080fd5b505af1158015611551573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611575919061516e565b9050610f808282613206565b866001600160a01b031663d505accf876115996115fb565b88888888886040518863ffffffff1660e01b81526004016115c097969594939291906154a0565b600060405180830381600087803b1580156115da57600080fd5b505af11580156115ee573d6000803e3d6000fd5b5050505050505050505050565b7f00000000000000000000000020dd72ed959b6147912c2e529f0a0c651c33c9ce90565b6001600160a01b03851633148061163e57506001600160a01b03851630145b61165a5760405162461bcd60e51b81526004016107029061582a565b60006116658861395c565b905060006116728361321e565b61167d576000611712565b6040517f70a082310000000000000000000000000000000000000000000000000000000081526001600160a01b038316906370a08231906116c29089906004016153ab565b60206040518083038186803b1580156116da57600080fd5b505afa1580156116ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611712919061516e565b9050611722888660400151613962565b604086015261172f6115fb565b6001600160a01b031663b95cac28858b8a8a8a6040518663ffffffff1660e01b8152600401611761949392919061567b565b6000604051808303818588803b15801561177a57600080fd5b505af115801561178e573d6000803e3d6000fd5b505050505061179c8361321e565b1561184b576040517f70a082310000000000000000000000000000000000000000000000000000000081526000906001600160a01b038416906370a08231906117e9908a906004016153ab565b60206040518083038186803b15801561180157600080fd5b505afa158015611815573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611839919061516e565b90506118498461089c83856139e9565b505b505050505050505050565b61185f8261321e565b156118705761186d82613269565b91505b6040517f6352211e0000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec1690636352211e906118d59086906004016159ff565b60206040518083038186803b1580156118ed57600080fd5b505afa158015611901573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061192591906147f0565b6001600160a01b0316336001600160a01b0316146119555760405162461bcd60e51b815260040161070290615898565b61195d614391565b6040517fe48dc1350000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec169063e48dc135906119c29087906004016159ff565b60c06040518083038186803b1580156119da57600080fd5b505afa1580156119ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a12919061500d565b905060007f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec6001600160a01b0316636e7d401983608001516040518263ffffffff1660e01b8152600401611a6691906159ff565b60206040518083038186803b158015611a7e57600080fd5b505afa158015611a92573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ab691906147f0565b6040517fd1abb9070000000000000000000000000000000000000000000000000000000081529091506001600160a01b037f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec169063d1abb90790611b2290879089908b90600401615a5d565b600060405180830381600087803b158015611b3c57600080fd5b505af1158015611b50573d6000803e3d6000fd5b50506040517fa9059cbb0000000000000000000000000000000000000000000000000000000081526001600160a01b038416925063a9059cbb9150611b9b90899088906004016154fd565b602060405180830381600087803b158015611bb557600080fd5b505af1158015611bc9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bed9190614b55565b50611bf78361321e565b15610f8057610f8083856132a0565b876001600160a01b0316638fcbaf0c88611c1e6115fb565b8989898989896040518963ffffffff1660e01b8152600401611c47989796959493929190615457565b600060405180830381600087803b158015611c6157600080fd5b505af1158015611c75573d6000803e3d6000fd5b505050505050505050505050565b611c8c8261321e565b15611c9d57611c9a82613269565b91505b611ca5614391565b6040517fe48dc1350000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec169063e48dc13590611d0a9087906004016159ff565b60c06040518083038186803b158015611d2257600080fd5b505afa158015611d36573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d5a919061500d565b9050846001600160a01b03167f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec6001600160a01b0316636e7d401983608001516040518263ffffffff1660e01b8152600401611db691906159ff565b60206040518083038186803b158015611dce57600080fd5b505afa158015611de2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e0691906147f0565b6001600160a01b031614611e2c5760405162461bcd60e51b815260040161070290615861565b6001600160a01b0386163014611e6f576001600160a01b0386163314611e645760405162461bcd60e51b81526004016107029061582a565b611e6f8686856137f6565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000081526001600160a01b0386169063095ea7b390611ed6907f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec9087906004016154fd565b602060405180830381600087803b158015611ef057600080fd5b505af1158015611f04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f289190614b55565b506040517fe2bbb1580000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000001ed6411670c709f4e163854654bd52c74e66d7ec169063e2bbb15890611f90908690889060040161539d565b600060405180830381600087803b158015611faa57600080fd5b505af1158015611fbe573d6000803e3d6000fd5b50505050611fcb8261321e565b15610f8057610f8082846132a0565b611fe38261321e565b15611ff457611ff182613269565b91505b6000856001600160a01b0316631f1fcd516040518163ffffffff1660e01b815260040160206040518083038186803b15801561202f57600080fd5b505afa158015612043573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061206791906147f0565b90506001600160a01b03851630146120ac576001600160a01b03851633146120a15760405162461bcd60e51b81526004016107029061582a565b6120ac8582856137f6565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000081526001600160a01b0382169063095ea7b3906120f390899087906004016154fd565b602060405180830381600087803b15801561210d57600080fd5b505af1158015612121573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121459190614b55565b506040517fb6b55f250000000000000000000000000000000000000000000000000000000081526001600160a01b0387169063b6b55f259061218b9086906004016159ff565b600060405180830381600087803b1580156121a557600080fd5b505af11580156121b9573d6000803e3d6000fd5b50506040517f70a08231000000000000000000000000000000000000000000000000000000008152600092506001600160a01b03891691506370a08231906122059030906004016153ab565b60206040518083038186803b15801561221d57600080fd5b505afa158015612231573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612255919061516e565b6040517fa9059cbb0000000000000000000000000000000000000000000000000000000081529091506001600160a01b0388169063a9059cbb9061229f90889085906004016154fd565b602060405180830381600087803b1580156122b957600080fd5b505af11580156122cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122f19190614b55565b506122fb8361321e565b156106a6576106a683826132a0565b610b1a85866001600160a01b0316636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b15801561093557600080fd5b6123508161321e565b156123615761235e81613269565b90505b61237d61236c6115fb565b6001600160a01b03841690836139ff565b5050565b6109767f000000000000000000000000fcef8a994209d6916eb2c86cdd2afd60aa6f54b17f000000000000000000000000fcef8a994209d6916eb2c86cdd2afd60aa6f54b16001600160a01b03166319d152fa6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ad957600080fd5b61240985838661390c565b6040517f2e1a7d4d0000000000000000000000000000000000000000000000000000000081529092506001600160a01b03861690632e1a7d4d906124519085906004016159ff565b600060405180830381600087803b15801561246b57600080fd5b505af115801561247f573d6000803e3d6000fd5b505050506000856001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156124be57600080fd5b505afa1580156124d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124f691906147f0565b90506000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161252691906153ab565b60206040518083038186803b15801561253e57600080fd5b505afa158015612552573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612576919061516e565b90506106a682868386613b4b565b6001600160a01b0385163314806125a357506001600160a01b03851630145b6125bf5760405162461bcd60e51b81526004016107029061582a565b60608167ffffffffffffffff811180156125d857600080fd5b50604051908082528060200260200182016040528015612602578160200160208202803683370190505b50905060608267ffffffffffffffff8111801561261e57600080fd5b50604051908082528060200260200182016040528015612648578160200160208202803683370190505b50905060005b838110156127b85761266585858381811061082757fe5b6126815760405162461bcd60e51b81526004016107029061593d565b855160009086868481811061269257fe5b90506040020160000135815181106126a657fe5b602002602001015190508660600151156126f4576126c381613b79565b8483815181106126cf57fe5b60200260200101906001600160a01b031690816001600160a01b0316815250506127af565b6126fd81613b7c565b61278a5761270a81613b79565b6001600160a01b03166370a08231896040518263ffffffff1660e01b815260040161273591906153ab565b60206040518083038186803b15801561274d57600080fd5b505afa158015612761573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612785919061516e565b612796565b876001600160a01b0316315b8383815181106127a257fe5b6020026020010181815250505b5060010161264e565b5084606001511561284f576127cb6115fb565b6001600160a01b0316630f5a6efa87846040518363ffffffff1660e01b81526004016127f89291906153e3565b60006040518083038186803b15801561281057600080fd5b505afa158015612824573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261284c9190810190614ad2565b90505b61285d888660400151613b89565b604086015261286a6115fb565b6001600160a01b0316638bdb39138a8989896040518563ffffffff1660e01b815260040161289b949392919061567b565b600060405180830381600087803b1580156128b557600080fd5b505af11580156128c9573d6000803e3d6000fd5b50606092508591505067ffffffffffffffff811180156128e857600080fd5b50604051908082528060200260200182016040528015612912578160200160208202803683370190505b5090508560600151156129af576129276115fb565b6001600160a01b0316630f5a6efa88856040518363ffffffff1660e01b81526004016129549291906153e3565b60006040518083038186803b15801561296c57600080fd5b505afa158015612980573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526129a89190810190614ad2565b9050612aad565b60005b84811015612aab5786516000908787848181106129cb57fe5b90506040020160000135815181106129df57fe5b602002602001015190506129f281613b7c565b612a7f576129ff81613b79565b6001600160a01b03166370a082318a6040518263ffffffff1660e01b8152600401612a2a91906153ab565b60206040518083038186803b158015612a4257600080fd5b505afa158015612a56573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a7a919061516e565b612a8b565b886001600160a01b0316315b838381518110612a9757fe5b6020908102919091010152506001016129b2565b505b60005b848110156115ee57612b0a868683818110612ac757fe5b9050604002016020013561089c858481518110612ae057fe5b6020026020010151858581518110612af457fe5b60200260200101516139e990919063ffffffff16565b600101612ab0565b6109767f000000000000000000000000a48d959ae2e88f1daa7d5f611e01908106de75987f000000000000000000000000a48d959ae2e88f1daa7d5f611e01908106de75986001600160a01b0316634b3df2006040518163ffffffff1660e01b815260040160206040518083038186803b15801561093557600080fd5b6000856001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b158015612bca57600080fd5b505afa158015612bde573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c0291906147f0565b9050612c10818785886131db565b6040517fb6b55f250000000000000000000000000000000000000000000000000000000081529093506001600160a01b0387169063b6b55f2590612c589086906004016159ff565b600060405180830381600087803b158015612c7257600080fd5b505af1158015612c86573d6000803e3d6000fd5b50506040517f70a08231000000000000000000000000000000000000000000000000000000008152600092506001600160a01b03891691506370a0823190612cd29030906004016153ab565b60206040518083038186803b158015612cea57600080fd5b505afa158015612cfe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d22919061516e565b90506106a687868386613b4b565b612d398261321e565b15612d4a57612d4782613269565b91505b6001600160a01b0384163014612d8d576001600160a01b0384163314612d825760405162461bcd60e51b81526004016107029061582a565b612d8d8486846137f6565b6000856001600160a01b0316631f1fcd516040518163ffffffff1660e01b815260040160206040518083038186803b158015612dc857600080fd5b505afa158015612ddc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e0091906147f0565b6040517f2e1a7d4d0000000000000000000000000000000000000000000000000000000081529091506001600160a01b03871690632e1a7d4d90612e489086906004016159ff565b600060405180830381600087803b158015612e6257600080fd5b505af1158015612e76573d6000803e3d6000fd5b50506040517f70a08231000000000000000000000000000000000000000000000000000000008152600092506001600160a01b03841691506370a0823190612ec29030906004016153ab565b60206040518083038186803b158015612eda57600080fd5b505afa158015612eee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f12919061516e565b6040517fa9059cbb0000000000000000000000000000000000000000000000000000000081529091506001600160a01b0383169063a9059cbb9061229f90889085906004016154fd565b60005b82811015612ff05733848483818110612f7457fe5b905060a002016060016020810190612f8c91906147d4565b6001600160a01b03161480612fcc575030848483818110612fa957fe5b905060a002016060016020810190612fc191906147d4565b6001600160a01b0316145b612fe85760405162461bcd60e51b81526004016107029061582a565b600101612f5f565b50612ff96115fb565b6001600160a01b0316630e8e3e848285856040518463ffffffff1660e01b8152600401613027929190615537565b6000604051808303818588803b15801561304057600080fd5b505af1158015613054573d6000803e3d6000fd5b5050505050505050565b61306985838661390c565b91506000856001600160a01b031663ba0876528486306040518463ffffffff1660e01b815260040161152393929190615a1f565b60006130a882613bff565b9392505050565b6130ba85838661390c565b91506000856001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156130f757600080fd5b505afa15801561310b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061312f91906147f0565b6040517f05fe138b0000000000000000000000000000000000000000000000000000000081529091506001600160a01b038216906305fe138b906131799086908890600401615a08565b600060405180830381600087803b15801561319357600080fd5b505af11580156131a7573d6000803e3d6000fd5b50505050610f8082826001600160a01b0316635427c938866040518263ffffffff1660e01b815260040161065191906159ff565b60006131e885848461390c565b90506131fe6001600160a01b03861685836139ff565b949350505050565b61320f8261321e565b1561237d5761237d82826132a0565b7fba100000000000000000000000000000000000000000000000000000000000007ffff00000000000000000000000000000000000000000000000000000000000008216145b919050565b600080600061327784613bff565b9150915061328484613c16565b156130a857600082559392505050565b60ff81901d9081180390565b60006132ab83613c5d565b919091555050565b6132bc8261321e565b156132cd576132ca82613269565b91505b6001600160a01b0384163014613310576001600160a01b03841633146133055760405162461bcd60e51b81526004016107029061582a565b6133108486846137f6565b6040517f70a082310000000000000000000000000000000000000000000000000000000081526000906001600160a01b038816906370a08231906133589030906004016153ab565b60206040518083038186803b15801561337057600080fd5b505afa158015613384573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133a8919061516e565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000081529091506001600160a01b0387169063095ea7b3906133f2908a9087906004016154fd565b602060405180830381600087803b15801561340c57600080fd5b505af1158015613420573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134449190614b55565b506040517fa59f3e0c0000000000000000000000000000000000000000000000000000000081526001600160a01b0388169063a59f3e0c9061348a9086906004016159ff565b600060405180830381600087803b1580156134a457600080fd5b505af11580156134b8573d6000803e3d6000fd5b50505050600081886001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016134eb91906153ab565b60206040518083038186803b15801561350357600080fd5b505afa158015613517573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061353b919061516e565b039050876001600160a01b031663a9059cbb86836040518363ffffffff1660e01b815260040161356c9291906154fd565b602060405180830381600087803b15801561358657600080fd5b505af115801561359a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135be9190614b55565b506135c88361321e565b156130545761305483826132a0565b6135e08261321e565b156135f1576135ee82613269565b91505b6001600160a01b0384163014613634576001600160a01b03841633146136295760405162461bcd60e51b81526004016107029061582a565b6136348487846137f6565b6040517f70a082310000000000000000000000000000000000000000000000000000000081526000906001600160a01b038716906370a082319061367c9030906004016153ab565b60206040518083038186803b15801561369457600080fd5b505afa1580156136a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136cc919061516e565b6040517f67dfd4c90000000000000000000000000000000000000000000000000000000081529091506001600160a01b038816906367dfd4c9906137149086906004016159ff565b600060405180830381600087803b15801561372e57600080fd5b505af1158015613742573d6000803e3d6000fd5b50505050600081876001600160a01b03166370a08231306040518263ffffffff1660e01b815260040161377591906153ab565b60206040518083038186803b15801561378d57600080fd5b505afa1580156137a1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137c5919061516e565b039050866001600160a01b031663a9059cbb86836040518363ffffffff1660e01b815260040161356c9291906154fd565b8061380057611112565b60408051600180825281830190925260609160208083019080368337019050509050828160008151811061383057fe5b6001600160a01b039290921660209283029190910190910152604080516001808252818301909252606091816020016020820280368337019050509050828160008151811061387b57fe5b602002602001018181525050610b1a858383613cbb565b606060006060846001600160a01b0316846040516138b0919061535c565b6000604051808303816000865af19150503d80600081146138ed576040519150601f19603f3d011682016040523d82523d6000602084013e6138f2565b606091505b50915091506139018282613df5565b925050505b92915050565b600061391783613e1f565b90506001600160a01b03821630146130a8576001600160a01b03821633146139515760405162461bcd60e51b81526004016107029061582a565b6130a88285836137f6565b60601c90565b6060600083600381111561397257fe5b14156139885761398182613e3d565b9050613906565b600183600381111561399657fe5b14806139ad575060028360038111156139ab57fe5b145b806139c3575060038360038111156139c157fe5b145b156139d15761398182613e3d565b60405162461bcd60e51b815260040161070290615906565b60006139f9838311156001613e7a565b50900390565b8015801590613aa357506040517fdd62ed3e0000000000000000000000000000000000000000000000000000000081526001600160a01b0384169063dd62ed3e90613a50903090869060040161543d565b60206040518083038186803b158015613a6857600080fd5b505afa158015613a7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613aa0919061516e565b15155b15613b2c57613b2c8363095ea7b360e01b846000604051602401613ac89291906154e1565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff0000000000000000000000000000000000000000000000000000000090931692909217909152613e88565b6111128363095ea7b360e01b8484604051602401613ac89291906154fd565b6001600160a01b0383163014613b6f57613b6f6001600160a01b0385168484613f28565b6109768183613206565b90565b6001600160a01b03161590565b60606000836003811115613b9957fe5b1415613ba85761398182613f47565b6001836003811115613bb657fe5b1415613bc55761398182613f90565b6002836003811115613bd357fe5b1415613be25761398182613fd6565b6003836003811115613bf057fe5b14156139d15761398182614002565b600080613c0b83613c5d565b915081549050915091565b7fffff000000000000000000000000000000000000000000000000000000000000167fba100000000000000000000000000000000000000000000000000000000000001490565b60006001613c6a83614035565b7fae1dc54057af8e8e5ce068cdd4383149c7efcb30e8fb95b592ee1594367fb509604051602001613c9c92919061539d565b60408051808303601f1901815291905280516020909101200392915050565b6060825167ffffffffffffffff81118015613cd557600080fd5b50604051908082528060200260200182016040528015613d0f57816020015b613cfc6143c7565b815260200190600190039081613cf45790505b50905060005b8351811015613da7576040805160a081019091528060038152602001858381518110613d3d57fe5b60200260200101516001600160a01b03168152602001848381518110613d5f57fe5b60200260200101518152602001866001600160a01b03168152602001306001600160a01b0316815250828281518110613d9457fe5b6020908102919091010152600101613d15565b50613db06115fb565b6001600160a01b0316630e8e3e84826040518263ffffffff1660e01b8152600401613ddb91906155e5565b600060405180830381600087803b15801561304057600080fd5b60608215613e04575080613906565b815115613e145781518083602001fd5b6139066101ae614058565b6000613e2a8261321e565b613e345781613906565b61390682613269565b60606000613e4a83614085565b90506001816003811115613e5a57fe5b1415613e7157613e698361409b565b915050613264565b82915050613264565b8161237d5761237d81614058565b60006060836001600160a01b031683604051613ea4919061535c565b6000604051808303816000865af19150503d8060008114613ee1576040519150601f19603f3d011682016040523d82523d6000602084013e613ee6565b606091505b50915091506000821415613efe573d6000803e3d6000fd5b610976815160001480613f20575081806020019051810190613f209190614b55565b6101a2613e7a565b6111128363a9059cbb60e01b8484604051602401613ac89291906154fd565b60606000613f54836140ed565b90506000816002811115613f6457fe5b1415613f7357613e6983614103565b6001816002811115613f8157fe5b1415613e7157613e6983614166565b60606000613f9d836140ed565b6002811115613fa857fe5b905060ff8116613fbc57613e6983826141b9565b60015b60ff168160ff161415613e7157613e69838261421b565b60606000613fe3836140ed565b6002811115613fee57fe5b905060ff8116613e7157613e6983826141b9565b6060600061400f836140ed565b600281111561401a57fe5b905060ff811661402e57613e6983826141b9565b6002613fbf565b7dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1690565b614082817f42414c0000000000000000000000000000000000000000000000000000000000614276565b50565b6000818060200190518101906139069190614e9d565b60608060006140a9846142d7565b915091506140b6826142fa565b6140c057836131fe565b600182826040516020016140d6939291906156ef565b604051602081830303815290604052949350505050565b6000818060200190518101906139069190614e1e565b606060008061411184614364565b9150915061411e8261321e565b1561415c5761412c82613269565b915060008282604051602001614144939291906156ce565b60405160208183030381529060405292505050613264565b8392505050613264565b606060006141738361437b565b905061417e8161321e565b15613e715761418c81613269565b90506001816040516020016141a29291906156b7565b604051602081830303815290604052915050613264565b60606000806141c785614364565b915091506141d48261321e565b15614211576141e282613269565b91508382826040516020016141f993929190615a8f565b60405160208183030381529060405292505050613906565b8492505050613906565b606060006142288461437b565b90506142338161321e565b1561426d5761424181613269565b90508281604051602001614256929190615a7c565b604051602081830303815290604052915050613906565b83915050613906565b62461bcd60e51b600090815260206004526007602452600a808404818106603090810160081b958390069590950190829004918206850160101b01602363ffffff0060e086901c160160181b0190930160c81b60445260e882901c90606490fd5b60606000828060200190518101906142ef9190614eb9565b909590945092505050565b600080805b835181101561435d57600084828151811061431657fe5b602002602001015190506143298161321e565b156143545761433781613269565b85838151811061434357fe5b602002602001018181525050600192505b506001016142ff565b5092915050565b600080828060200190518101906142ef9190614e67565b6000818060200190518101906130a89190614e3a565b6040518060c001604052806000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6040805160a081019091528060008152600060208201819052604082018190526060820181905260809091015290565b803561390681615b48565b60008083601f840112614413578182fd5b50813567ffffffffffffffff81111561442a578182fd5b602083019150836020808302850101111561444457600080fd5b9250929050565b600082601f83011261445b578081fd5b813561446e61446982615ad1565b615aaa565b81815291506020808301908481018184028601820187101561448f57600080fd5b60005b848110156144b75781356144a581615b48565b84529282019290820190600101614492565b505050505092915050565b600082601f8301126144d2578081fd5b81356144e061446982615ad1565b818152915060208083019084810160005b848110156144b7578135870160a080601f19838c0301121561451257600080fd5b61451b81615aaa565b85830135815260408084013587830152606080850135828401526080915081850135818401525082840135925067ffffffffffffffff83111561455d57600080fd5b61456b8c888587010161468d565b908201528652505092820192908201906001016144f1565b60008083601f840112614594578182fd5b50813567ffffffffffffffff8111156145ab578182fd5b60208301915083602060408302850101111561444457600080fd5b600082601f8301126145d6578081fd5b81356145e461446982615ad1565b81815291506020808301908481018184028601820187101561460557600080fd5b60005b848110156144b757813584529282019290820190600101614608565b600082601f830112614634578081fd5b815161464261446982615ad1565b81815291506020808301908481018184028601820187101561466357600080fd5b60005b848110156144b757815184529282019290820190600101614666565b803561390681615b5d565b600082601f83011261469d578081fd5b813567ffffffffffffffff8111156146b3578182fd5b6146c66020601f19601f84011601615aaa565b91508082528360208285010111156146dd57600080fd5b8060208401602084013760009082016020015292915050565b80356002811061390657600080fd5b600060808284031215614716578081fd5b6147206080615aaa565b9050813567ffffffffffffffff8082111561473a57600080fd5b6147468583860161444b565b8352602084013591508082111561475c57600080fd5b614768858386016145c6565b6020840152604084013591508082111561478157600080fd5b5061478e8482850161468d565b6040830152506147a18360608401614682565b606082015292915050565b6000608082840312156147bd578081fd5b50919050565b803560ff8116811461390657600080fd5b6000602082840312156147e5578081fd5b81356130a881615b48565b600060208284031215614801578081fd5b81516130a881615b48565b60008060008060008060c08789031215614824578182fd5b863561482f81615b48565b9550602087013561483f81615b48565b9450604087013561484f81615b48565b959894975094956060810135955060808101359460a0909101359350915050565b60008060008060808587031215614885578182fd5b843561489081615b48565b935060208501356148a081615b48565b93969395505050506040820135916060013590565b600080600080606085870312156148ca578182fd5b84356148d581615b48565b935060208501356148e581615b5d565b9250604085013567ffffffffffffffff80821115614901578384fd5b818701915087601f830112614914578384fd5b813581811115614922578485fd5b886020828501011115614933578485fd5b95989497505060200194505050565b600080600080600060a08688031215614959578283fd5b853561496481615b48565b9450602086013561497481615b48565b94979496505050506040830135926060810135926080909101359150565b600080600080608085870312156149a7578182fd5b84356149b281615b48565b966020860135965060408601359560600135945092505050565b600060208083850312156149de578182fd5b825167ffffffffffffffff8111156149f4578283fd5b8301601f81018513614a04578283fd5b8051614a1261446982615ad1565b8181528381019083850185840285018601891015614a2e578687fd5b8694505b83851015614a50578051835260019490940193918501918501614a32565b50979650505050505050565b600080600060408486031215614a70578081fd5b833567ffffffffffffffff80821115614a87578283fd5b818601915086601f830112614a9a578283fd5b813581811115614aa8578384fd5b87602060a083028501011115614abc578384fd5b6020928301989097509590910135949350505050565b600060208284031215614ae3578081fd5b815167ffffffffffffffff811115614af9578182fd5b6131fe84828501614624565b60008060408385031215614b17578182fd5b823567ffffffffffffffff811115614b2d578283fd5b614b39858286016145c6565b9250506020830135614b4a81615b48565b809150509250929050565b600060208284031215614b66578081fd5b81516130a881615b5d565b600080600080600080600060c0888a031215614b8b578485fd5b873596506020880135614b9d81615b78565b95506040880135614bad81615b48565b94506060880135614bbd81615b48565b9350608088013567ffffffffffffffff80821115614bd9578283fd5b614be58b838c01614705565b945060a08a0135915080821115614bfa578283fd5b50614c078a828b01614583565b989b979a50959850939692959293505050565b600080600080600080600060e0888a031215614c34578081fd5b873596506020880135614c4681615b78565b95506040880135614c5681615b48565b94506060880135614c6681615b48565b9350608088013567ffffffffffffffff811115614c81578182fd5b614c8d8a828b01614705565b93505060a0880135915060c0880135905092959891949750929550565b600080600080600060a08688031215614cc1578283fd5b8535614ccc81615b48565b94506020860135614cdc81615b48565b93506040860135614cec81615b48565b94979396509394606081013594506080013592915050565b600080600080600080600080610100898b031215614d20578182fd5b8835614d2b81615b48565b97506020890135614d3b81615b48565b965060408901359550606089013594506080890135614d5981615b5d565b9350614d688a60a08b016147c3565b925060c0890135915060e089013590509295985092959890939650565b600080600080600080600060e0888a031215614d9f578081fd5b8735614daa81615b48565b96506020880135614dba81615b48565b95506040880135945060608801359350614dd78960808a016147c3565b925060a0880135915060c0880135905092959891949750929550565b60008060408385031215614e05578182fd5b8235614e1081615b48565b946020939093013593505050565b600060208284031215614e2f578081fd5b81516130a881615b6b565b60008060408385031215614e4c578182fd5b8251614e5781615b6b565b6020939093015192949293505050565b600080600060608486031215614e7b578081fd5b8351614e8681615b6b565b602085015160409095015190969495509392505050565b600060208284031215614eae578081fd5b81516130a881615b78565b600080600060608486031215614ecd578081fd5b8351614ed881615b78565b602085015190935067ffffffffffffffff811115614ef4578182fd5b614f0086828701614624565b925050604084015190509250925092565b60008060008060008060008060008060006101608c8e031215614f32578485fd5b614f3c8d8d6146f6565b9a5067ffffffffffffffff8060208e01351115614f57578586fd5b614f678e60208f01358f016144c2565b9a508060408e01351115614f79578586fd5b614f898e60408f01358f01614402565b909a509850614f9b8e60608f016147ac565b97508060e08e01351115614fad578586fd5b614fbd8e60e08f01358f01614402565b90975095506101008d013594506101208d013593506101408d0135811015614fe3578283fd5b50614ff58d6101408e01358e01614583565b81935080925050509295989b509295989b9093969950565b600060c0828403121561501e578081fd5b61502860c0615aaa565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a08201528091505092915050565b6000806000806000806101208789031215615081578384fd5b863567ffffffffffffffff80821115615098578586fd5b9088019060c0828b0312156150ab578586fd5b6150b560c0615aaa565b823581526150c68b602085016146f6565b602082015260408301356150d981615b48565b60408201526150eb8b606085016143f7565b60608201526080830135608082015260a08301358281111561510b578788fd5b6151178c82860161468d565b60a08301525080985050505061513088602089016147ac565b959895975050505060a08401359360c08101359360e08201359350610100909101359150565b600060208284031215615167578081fd5b5035919050565b60006020828403121561517f578081fd5b5051919050565b6001600160a01b03169052565b60008284526020808501945082825b858110156151d05781356151b581615b48565b6001600160a01b0316875295820195908201906001016151a2565b509495945050505050565b60008284526020808501945082825b858110156151d0578135875295820195908201906001016151ea565b6000815180845260208085019450808401835b838110156151d057815187529582019590820190600101615219565b15159052565b60008151808452615253816020860160208601615afe565b601f01601f19169290920160200192915050565b8051608080845281519084018190526000916020919082019060a0860190845b818110156152ac5783516001600160a01b031683529284019291840191600101615287565b5050828501519150858103838701526152c58183615206565b92505050604083015184820360408601526152e0828261523b565b91505060608301516152f56060860182615235565b509392505050565b803561530881615b48565b6001600160a01b03908116835260208201359061532482615b5d565b901515602084015260408201359061533b82615b48565b166040830152606081013561534f81615b5d565b8015156060840152505050565b6000825161536e818460208701615afe565b9190910192915050565b6000845161538a818460208901615afe565b8201838582379092019182525092915050565b918252602082015260400190565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152901515604082015260600190565b6000604082016001600160a01b03808616845260206040818601528286518085526060870191508288019450855b8181101561542f578551851683529483019491830191600101615411565b509098975050505050505050565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039889168152969097166020870152604086019490945260608501929092521515608084015260ff1660a083015260c082015260e08101919091526101000190565b6001600160a01b0397881681529590961660208601526040850193909352606084019190915260ff16608083015260a082015260c081019190915260e00190565b6001600160a01b0392909216825260ff16602082015260400190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039390931683526020830191909152604082015260600190565b6020808252818101839052600090604080840186845b878110156155d857813561556081615b78565b61556981615b34565b83528185013561557881615b48565b6001600160a01b0316838601528184013584840152606061559b81840184615af1565b6155a782860182615186565b505060806155b781840184615af1565b6155c382860182615186565b505060a092830192919091019060010161554d565b5090979650505050505050565b602080825282518282018190526000919060409081850190868401855b8281101561566e578151805161561781615b34565b8552808701516001600160a01b031687860152858101518686015260608082015161564482880182615186565b50506080908101519061565986820183615186565b505060a0939093019290850190600101615602565b5091979650505050505050565b60008582526001600160a01b038086166020840152808516604084015250608060608301526156ad6080830184615267565b9695505050505050565b604081016156c484615b2a565b9281526020015290565b606081016156db85615b2a565b938152602081019290925260409091015290565b60006156fa85615b34565b848252606060208301526157116060830185615206565b9050826040830152949350505050565b60006101208083016157328c615b3e565b8b84526020808501929092528a5190819052610140808501928281028601909101918c8201855b828110156157d9578785037ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec00186528151805186528481015185870152604080820151908701526060808201519087015260809081015160a0918701829052906157c58188018361523b565b978601979650505090830190600101615759565b5050505083810360408501526157f0818a8c615193565b91505061580060608401886152fd565b82810360e08401526158138186886151db565b915050826101008301529998505050505050505050565b60208082526010908201527f496e636f72726563742073656e64657200000000000000000000000000000000604082015260600190565b60208082526017908201527f496e636f727265637420746f6b656e20666f7220706964000000000000000000604082015260600190565b60208082526019908201527f53656e646572206e6f74206f776e6572206f662072656c696300000000000000604082015260600190565b6020808252601f908201527f52656c617965722063616e206f6e6c7920617070726f766520697473656c6600604082015260600190565b60208082526013908201527f554e48414e444c45445f504f4f4c5f4b494e4400000000000000000000000000604082015260600190565b60208082526019908201527f696e76616c696420636861696e6564207265666572656e636500000000000000604082015260600190565b600060e08252855160e0830152602086015161598f81615b3e565b61010083015260408601516001600160a01b03908116610120840152606087015116610140830152608086015161016083015260a086015160c06101808401526159dd6101a084018261523b565b9150506159ed60208301866152fd565b60a082019390935260c0015292915050565b90815260200190565b9182526001600160a01b0316602082015260400190565b9283526001600160a01b03918216602084015216604082015260600190565b9283526001600160a01b03919091166020830152604082015260600190565b92835260208301919091526001600160a01b0316604082015260600190565b60ff929092168252602082015260400190565b60ff9390931683526020830191909152604082015260600190565b60405181810167ffffffffffffffff81118282101715615ac957600080fd5b604052919050565b600067ffffffffffffffff821115615ae7578081fd5b5060209081020190565b600082356130a881615b48565b60005b83811015615b19578181015183820152602001615b01565b838111156109765750506000910152565b6003811061408257fe5b6004811061408257fe5b6002811061408257fe5b6001600160a01b038116811461408257600080fd5b801515811461408257600080fd5b6003811061408257600080fd5b6004811061408257600080fdfea2646970667358221220e0ff0d7058fd0bb3ce53f232b824924292757610fae06823eaae6530394abc3564736f6c63430007010033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Txn Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.