ETH Price: $3,472.21 (+0.05%)

Token

Wrapped liquid staked Ether 2.0 Adapter (wstETH-adapter)
 

Overview

Max Total Supply

0.08849602457670303 wstETH-adapter

Holders

15

Market

Onchain Market Cap

$0.00

Circulating Supply Market Cap

-

Other Info

Token Contract (WITH 18 Decimals)

Filtered by Token Holder
Null: 0x000...000
Balance
0.000000000001 wstETH-adapter

Value
$0.00
0x0000000000000000000000000000000000000000
Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
# Exchange Pair Price  24H Volume % Volume
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

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

Contract Name:
Space

Compiler Version
v0.7.5+commit.eb77ed08

Optimization Enabled:
Yes with 1500 runs

Other Settings:
default evmVersion
File 1 of 32 : Space.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

// External references
import { FixedPoint } from "@balancer-labs/v2-solidity-utils/contracts/math/FixedPoint.sol";
import { Math as BasicMath } from "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol";
import { BalancerPoolToken } from "@balancer-labs/v2-pool-utils/contracts/BalancerPoolToken.sol";
import { ERC20 } from "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20.sol";
import { LogCompression } from "@balancer-labs/v2-solidity-utils/contracts/helpers/LogCompression.sol";

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

import { Errors, _require } from "./Errors.sol";
import { PoolPriceOracle } from "./oracle/PoolPriceOracle.sol";

interface AdapterLike {
    function scale() external returns (uint256);

    function scaleStored() external view returns (uint256);

    function target() external view returns (address);

    function symbol() external view returns (string memory);

    function name() external view returns (string memory);

    function getUnderlyingPrice() external view returns (uint256);
}

/*
                    SPACE
        *   '*
                *
                        *
                            *
                    *
                            *
                .                      .
                .                      ;
                :                  - --+- -
                !           .          !

*/

/// @notice A Yieldspace implementation extended such that LPs can deposit
/// [Principal Token, Yield-bearing asset], rather than [Principal Token, Underlying], while keeping the benefits of the
/// yieldspace invariant (e.g. it can hold [Principal Token, cDAI], rather than [Principal Token, DAI], while still operating
/// in "yield space" for the principal token side. See the YieldSpace paper for more https://yield.is/YieldSpace.pdf)
/// @dev We use much more internal storage here than in other Sense contracts because it
/// conforms to Balancer's own style, and we're using several Balancer functions that play nicer if we do.
/// @dev Requires an external "Adapter" contract with a `scale()` function which returns the
/// current exchange rate from Target to the Underlying asset.
contract Space is IMinimalSwapInfoPool, BalancerPoolToken, PoolPriceOracle {
    using FixedPoint for uint256;

    /* ========== STRUCTURES ========== */

    struct OracleData {
        uint16 oracleIndex;
        uint32 oracleSampleInitialTimestamp;
        bool oracleEnabled;
        int200 logInvariant;
    }

    /* ========== CONSTANTS ========== */

    /// @notice Minimum BPT we can have for this pool after initialization
    uint256 public constant MINIMUM_BPT = 1e6;

    /* ========== PUBLIC IMMUTABLES ========== */

    /// @notice Adapter address for the associated Series
    address public immutable adapter;

    /// @notice Maturity timestamp for associated Series
    uint256 public immutable maturity;

    /// @notice Principal Token index (there are only two tokens in this pool, so `targeti` is always just the complement)
    uint256 public immutable pti;

    /// @notice Yieldspace config, passed in from the Space Factory
    uint256 public immutable ts;
    uint256 public immutable g1;
    uint256 public immutable g2;

    /* ========== INTERNAL IMMUTABLES ========== */

    /// @dev Balancer pool id (as registered with the Balancer Vault)
    bytes32 internal immutable _poolId;

    /// @dev Token registered at index 0 for this pool
    IERC20 internal immutable _token0;

    /// @dev Token registered at index one for this pool
    IERC20 internal immutable _token1;

    /// @dev Factor needed to scale the PT to 18 decimals
    uint256 internal immutable _scalingFactorPT;

    /// @dev Factor needed to scale the Target token to 18 decimals
    uint256 internal immutable _scalingFactorTarget;

    /// @dev Balancer Vault
    IVault internal immutable _vault;

    /// @dev Contract that collects Balancer protocol fees
    address internal immutable _protocolFeesCollector;

    /* ========== INTERNAL MUTABLE STORAGE ========== */

    /// @dev Scale value for the yield-bearing asset's first `join` (i.e. initialization)
    uint256 internal _initScale;

    /// @dev Invariant tracking for calculating Balancer protocol fees
    uint256 internal _lastToken0Reserve;
    uint256 internal _lastToken1Reserve;

    /// @dev Oracle sample collection metadata
    OracleData internal oracleData;

    constructor(
        IVault vault,
        address _adapter,
        uint256 _maturity,
        address pt,
        uint256 _ts,
        uint256 _g1,
        uint256 _g2,
        bool _oracleEnabled
    ) BalancerPoolToken(AdapterLike(_adapter).name(), AdapterLike(_adapter).symbol()) {
        bytes32 poolId = vault.registerPool(IVault.PoolSpecialization.TWO_TOKEN);

        address target = AdapterLike(_adapter).target();
        IERC20[] memory tokens = new IERC20[](2);

        // Ensure that the array of tokens is correctly ordered
        uint256 _pti = pt < target ? 0 : 1;
        tokens[_pti] = IERC20(pt);
        tokens[1 - _pti] = IERC20(target);
        vault.registerTokens(poolId, tokens, new address[](2));

        // Set Balancer-specific pool config
        _vault = vault;
        _poolId = poolId;
        _token0 = tokens[0];
        _token1 = tokens[1];
        _protocolFeesCollector = address(vault.getProtocolFeesCollector());

        _scalingFactorPT = 10**(BasicMath.sub(uint256(18), ERC20(pt).decimals()));
        _scalingFactorTarget = 10**(BasicMath.sub(uint256(18), ERC20(target).decimals()));

        // Set Yieldspace config
        g1 = _g1; // Fees are baked into factors `g1` & `g2`,
        g2 = _g2; // see the "Fees" section of the yieldspace paper
        ts = _ts;

        // Set Space-specific slots
        pti = _pti;
        adapter = _adapter;
        maturity = _maturity;
        oracleData.oracleEnabled = _oracleEnabled;
    }

    /* ========== BALANCER VAULT HOOKS ========== */

    function onJoinPool(
        bytes32 poolId,
        address, /* sender */
        address recipient,
        uint256[] memory reserves,
        uint256 lastChangeBlock,
        uint256 protocolSwapFeePercentage,
        bytes memory userData
    ) external override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
        // Space does not have multiple join types like other Balancer pools,
        // instead, its `joinPool` always behaves like `EXACT_TOKENS_IN_FOR_BPT_OUT`

        _require(maturity >= block.timestamp, Errors.POOL_PAST_MATURITY);

        (uint256[] memory reqAmountsIn, uint256 minBptOut) = abi.decode(userData, (uint256[], uint256));

        // Upscale both requested amounts and reserves to 18 decimals
        _upscaleArray(reserves);
        _upscaleArray(reqAmountsIn);

        if (totalSupply() == 0) {
            uint256 initScale = AdapterLike(adapter).scale();

            // Convert target balance into Underlying
            // note We assume scale values will always be 18 decimals
            uint256 underlyingIn = reqAmountsIn[1 - pti].mulDown(initScale);

            // Just like weighted pool 2 token from the balancer v2 monorepo,
            // we lock MINIMUM_BPT in by minting it for the PT address. This reduces potential
            // issues with rounding and ensures that this code path will only be executed once
            _mintPoolTokens(address(0), MINIMUM_BPT);

            uint256 bptToMint = underlyingIn.sub(MINIMUM_BPT);

            // Mint the recipient BPT comensurate with the value of their join in Underlying
            _mintPoolTokens(recipient, bptToMint);

            _require(bptToMint >= minBptOut, Errors.BPT_OUT_MIN_AMOUNT);

            // Amounts entering the Pool, so we round up
            _downscaleUpArray(reqAmountsIn);

            // Set the scale value all future deposits will be backdated to
            _initScale = initScale;

            // For the first join, we don't pull any PT, regardless of what the caller requested.
            // This starts this pool off as synthetic Underlying only, as the yieldspace invariant expects
            delete reqAmountsIn[pti];

            // Cache starting Target reserves
            reserves = reqAmountsIn;
        
            // Cache new reserves, post join
            _cacheReserves(reserves);

            return (reqAmountsIn, new uint256[](2));
        } else {
            // Update oracle with upscaled reserves
            _updateOracle(lastChangeBlock, reserves[pti], reserves[1 - pti]);

            // Calculate fees due before updating bpt balances to determine invariant growth from just swap fees
            if (protocolSwapFeePercentage != 0) {
                // This doesn't break the YS virtual reserves efficiency trick because, even though we're minting new BPT, 
                // the BPT is still getting denser faster than it's getting diluted, 
                // meaning that it'll never fall below invariant #23 in the YS paper
                _mintPoolTokens(_protocolFeesCollector, _bptFeeDue(reserves, protocolSwapFeePercentage));
            }

            (uint256 bptToMint, uint256[] memory amountsIn) = _tokensInForBptOut(reqAmountsIn, reserves);

            _require(bptToMint >= minBptOut, Errors.BPT_OUT_MIN_AMOUNT);

            // `recipient` receives liquidity tokens
            _mintPoolTokens(recipient, bptToMint);

            // Update reserves for caching
            //
            // No risk of overflow as this function will only succeed if the user actually has `amountsIn` and
            // the max token supply for a well-behaved token is bounded by `uint256 totalSupply`
            reserves[0] += amountsIn[0];
            reserves[1] += amountsIn[1];

            // Cache new reserves, post join
            _cacheReserves(reserves);

            // Amounts entering the Pool, so we round up
            _downscaleUpArray(amountsIn);

            // Inspired by PR #990 in the balancer v2 monorepo, we always return pt dueProtocolFeeAmounts
            // to the Vault, and pay protocol fees by minting BPT directly to the protocolFeeCollector instead
            return (amountsIn, new uint256[](2));
        }
    }

    function onExitPool(
        bytes32 poolId,
        address sender,
        address, /* recipient */
        uint256[] memory reserves,
        uint256 lastChangeBlock,
        uint256 protocolSwapFeePercentage,
        bytes memory userData
    ) external override onlyVault(poolId) returns (uint256[] memory, uint256[] memory) {
        // Space does not have multiple exit types like other Balancer pools,
        // instead, its `exitPool` always behaves like `EXACT_BPT_IN_FOR_TOKENS_OUT`

        // Upscale reserves to 18 decimals
        _upscaleArray(reserves);

        // Update oracle with upscaled reserves
        _updateOracle(lastChangeBlock, reserves[pti], reserves[1 - pti]);

        // Calculate fees due before updating bpt balances to determine invariant growth from just swap fees
        if (protocolSwapFeePercentage != 0) {
            _mintPoolTokens(_protocolFeesCollector, _bptFeeDue(reserves, protocolSwapFeePercentage));
        }

        // Determine what percentage of the pool the BPT being passed in represents
        uint256 bptAmountIn = abi.decode(userData, (uint256));

        // Calculate the amount of tokens owed in return for giving that amount of BPT in
        uint256[] memory amountsOut = new uint256[](2);
        uint256 _totalSupply = totalSupply();
        // Even though we are sending tokens to the user, we round both amounts out *up* here, b/c:
        //     1) Maximizing the number of tokens users get when exiting maximizes the
        //        number of BPT we mint for users joining afterwards (it maximizes the equation 
        //        totalSupply * amtIn / reserves). As a result, we ensure that the total supply component of the
        //        numerator is greater than the denominator in the "marginal rate equation" (eq. 2) from the YS paper
        //     2) We lock MINIMUM_BPT away at initialization, which means a number of reserves will
        //        remain untouched and will function as a buffer for "off by one" rounding errors
        amountsOut[0] = reserves[0].mulUp(bptAmountIn).divUp(_totalSupply);
        amountsOut[1] = reserves[1].mulUp(bptAmountIn).divUp(_totalSupply);

        // `sender` pays for the liquidity
        _burnPoolTokens(sender, bptAmountIn);

        // Update reserves for caching
        reserves[0] = reserves[0].sub(amountsOut[0]);
        reserves[1] = reserves[1].sub(amountsOut[1]);

        // Cache new invariant and reserves, post exit
        _cacheReserves(reserves);

        // Amounts are leaving the Pool, so we round down
        _downscaleDownArray(amountsOut);

        return (amountsOut, new uint256[](2));
    }

    function onSwap(
        SwapRequest memory request,
        uint256 reservesTokenIn,
        uint256 reservesTokenOut
    ) external override returns (uint256) {
        bool pTIn = request.tokenIn == _token0 ? pti == 0 : pti == 1;

        uint256 scalingFactorTokenIn = _scalingFactor(pTIn);
        uint256 scalingFactorTokenOut = _scalingFactor(!pTIn);

        // Upscale reserves to 18 decimals
        reservesTokenIn = _upscale(reservesTokenIn, scalingFactorTokenIn);
        reservesTokenOut = _upscale(reservesTokenOut, scalingFactorTokenOut);

        // Update oracle with upscaled reserves
        _updateOracle(
            request.lastChangeBlock, 
            pTIn ? reservesTokenIn : reservesTokenOut,
            pTIn ? reservesTokenOut: reservesTokenIn
        );

        uint256 scale = AdapterLike(adapter).scale();

        if (pTIn) {
            // Add LP supply to PT reserves, as suggested by the yieldspace paper
            reservesTokenIn = reservesTokenIn.add(totalSupply());

            // Backdate the Target reserves and convert to Underlying, as if it were still t0 (initialization)
            reservesTokenOut = reservesTokenOut.mulDown(_initScale);
        } else {
            // Backdate the Target reserves and convert to Underlying, as if it were still t0 (initialization)
            reservesTokenIn = reservesTokenIn.mulDown(_initScale);

            // Add LP supply to PT reserves, as suggested by the yieldspace paper
            reservesTokenOut = reservesTokenOut.add(totalSupply());
        }

        if (request.kind == IVault.SwapKind.GIVEN_IN) {
            request.amount = _upscale(request.amount, scalingFactorTokenIn);
            // If Target is being swapped in, convert the amountIn to Underlying using present day Scale
            if (!pTIn) {
                request.amount = request.amount.mulDown(scale);
            }

            // Determine the amountOut
            uint256 amountOut = _onSwap(pTIn, true, request.amount, reservesTokenIn, reservesTokenOut);

            // If PTs are being swapped in, convert the Underlying out back to Target using present day Scale
            if (pTIn) {
                amountOut = amountOut.divDown(scale);
            }

            // AmountOut, so we round down
            return _downscaleDown(amountOut, scalingFactorTokenOut);
        } else {
            request.amount = _upscale(request.amount, scalingFactorTokenOut);
            // If PTs are being swapped in, convert the amountOut from Target to Underlying using present day Scale
            if (pTIn) {
                request.amount = request.amount.mulDown(scale);
            }

            // Determine the amountIn
            uint256 amountIn = _onSwap(pTIn, false, request.amount, reservesTokenIn, reservesTokenOut);

            // If Target is being swapped in, convert the amountIn back to Target using present day Scale
            if (!pTIn) {
                amountIn = amountIn.divDown(scale);
            }

            // amountIn, so we round up
            return _downscaleUp(amountIn, scalingFactorTokenIn);
        }
    }

    /* ========== INTERNAL JOIN/SWAP ACCOUNTING ========== */

    /// @notice Calculate the max amount of BPT that can be minted from the requested amounts in,
    // given the ratio of the reserves, and assuming we don't make any swaps
    function _tokensInForBptOut(uint256[] memory reqAmountsIn, uint256[] memory reserves)
        internal
        view
        returns (uint256, uint256[] memory)
    {
        // Disambiguate reserves wrt token type
        (uint256 pTReserves, uint256 targetReserves) = (reserves[pti], reserves[1 - pti]);

        uint256[] memory amountsIn = new uint256[](2);

        // An empty PT reserve occurs after 
        //     1) Pool initialization
        //     2) When the entire PT side is swapped out of the pool without implying a negative rate
        if (pTReserves == 0) {
            uint256 reqTargetIn = reqAmountsIn[1 - pti];
            // Mint LP shares according to the relative amount of Target being offered
            uint256 bptToMint = reqTargetIn.mulDown(_initScale);

            // Pull the entire offered Target
            amountsIn[1 - pti] = reqTargetIn;

            return (bptToMint, amountsIn);
        } else {
            // Disambiguate requested amounts wrt token type
            (uint256 reqPTIn, uint256 reqTargetIn) = (reqAmountsIn[pti], reqAmountsIn[1 - pti]);
            uint256 _totalSupply = totalSupply();
            // Caclulate the percentage of the pool we'd get if we pulled all of the requested Target in
            uint256 bptToMintTarget = BasicMath.mul(_totalSupply, reqTargetIn) / targetReserves;

            // Caclulate the percentage of the pool we'd get if we pulled all of the requested PT in
            uint256 bptToMintPT = BasicMath.mul(_totalSupply, reqPTIn) / pTReserves;

            // Determine which amountIn is our limiting factor
            if (bptToMintTarget < bptToMintPT) {
                amountsIn[pti] = BasicMath.mul(pTReserves, reqTargetIn) / targetReserves;
                amountsIn[1 - pti] = reqTargetIn;

                return (bptToMintTarget, amountsIn);
            } else {
                amountsIn[pti] = reqPTIn;
                amountsIn[1 - pti] = BasicMath.mul(targetReserves, reqPTIn) / pTReserves;

                return (bptToMintPT, amountsIn);
            }
        }
    }

    /// @notice Calculate the missing variable in the yield space equation given the direction (PT in vs. out)
    /// @dev We round in favor of the LPs, meaning that traders get slightly worse prices than they would if we had full
    /// precision. However, the differences are small (on the order of 1e-11), and should only matter for very small trades.
    function _onSwap(
        bool pTIn,
        bool givenIn,
        uint256 amountDelta,
        uint256 reservesTokenIn,
        uint256 reservesTokenOut
    ) internal view returns (uint256) {
        // xPre = token in reserves pre swap
        // yPre = token out reserves pre swap

        // Seconds until maturity, in 18 decimals
        // After maturity, this pool becomes a constant sum AMM
        uint256 ttm = maturity > block.timestamp ? uint256(maturity - block.timestamp) * FixedPoint.ONE : 0;

        // Time shifted partial `t` from the yieldspace paper (`ttm` adjusted by some factor `ts`)
        uint256 t = ts.mulDown(ttm);

        // Full `t` with fees baked in
        uint256 a = (pTIn ? g2 : g1).mulUp(t).complement();

        // Pow up for `x1` & `y1` and down for `xOrY2` causes the pow induced error for `xOrYPost`
        // to tend towards higher values rather than lower.
        // Effectively we're adding a little bump up for ammountIn, and down for amountOut

        // x1 = xPre ^ a; y1 = yPre ^ a
        uint256 x1 = reservesTokenIn.powUp(a);
        uint256 y1 = reservesTokenOut.powUp(a);

        // y2 = (yPre - amountOut) ^ a; x2 = (xPre + amountIn) ^ a
        //
        // No overflow risk in the addition as Balancer will only allow an `amountDelta` for tokens coming in
        // if the user actually has it, and the max token supply for well-behaved tokens is bounded by the uint256 type
        uint256 newReservesTokenInOrOut = givenIn ? reservesTokenIn + amountDelta : reservesTokenOut.sub(amountDelta);
        uint256 xOrY2 = newReservesTokenInOrOut.powDown(a);

        // x1 + y1 = xOrY2 + xOrYPost ^ a
        // -> xOrYPost ^ a = x1 + y1 - x2
        // -> xOrYPost = (x1 + y1 - xOrY2) ^ (1 / a)
        uint256 xOrYPost = (x1.add(y1).sub(xOrY2)).powUp(FixedPoint.ONE.divDown(a));
        _require(!givenIn || reservesTokenOut > xOrYPost, Errors.SWAP_TOO_SMALL);

        if (givenIn) {
            // Check that PT reserves are greater than "Underlying" reserves per section 6.3 of the YS paper
            _require(
                pTIn ?
                newReservesTokenInOrOut >= xOrYPost :
                newReservesTokenInOrOut <= xOrYPost,
                Errors.NEGATIVE_RATE
            );

            // amountOut = yPre - yPost
            return reservesTokenOut.sub(xOrYPost);
        } else {
            _require(
                pTIn ?
                xOrYPost >= newReservesTokenInOrOut :
                xOrYPost <= newReservesTokenInOrOut,
                Errors.NEGATIVE_RATE
            );

            // amountIn = xPost - xPre
            return xOrYPost.sub(reservesTokenIn);
        }
    }

    /* ========== PROTOCOL FEE HELPERS ========== */

    /// @notice Determine the growth in the invariant due to swap fees only
    /// @dev This can't be a view function b/c `Adapter.scale` is not a view function
    function _bptFeeDue(uint256[] memory reserves, uint256 protocolSwapFeePercentage) internal view returns (uint256) {
        uint256 ttm = maturity > block.timestamp ? uint256(maturity - block.timestamp) * FixedPoint.ONE : 0;
        uint256 a = ts.mulDown(ttm).complement();

        // Invariant growth from time only
        uint256 timeOnlyInvariant = _lastToken0Reserve.powDown(a).add(_lastToken1Reserve.powDown(a));

        // `x` & `y` for the actual invariant, with growth from time and fees
        uint256 x = reserves[pti].add(totalSupply()).powDown(a);
        uint256 y = reserves[1 - pti].mulDown(_initScale).powDown(a);
        uint256 fullInvariant = x.add(y);

        if (fullInvariant <= timeOnlyInvariant) {
            // Similar to the invariant check in balancer-v2-monorepo/**/WeightedMath.sol,
            // this shouldn't happen outside of rounding errors, yet we keep this so that those
            // potential errors don't lead to a locked state
            return 0;
        }

        // The formula to calculate fees due is:
        //
        // where:
        //   `g` is the factor by which reserves have grown
        //   `time-only invariant` = x^a + y^a
        //   `realized invariant`  = (g*x)^a + (g*y)^a
        //
        //              /   realized invariant     \ ^ (1/a)
        // `growth` =  |   ----------------------  |
        //              \   time-only invariant    /
        //
        //
        // This gets us the proportional growth of all token balances, or `growth`
        //
        // We can plug this into the following equation from `WeightedMath` in PR#1111 on the Balancer monorepo:
        //
        //             supply * protocol fee * (growth - 1)
        //                 ---------------------------
        //                          growth
        // toMint = --------------------------------------
        //              1 - protocol fee * (growth - 1)
        //                ---------------------------
        //                          growth

        uint256 growth = fullInvariant.divDown(timeOnlyInvariant).powDown(FixedPoint.ONE.divDown(a));
        uint256 k = protocolSwapFeePercentage.mulDown(growth.sub(FixedPoint.ONE)).divDown(growth);

        return totalSupply().mulDown(k).divDown(k.complement());
    }

    /// @notice Cache the given reserve amounts
    /// @dev if the oracle is set, this function will also cache the invariant and supply
    function _cacheReserves(uint256[] memory reserves) internal {
        uint256 reservePT = reserves[pti].add(totalSupply());
        // Calculate the backdated Target reserve
        uint256 reserveUnderlying = reserves[1 - pti].mulDown(_initScale);

        // Caclulate the invariant and store everything
        uint256 lastToken0Reserve;
        uint256 lastToken1Reserve;
        if (pti == 0) {
            lastToken0Reserve = reservePT;
            lastToken1Reserve = reserveUnderlying;
        } else {
            lastToken0Reserve = reserveUnderlying;
            lastToken1Reserve = reservePT;
        }

        if (oracleData.oracleEnabled) {
            // If the oracle is enabled, cache the current invarant as well so that callers can determine liquidity
            uint256 ttm = maturity > block.timestamp ? uint256(maturity - block.timestamp) * FixedPoint.ONE : 0;
            uint256 a = ts.mulDown(ttm).complement();

            oracleData.logInvariant = int200(
                LogCompression.toLowResLog(
                    lastToken0Reserve.powDown(a).add(lastToken1Reserve.powDown(a))
                )
            );
        }

        _lastToken0Reserve = lastToken0Reserve;
        _lastToken1Reserve = lastToken1Reserve;
    }

    /* ========== ORACLE HELPERS ========== */

    /// @notice Update the oracle with the current index and timestamp
    /// @dev Must receive reserves that have already been upscaled
    /// @dev Acts as a no-op if:
    ///     * the oracle is not enabled 
    ///     * a price has already been stored for this block
    ///     * the Target side of the pool doesn't have enough liquidity
    function _updateOracle(
        uint256 lastChangeBlock,
        uint256 balancePT,
        uint256 balanceTarget
    ) internal {
        // The Target side of the pool must have at least 0.01 units of liquidity for us to collect a price sample
        // note additional liquidity contraints may be enforced outside of this contract via the invariant TWAP
        if (oracleData.oracleEnabled && block.number > lastChangeBlock && balanceTarget >= 1e16) {
            // Use equation (2) from the YieldSpace paper to calculate the the marginal rate from the reserves
            uint256 impliedRate = balancePT.add(totalSupply())
                .divDown(balanceTarget.mulDown(_initScale));

            // Guard against rounding from exits leading the implied rate to be very slightly negative
            // NOTE: in a future version of this system, a postive rate invariant for joins/exits will be preserved,
            // as is currently done for swaps
            impliedRate = impliedRate < FixedPoint.ONE ? 0 : impliedRate.sub(FixedPoint.ONE);

            // Cacluate the price of one PT in Target terms
            uint256 pTPriceInTarget = getPriceFromImpliedRate(impliedRate);

            // Following Balancer's oracle conventions, get price of token 1 in terms of token 0 and
            // and the price of one BPT in terms of token 0
            //
            // note b/c reserves are upscaled coming into this function,
            // price is already upscaled to 18 decimals, regardless of the decimals used for token 0 & 1
            uint256 pairPrice = pti == 0 ? FixedPoint.ONE.divDown(pTPriceInTarget) : pTPriceInTarget;

            uint256 oracleUpdatedIndex = _processPriceData(
                oracleData.oracleSampleInitialTimestamp,
                oracleData.oracleIndex,
                LogCompression.toLowResLog(pairPrice),
                // We diverge from Balancer's defaults here by storing implied rate
                // rather than BPT price in this second slot
                //
                // Also note implied rates of less than 1e6 are taken as 1e6, b/c:
                //     1) `toLowResLog` fails for 0 and 1e6 is precise enough for our needs
                //     2) 1e6 is the lowest value Balancer passes into this util (min for totalSupply())
                impliedRate < 1e6 ? LogCompression.toLowResLog(1e6) : LogCompression.toLowResLog(impliedRate),
                int256(oracleData.logInvariant)
            );

            if (oracleData.oracleIndex != oracleUpdatedIndex) {
                oracleData.oracleSampleInitialTimestamp = uint32(block.timestamp);
                oracleData.oracleIndex = uint16(oracleUpdatedIndex);
            }
        }
    }

    function _getOracleIndex() internal view override returns (uint256) {
        return oracleData.oracleIndex;
    }

    /* ========== PUBLIC GETTERS ========== */

    /// @notice Get the APY implied rate for PTs given a price in Target
    /// @param pTPriceInTarget price of PTs in terms of Target
    function getImpliedRateFromPrice(uint256 pTPriceInTarget) public view returns (uint256 impliedRate) {
        if (block.timestamp >= maturity) {
            return 0;
        }

        // Calculate the *normed* implied rate from the PT price 
        // (i.e. the effective implied rate of PTs over the period normed by the timeshift param)
        // (e.g. PTs = 0.9 [U], time to maturity of 0.5 yrs, timeshift param of 10 yrs, the
        //  normed implied rate = ( 1 / 0.9 ) ^ ( 1 / (0.5 * [1 / 10]) ) - 1 = 722.5% )
        impliedRate = FixedPoint.ONE
            .divDown(pTPriceInTarget.mulDown(AdapterLike(adapter).scaleStored()))
            .powDown(FixedPoint.ONE.divDown(ts).divDown((maturity - block.timestamp) * FixedPoint.ONE))
            .sub(FixedPoint.ONE);
    }

    /// @notice Get price of PTs in Target terms given a price for PTs in Target
    /// @param impliedRate Normed implied rate
    function getPriceFromImpliedRate(uint256 impliedRate) public view returns (uint256 pTPriceInTarget) {
        if (block.timestamp >= maturity) {
            return FixedPoint.ONE;
        }

        // Calculate the PT price in Target from an implied rate adjusted by the timeshift param,
        // where the timeshift is a normalization factor applied to the time to maturity
        pTPriceInTarget = FixedPoint.ONE
            .divDown(impliedRate.add(FixedPoint.ONE)
            .powDown(((maturity - block.timestamp) * FixedPoint.ONE)
            .divDown(FixedPoint.ONE.divDown(ts))))
            .divDown(AdapterLike(adapter).scaleStored());
    }

    /// @notice Get the "fair" price for the BPT tokens given a correct price for PTs
    /// in terms of Target. i.e. the price of one BPT in terms of Target using reserves
    /// as they would be if they accurately reflected the true PT price
    /// @dev for a technical explanation of the concept, see the description in the following repo:
    /// https://github.com/makerdao/univ2-lp-oracle/blob/874a59d74d847909cc4a31f0d38ee6b020f6525f/src/UNIV2LPOracle.sol#L26
    function getFairBPTPrice(uint256 ptTwapDuration)
        public
        view
        returns (uint256 fairBptPriceInTarget)
    {
        OracleAverageQuery[] memory queries = new OracleAverageQuery[](1);
        queries[0] = OracleAverageQuery({
            variable: Variable.PAIR_PRICE,
            secs: ptTwapDuration,
            ago: 1 hours // take the oracle from 1 hour ago + ptTwapDuration ago to 1 hour ago
        });

        // TWAP read will revert with ORACLE_NOT_INITIALIZED if the buffer has not been filled
        uint256[] memory results = this.getTimeWeightedAverage(queries);
        uint256 pTPriceInTarget = pti == 1 ? results[0] : FixedPoint.ONE.divDown(results[0]);

        uint256 impliedRate = getImpliedRateFromPrice(pTPriceInTarget);
        (, uint256[] memory balances, ) = _vault.getPoolTokens(_poolId);

        uint256 ttm = maturity > block.timestamp
            ? uint256(maturity - block.timestamp) * FixedPoint.ONE
            : 0;
        uint256 a = ts.mulDown(ttm).complement();

        uint256 k = balances[pti].add(totalSupply()).powDown(a).add(
            balances[1 - pti].mulDown(_initScale).powDown(a)
        );

        // Equilibrium reserves for the PT side, w/o the final `- totalSupply` at the end
        uint256 equilibriumPTReservesPartial = k.divDown(
            FixedPoint.ONE.divDown(FixedPoint.ONE.add(impliedRate).powDown(a)).add(FixedPoint.ONE)
        ).powDown(FixedPoint.ONE.divDown(a));

        uint256 equilibriumTargetReserves = equilibriumPTReservesPartial
            .divDown(_initScale.mulDown(FixedPoint.ONE.add(impliedRate)));

        fairBptPriceInTarget = equilibriumTargetReserves
            // Complete the equilibrium PT reserve calc
            .add(equilibriumPTReservesPartial.sub(totalSupply())
            .mulDown(pTPriceInTarget)).divDown(totalSupply());
    }

    /// @notice Get token indices for PT and Target
    function getIndices() public view returns (uint256 _pti, uint256 _targeti) {
        _pti = pti;
        _targeti = 1 - pti;
    }

    /* ========== BALANCER REQUIRED INTERFACE ========== */

    function getPoolId() public view override returns (bytes32) {
        return _poolId;
    }

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

    /* ========== BALANCER SCALING FUNCTIONS ========== */

    /// @notice Scaling factors for PT & Target tokens
    function _scalingFactor(bool pt) internal view returns (uint256) {
        return pt ? _scalingFactorPT : _scalingFactorTarget;
    }

    /// @notice Scale number type to 18 decimals if need be
    function _upscale(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
        return BasicMath.mul(amount, scalingFactor);
    }

    /// @notice Ensure number type is back in its base decimal if need be, rounding down
    function _downscaleDown(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
        return amount / scalingFactor;
    }

    /// @notice Ensure number type is back in its base decimal if need be, rounding up
    function _downscaleUp(uint256 amount, uint256 scalingFactor) internal pure returns (uint256) {
        return BasicMath.divUp(amount, scalingFactor);
    }

    /// @notice Upscale array of token amounts to 18 decimals if need be
    function _upscaleArray(uint256[] memory amounts) internal view {
        amounts[pti] = BasicMath.mul(amounts[pti], _scalingFactor(true));
        amounts[1 - pti] = BasicMath.mul(amounts[1 - pti], _scalingFactor(false));
    }

    /// @notice Downscale array of token amounts to 18 decimals if need be, rounding down
    function _downscaleDownArray(uint256[] memory amounts) internal view {
        amounts[pti] = amounts[pti] / _scalingFactor(true);
        amounts[1 - pti] = amounts[1 - pti] / _scalingFactor(false);
    }
    /// @notice Downscale array of token amounts to 18 decimals if need be, rounding up
    function _downscaleUpArray(uint256[] memory amounts) internal view {
        amounts[pti] = BasicMath.divUp(amounts[pti], _scalingFactor(true));
        amounts[1 - pti] = BasicMath.divUp(amounts[1 - pti], _scalingFactor(false));
    }

    /* ========== MODIFIERS ========== */

    /// Taken from balancer-v2-monorepo/**/WeightedPool2Tokens.sol
    modifier onlyVault(bytes32 poolId_) {
        _require(msg.sender == address(getVault()), Errors.CALLER_NOT_VAULT);
        _require(poolId_ == getPoolId(), Errors.INVALID_POOL_ID);
        _;
    }
}

File 2 of 32 : FixedPoint.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 "./LogExpMath.sol";
import "../helpers/BalancerErrors.sol";

/* solhint-disable private-vars-leading-underscore */

library FixedPoint {
    uint256 internal constant ONE = 1e18; // 18 decimal places
    uint256 internal constant MAX_POW_RELATIVE_ERROR = 10000; // 10^(-14)

    // Minimum base for the power function when the exponent is 'free' (larger than ONE).
    uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;

    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        // Fixed Point addition is the same as regular checked addition

        uint256 c = a + b;
        _require(c >= a, Errors.ADD_OVERFLOW);
        return c;
    }

    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        // Fixed Point addition is the same as regular checked addition

        _require(b <= a, Errors.SUB_OVERFLOW);
        uint256 c = a - b;
        return c;
    }

    function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 product = a * b;
        _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);

        return product / ONE;
    }

    function mulUp(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 product = a * b;
        _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);

        if (product == 0) {
            return 0;
        } else {
            // The traditional divUp formula is:
            // divUp(x, y) := (x + y - 1) / y
            // To avoid intermediate overflow in the addition, we distribute the division and get:
            // divUp(x, y) := (x - 1) / y + 1
            // Note that this requires x != 0, which we already tested for.

            return ((product - 1) / ONE) + 1;
        }
    }

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

        if (a == 0) {
            return 0;
        } else {
            uint256 aInflated = a * ONE;
            _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow

            return aInflated / b;
        }
    }

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

        if (a == 0) {
            return 0;
        } else {
            uint256 aInflated = a * ONE;
            _require(aInflated / a == ONE, Errors.DIV_INTERNAL); // mul overflow

            // The traditional divUp formula is:
            // divUp(x, y) := (x + y - 1) / y
            // To avoid intermediate overflow in the addition, we distribute the division and get:
            // divUp(x, y) := (x - 1) / y + 1
            // Note that this requires x != 0, which we already tested for.

            return ((aInflated - 1) / b) + 1;
        }
    }

    /**
     * @dev Returns x^y, assuming both are fixed point numbers, rounding down. The result is guaranteed to not be above
     * the true value (that is, the error function expected - actual is always positive).
     */
    function powDown(uint256 x, uint256 y) internal pure returns (uint256) {
        uint256 raw = LogExpMath.pow(x, y);
        uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);

        if (raw < maxError) {
            return 0;
        } else {
            return sub(raw, maxError);
        }
    }

    /**
     * @dev Returns x^y, assuming both are fixed point numbers, rounding up. The result is guaranteed to not be below
     * the true value (that is, the error function expected - actual is always negative).
     */
    function powUp(uint256 x, uint256 y) internal pure returns (uint256) {
        uint256 raw = LogExpMath.pow(x, y);
        uint256 maxError = add(mulUp(raw, MAX_POW_RELATIVE_ERROR), 1);

        return add(raw, maxError);
    }

    /**
     * @dev Returns the complement of a value (1 - x), capped to 0 if x is larger than 1.
     *
     * Useful when computing the complement for values with some level of relative error, as it strips this error and
     * prevents intermediate negative values.
     */
    function complement(uint256 x) internal pure returns (uint256) {
        return (x < ONE) ? (ONE - x) : 0;
    }
}

File 3 of 32 : Math.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../helpers/BalancerErrors.sol";

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
 * Adapted from OpenZeppelin's SafeMath library
 */
library Math {
    /**
     * @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) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers of 256 bits.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? 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) {
        _require(b != 0, Errors.ZERO_DIVISION);

        if (a == 0) {
            return 0;
        } else {
            return 1 + (a - 1) / b;
        }
    }
}

File 4 of 32 : BalancerPoolToken.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 "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ERC20Permit.sol";

/**
 * @title Highly opinionated token implementation
 * @author Balancer Labs
 * @dev
 * - Includes functions to increase and decrease allowance as a workaround
 *   for the well-known issue with `approve`:
 *   https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
 * - Allows for 'infinite allowance', where an allowance of 0xff..ff is not
 *   decreased by calls to transferFrom
 * - Lets a token holder use `transferFrom` to send their own tokens,
 *   without first setting allowance
 * - Emits 'Approval' events whenever allowance is changed by `transferFrom`
 */
contract BalancerPoolToken is ERC20, ERC20Permit {
    constructor(string memory tokenName, string memory tokenSymbol)
        ERC20(tokenName, tokenSymbol)
        ERC20Permit(tokenName)
    {
        // solhint-disable-previous-line no-empty-blocks
    }

    // Overrides

    /**
     * @dev Override to allow for 'infinite allowance' and let the token owner use `transferFrom` with no self-allowance
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public override returns (bool) {
        uint256 currentAllowance = allowance(sender, msg.sender);
        _require(msg.sender == sender || currentAllowance >= amount, Errors.ERC20_TRANSFER_EXCEEDS_ALLOWANCE);

        _transfer(sender, recipient, amount);

        if (msg.sender != sender && currentAllowance != uint256(-1)) {
            // Because of the previous require, we know that if msg.sender != sender then currentAllowance >= amount
            _approve(sender, msg.sender, currentAllowance - amount);
        }

        return true;
    }

    /**
     * @dev Override to allow decreasing allowance by more than the current amount (setting it to zero)
     */
    function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
        uint256 currentAllowance = allowance(msg.sender, spender);

        if (amount >= currentAllowance) {
            _approve(msg.sender, spender, 0);
        } else {
            // No risk of underflow due to if condition
            _approve(msg.sender, spender, currentAllowance - amount);
        }

        return true;
    }

    // Internal functions

    function _mintPoolTokens(address recipient, uint256 amount) internal {
        _mint(recipient, amount);
    }

    function _burnPoolTokens(address sender, uint256 amount) internal {
        _burn(sender, amount);
    }
}

File 5 of 32 : ERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../helpers/BalancerErrors.sol";

import "./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}.
     */
    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

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

        _totalSupply = _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_ALLOWANCE);
        _totalSupply = _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 {}
}

File 6 of 32 : LogCompression.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 "../math/LogExpMath.sol";

/**
 * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in
 * a single storage slot, saving gas by performing less storage accesses.
 *
 * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two
 * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128.
 */
library LogCompression {
    int256 private constant _LOG_COMPRESSION_FACTOR = 1e14;
    int256 private constant _HALF_LOG_COMPRESSION_FACTOR = 0.5e14;

    /**
     * @dev Returns the natural logarithm of `value`, dropping most of the decimal places to arrive at a value that,
     * when passed to `fromLowResLog`, will have a maximum relative error of ~0.05% compared to `value`.
     *
     * Values returned from this function should not be mixed with other fixed-point values (as they have a different
     * number of digits), but can be added or subtracted. Use `fromLowResLog` to undo this process and return to an
     * 18 decimal places fixed point value.
     *
     * Because so much precision is lost, the logarithmic values can be stored using much fewer bits than the original
     * value required.
     */
    function toLowResLog(uint256 value) internal pure returns (int256) {
        int256 ln = LogExpMath.ln(int256(value));

        // Rounding division for signed numerator
        int256 lnWithError = (ln > 0 ? ln + _HALF_LOG_COMPRESSION_FACTOR : ln - _HALF_LOG_COMPRESSION_FACTOR);
        return lnWithError / _LOG_COMPRESSION_FACTOR;
    }

    /**
     * @dev Restores `value` from logarithmic space. `value` is expected to be the result of a call to `toLowResLog`,
     * any other function that returns 4 decimals fixed point logarithms, or the sum of such values.
     */
    function fromLowResLog(int256 value) internal pure returns (uint256) {
        return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR));
    }
}

File 7 of 32 : IMinimalSwapInfoPool.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 "./IBasePool.sol";

/**
 * @dev Pool contracts with the MinimalSwapInfo or TwoToken specialization settings should implement this interface.
 *
 * This is called by the Vault when a user calls `IVault.swap` or `IVault.batchSwap` to swap with this Pool.
 * Returns the number of tokens the Pool will grant to the user in a 'given in' swap, or that the user will grant
 * to the pool in a 'given out' swap.
 *
 * This can often be implemented by a `view` function, since many pricing algorithms don't need to track state
 * changes in swaps. However, contracts implementing this in non-view functions should check that the caller is
 * indeed the Vault.
 */
interface IMinimalSwapInfoPool is IBasePool {
    function onSwap(
        SwapRequest memory swapRequest,
        uint256 currentBalanceTokenIn,
        uint256 currentBalanceTokenOut
    ) external returns (uint256 amount);
}

File 8 of 32 : 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 "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol";
import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol";
import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol";

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

pragma solidity ^0.7.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 {
    // 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 9 of 32 : IERC20.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

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

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

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

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

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

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

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

File 10 of 32 : Errors.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.0;

// solhint-disable

/**
 * @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) pure {
    if (!condition) _revert(errorCode);
}

/**
 * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
 */
function _revert(uint256 errorCode) pure {
    // We're going to dynamically create a revert string based on the error code, with the following format:
    // 'SNS#{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. The "SNS#" part is a known constant
        // (0x3f534e5323): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
        // characters to it, each shifted by a multiple of 8.
        // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
        // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
        // array).

        let revertReason := shl(200, add(0x3f534e5323000000, 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 {
    // Space (using error codes as Space uses ^0.7.0)
    uint256 internal constant CALLER_NOT_VAULT = 100;
    uint256 internal constant INVALID_G1 = 101;
    uint256 internal constant INVALID_G2 = 102;
    uint256 internal constant INVALID_POOL_ID = 103;
    uint256 internal constant POOL_ALREADY_DEPLOYED = 104;
    uint256 internal constant POOL_PAST_MATURITY = 105;
    uint256 internal constant SWAP_TOO_SMALL = 106;
    uint256 internal constant NEGATIVE_RATE = 107;
    uint256 internal constant BPT_OUT_MIN_AMOUNT = 108;
}

File 11 of 32 : PoolPriceOracle.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/>.

// Forked from balancer-v2-monorepo/pkg/pool-utils/contracts/oracle/**
// at commit ef246cf213541c4120a78f811560f100e5a7e15a

pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

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

import "./interfaces/IPriceOracle.sol";
import "./interfaces/IPoolPriceOracle.sol";

import "./Buffer.sol";
import "./Samples.sol";
import "./QueryProcessor.sol";

/**
 * @dev This module allows Pools to access historical pricing information.
 *
 * It uses a 20 long circular buffer to store past data, where the data within each sample is the result of
 * accumulating live data for no more than two minutes. Therefore, assuming the worst case scenario where new data is
 * updated in every single block, the oldest samples in the buffer (and therefore largest queryable period) will
 * be slightly over 6.5 hours old.
 *
 * Usage of this module requires the caller to keep track of two variables: the latest circular buffer index, and the
 * timestamp when the index last changed. Aditionally, access to the latest circular buffer index must be exposed by
 * implementing `_getOracleIndex`.
 *
 * This contract relies on the `QueryProcessor` linked library to reduce bytecode size.
 */
abstract contract PoolPriceOracle is IPoolPriceOracle, IPriceOracle {
    using Buffer for uint256;
    using Samples for bytes32;

    // Each sample in the buffer accumulates information for up to 20 minutes. This is simply to reduce the size of the
    // buffer: small time deviations will not have any significant effect.
    // solhint-disable not-rely-on-time
    uint256 private constant _MAX_SAMPLE_DURATION = 20 minutes;

    // We use a mapping to simulate an array: the buffer won't grow or shrink, and since we will always use valid
    // indexes using a mapping saves gas by skipping the bounds checks.
    mapping(uint256 => bytes32) internal _samples;

    // IPoolPriceOracle

    function getSample(uint256 index)
        external
        view
        override
        returns (
            int256 logPairPrice,
            int256 accLogPairPrice,
            int256 logBptPrice,
            int256 accLogBptPrice,
            int256 logInvariant,
            int256 accLogInvariant,
            uint256 timestamp
        )
    {
        _require(index < Buffer.SIZE, Errors.ORACLE_INVALID_INDEX);

        bytes32 sample = _getSample(index);
        return sample.unpack();
    }

    function getTotalSamples() external pure override returns (uint256) {
        return Buffer.SIZE;
    }

    /**
     * @dev Manually dirty oracle sample storage slots with dummy data, to reduce the gas cost of the future swaps
     * that will initialize them. This function is only useful before the oracle has been fully initialized.
     *
     * `endIndex` is non-inclusive.
     */
    function dirtyUninitializedOracleSamples(uint256 startIndex, uint256 endIndex) external {
        _require(startIndex < endIndex && endIndex <= Buffer.SIZE, Errors.OUT_OF_BOUNDS);

        // Uninitialized samples are identified by a zero timestamp -- all other fields are ignored,
        // so any non-zero value with a zero timestamp suffices.
        bytes32 initSample = Samples.pack(1, 0, 0, 0, 0, 0, 0);
        for (uint256 i = startIndex; i < endIndex; i++) {
            if (_samples[i].timestamp() == 0) {
                _samples[i] = initSample;
            }
        }
    }

    // IPriceOracle

    function getLargestSafeQueryWindow() external pure override returns (uint256) {
        return 6.66 hours;
    }

    function getLatest(Variable variable) external view override returns (uint256) {
        return QueryProcessor.getInstantValue(_samples, variable, _getOracleIndex());
    }

    function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
        external
        view
        override
        returns (uint256[] memory results)
    {
        results = new uint256[](queries.length);
        uint256 latestIndex = _getOracleIndex();

        for (uint256 i = 0; i < queries.length; ++i) {
            results[i] = QueryProcessor.getTimeWeightedAverage(_samples, queries[i], latestIndex);
        }
    }

    function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
        external
        view
        override
        returns (int256[] memory results)
    {
        results = new int256[](queries.length);
        uint256 latestIndex = _getOracleIndex();

        OracleAccumulatorQuery memory query;
        for (uint256 i = 0; i < queries.length; ++i) {
            query = queries[i];
            results[i] = _getPastAccumulator(query.variable, latestIndex, query.ago);
        }
    }

    // Internal functions

    /**
     * @dev Processes new price and invariant data, updating the latest sample or creating a new one.
     *
     * Receives the new logarithms of values to store: `logPairPrice`, `logBptPrice` and `logInvariant`, as well the
     * index of the latest sample and the timestamp of its creation.
     *
     * Returns the index of the latest sample. If different from `latestIndex`, the caller should also store the
     * timestamp, and pass it on future calls to this function.
     */
    function _processPriceData(
        uint256 latestSampleCreationTimestamp,
        uint256 latestIndex,
        int256 logPairPrice,
        int256 logBptPrice,
        int256 logInvariant
    ) internal returns (uint256) {
        // Read latest sample, and compute the next one by updating it with the newly received data.
        bytes32 sample = _getSample(latestIndex).update(logPairPrice, logBptPrice, logInvariant, block.timestamp);

        // We create a new sample if more than _MAX_SAMPLE_DURATION seconds have elapsed since the creation of the
        // latest one. In other words, no sample accumulates data over a period larger than _MAX_SAMPLE_DURATION.
        bool newSample = block.timestamp - latestSampleCreationTimestamp >= _MAX_SAMPLE_DURATION;
        latestIndex = newSample ? latestIndex.next() : latestIndex;

        // Store the updated or new sample.
        _samples[latestIndex] = sample;

        return latestIndex;
    }

    function _getPastAccumulator(
        IPriceOracle.Variable variable,
        uint256 latestIndex,
        uint256 ago
    ) internal view returns (int256) {
        return QueryProcessor.getPastAccumulator(_samples, variable, latestIndex, ago);
    }

    function _findNearestSample(
        uint256 lookUpDate,
        uint256 offset,
        uint256 length
    ) internal view returns (bytes32 prev, bytes32 next) {
        return QueryProcessor.findNearestSample(_samples, lookUpDate, offset, length);
    }

    /**
     * @dev Returns the sample that corresponds to a given `index`.
     *
     * Using this function instead of accessing storage directly results in denser bytecode (since the storage slot is
     * only computed here).
     */
    function _getSample(uint256 index) internal view returns (bytes32) {
        return _samples[index];
    }

    /**
     * @dev Virtual function to be implemented by derived contracts. Must return the current index of the oracle
     * circular buffer.
     */
    function _getOracleIndex() internal view virtual returns (uint256);
}

File 12 of 32 : LogExpMath.sol
// SPDX-License-Identifier: MIT
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pragma solidity ^0.7.0;

import "../helpers/BalancerErrors.sol";

/* solhint-disable */

/**
 * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
 *
 * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
 * exponentiation and logarithm (where the base is Euler's number).
 *
 * @author Fernando Martinelli - @fernandomartinelli
 * @author Sergio Yuhjtman - @sergioyuhjtman
 * @author Daniel Fernandez - @dmf7z
 */
library LogExpMath {
    // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
    // two numbers, and multiply by ONE when dividing them.

    // All arguments and return values are 18 decimal fixed point numbers.
    int256 constant ONE_18 = 1e18;

    // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
    // case of ln36, 36 decimals.
    int256 constant ONE_20 = 1e20;
    int256 constant ONE_36 = 1e36;

    // The domain of natural exponentiation is bound by the word size and number of decimals used.
    //
    // Because internally the result will be stored using 20 decimals, the largest possible result is
    // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
    // The smallest possible result is 10^(-18), which makes largest negative argument
    // ln(10^(-18)) = -41.446531673892822312.
    // We use 130.0 and -41.0 to have some safety margin.
    int256 constant MAX_NATURAL_EXPONENT = 130e18;
    int256 constant MIN_NATURAL_EXPONENT = -41e18;

    // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
    // 256 bit integer.
    int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
    int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;

    uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);

    // 18 decimal constants
    int256 constant x0 = 128000000000000000000; // 2ˆ7
    int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
    int256 constant x1 = 64000000000000000000; // 2ˆ6
    int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)

    // 20 decimal constants
    int256 constant x2 = 3200000000000000000000; // 2ˆ5
    int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
    int256 constant x3 = 1600000000000000000000; // 2ˆ4
    int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
    int256 constant x4 = 800000000000000000000; // 2ˆ3
    int256 constant a4 = 298095798704172827474000; // eˆ(x4)
    int256 constant x5 = 400000000000000000000; // 2ˆ2
    int256 constant a5 = 5459815003314423907810; // eˆ(x5)
    int256 constant x6 = 200000000000000000000; // 2ˆ1
    int256 constant a6 = 738905609893065022723; // eˆ(x6)
    int256 constant x7 = 100000000000000000000; // 2ˆ0
    int256 constant a7 = 271828182845904523536; // eˆ(x7)
    int256 constant x8 = 50000000000000000000; // 2ˆ-1
    int256 constant a8 = 164872127070012814685; // eˆ(x8)
    int256 constant x9 = 25000000000000000000; // 2ˆ-2
    int256 constant a9 = 128402541668774148407; // eˆ(x9)
    int256 constant x10 = 12500000000000000000; // 2ˆ-3
    int256 constant a10 = 113314845306682631683; // eˆ(x10)
    int256 constant x11 = 6250000000000000000; // 2ˆ-4
    int256 constant a11 = 106449445891785942956; // eˆ(x11)

    /**
     * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
     *
     * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
     */
    function pow(uint256 x, uint256 y) internal pure returns (uint256) {
        if (y == 0) {
            // We solve the 0^0 indetermination by making it equal one.
            return uint256(ONE_18);
        }

        if (x == 0) {
            return 0;
        }

        // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
        // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
        // x^y = exp(y * ln(x)).

        // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
        _require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
        int256 x_int256 = int256(x);

        // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
        // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.

        // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
        _require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
        int256 y_int256 = int256(y);

        int256 logx_times_y;
        if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
            int256 ln_36_x = _ln_36(x_int256);

            // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
            // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
            // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
            // (downscaled) last 18 decimals.
            logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
        } else {
            logx_times_y = _ln(x_int256) * y_int256;
        }
        logx_times_y /= ONE_18;

        // Finally, we compute exp(y * ln(x)) to arrive at x^y
        _require(
            MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
            Errors.PRODUCT_OUT_OF_BOUNDS
        );

        return uint256(exp(logx_times_y));
    }

    /**
     * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
     *
     * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
     */
    function exp(int256 x) internal pure returns (int256) {
        _require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);

        if (x < 0) {
            // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
            // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
            // Fixed point division requires multiplying by ONE_18.
            return ((ONE_18 * ONE_18) / exp(-x));
        }

        // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
        // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
        // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
        // decomposition.
        // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
        // decomposition, which will be lower than the smallest x_n.
        // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
        // We mutate x by subtracting x_n, making it the remainder of the decomposition.

        // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
        // intermediate overflows. Instead we store them as plain integers, with 0 decimals.
        // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
        // decomposition.

        // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
        // it and compute the accumulated product.

        int256 firstAN;
        if (x >= x0) {
            x -= x0;
            firstAN = a0;
        } else if (x >= x1) {
            x -= x1;
            firstAN = a1;
        } else {
            firstAN = 1; // One with no decimal places
        }

        // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
        // smaller terms.
        x *= 100;

        // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
        // one. Recall that fixed point multiplication requires dividing by ONE_20.
        int256 product = ONE_20;

        if (x >= x2) {
            x -= x2;
            product = (product * a2) / ONE_20;
        }
        if (x >= x3) {
            x -= x3;
            product = (product * a3) / ONE_20;
        }
        if (x >= x4) {
            x -= x4;
            product = (product * a4) / ONE_20;
        }
        if (x >= x5) {
            x -= x5;
            product = (product * a5) / ONE_20;
        }
        if (x >= x6) {
            x -= x6;
            product = (product * a6) / ONE_20;
        }
        if (x >= x7) {
            x -= x7;
            product = (product * a7) / ONE_20;
        }
        if (x >= x8) {
            x -= x8;
            product = (product * a8) / ONE_20;
        }
        if (x >= x9) {
            x -= x9;
            product = (product * a9) / ONE_20;
        }

        // x10 and x11 are unnecessary here since we have high enough precision already.

        // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
        // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).

        int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
        int256 term; // Each term in the sum, where the nth term is (x^n / n!).

        // The first term is simply x.
        term = x;
        seriesSum += term;

        // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
        // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.

        term = ((term * x) / ONE_20) / 2;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 3;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 4;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 5;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 6;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 7;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 8;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 9;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 10;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 11;
        seriesSum += term;

        term = ((term * x) / ONE_20) / 12;
        seriesSum += term;

        // 12 Taylor terms are sufficient for 18 decimal precision.

        // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
        // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
        // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
        // and then drop two digits to return an 18 decimal value.

        return (((product * seriesSum) / ONE_20) * firstAN) / 100;
    }

    /**
     * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
     */
    function log(int256 arg, int256 base) internal pure returns (int256) {
        // This performs a simple base change: log(arg, base) = ln(arg) / ln(base).

        // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
        // upscaling.

        int256 logBase;
        if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
            logBase = _ln_36(base);
        } else {
            logBase = _ln(base) * ONE_18;
        }

        int256 logArg;
        if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
            logArg = _ln_36(arg);
        } else {
            logArg = _ln(arg) * ONE_18;
        }

        // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
        return (logArg * ONE_18) / logBase;
    }

    /**
     * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
     */
    function ln(int256 a) internal pure returns (int256) {
        // The real natural logarithm is not defined for negative numbers or zero.
        _require(a > 0, Errors.OUT_OF_BOUNDS);
        if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
            return _ln_36(a) / ONE_18;
        } else {
            return _ln(a);
        }
    }

    /**
     * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
     */
    function _ln(int256 a) private pure returns (int256) {
        if (a < ONE_18) {
            // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
            // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
            // Fixed point division requires multiplying by ONE_18.
            return (-_ln((ONE_18 * ONE_18) / a));
        }

        // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
        // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
        // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
        // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
        // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
        // decomposition, which will be lower than the smallest a_n.
        // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
        // We mutate a by subtracting a_n, making it the remainder of the decomposition.

        // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
        // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
        // ONE_18 to convert them to fixed point.
        // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
        // by it and compute the accumulated sum.

        int256 sum = 0;
        if (a >= a0 * ONE_18) {
            a /= a0; // Integer, not fixed point division
            sum += x0;
        }

        if (a >= a1 * ONE_18) {
            a /= a1; // Integer, not fixed point division
            sum += x1;
        }

        // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
        sum *= 100;
        a *= 100;

        // Because further a_n are  20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.

        if (a >= a2) {
            a = (a * ONE_20) / a2;
            sum += x2;
        }

        if (a >= a3) {
            a = (a * ONE_20) / a3;
            sum += x3;
        }

        if (a >= a4) {
            a = (a * ONE_20) / a4;
            sum += x4;
        }

        if (a >= a5) {
            a = (a * ONE_20) / a5;
            sum += x5;
        }

        if (a >= a6) {
            a = (a * ONE_20) / a6;
            sum += x6;
        }

        if (a >= a7) {
            a = (a * ONE_20) / a7;
            sum += x7;
        }

        if (a >= a8) {
            a = (a * ONE_20) / a8;
            sum += x8;
        }

        if (a >= a9) {
            a = (a * ONE_20) / a9;
            sum += x9;
        }

        if (a >= a10) {
            a = (a * ONE_20) / a10;
            sum += x10;
        }

        if (a >= a11) {
            a = (a * ONE_20) / a11;
            sum += x11;
        }

        // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
        // that converges rapidly for values of `a` close to one - the same one used in ln_36.
        // Let z = (a - 1) / (a + 1).
        // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))

        // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
        // division by ONE_20.
        int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
        int256 z_squared = (z * z) / ONE_20;

        // num is the numerator of the series: the z^(2 * n + 1) term
        int256 num = z;

        // seriesSum holds the accumulated sum of each term in the series, starting with the initial z
        int256 seriesSum = num;

        // In each step, the numerator is multiplied by z^2
        num = (num * z_squared) / ONE_20;
        seriesSum += num / 3;

        num = (num * z_squared) / ONE_20;
        seriesSum += num / 5;

        num = (num * z_squared) / ONE_20;
        seriesSum += num / 7;

        num = (num * z_squared) / ONE_20;
        seriesSum += num / 9;

        num = (num * z_squared) / ONE_20;
        seriesSum += num / 11;

        // 6 Taylor terms are sufficient for 36 decimal precision.

        // Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
        seriesSum *= 2;

        // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
        // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
        // value.

        return (sum + seriesSum) / 100;
    }

    /**
     * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
     * for x close to one.
     *
     * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
     */
    function _ln_36(int256 x) private pure returns (int256) {
        // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
        // worthwhile.

        // First, we transform x to a 36 digit fixed point value.
        x *= ONE_18;

        // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
        // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))

        // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
        // division by ONE_36.
        int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
        int256 z_squared = (z * z) / ONE_36;

        // num is the numerator of the series: the z^(2 * n + 1) term
        int256 num = z;

        // seriesSum holds the accumulated sum of each term in the series, starting with the initial z
        int256 seriesSum = num;

        // In each step, the numerator is multiplied by z^2
        num = (num * z_squared) / ONE_36;
        seriesSum += num / 3;

        num = (num * z_squared) / ONE_36;
        seriesSum += num / 5;

        num = (num * z_squared) / ONE_36;
        seriesSum += num / 7;

        num = (num * z_squared) / ONE_36;
        seriesSum += num / 9;

        num = (num * z_squared) / ONE_36;
        seriesSum += num / 11;

        num = (num * z_squared) / ONE_36;
        seriesSum += num / 13;

        num = (num * z_squared) / ONE_36;
        seriesSum += num / 15;

        // 8 Taylor terms are sufficient for 36 decimal precision.

        // All that remains is multiplying by 2 (non fixed point).
        return seriesSum * 2;
    }
}

File 13 of 32 : 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;

// solhint-disable

/**
 * @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) pure {
    if (!condition) _revert(errorCode);
}

/**
 * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported.
 */
function _revert(uint256 errorCode) pure {
    // 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. The "BAL#" part is a known constant
        // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the
        // characters to it, each shifted by a multiple of 8.
        // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits
        // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte
        // array).

        let revertReason := shl(200, add(0x42414c23000000, 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;

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

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

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

    // 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;
}

File 14 of 32 : ERC20Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./ERC20.sol";
import "./IERC20Permit.sol";
import "./EIP712.sol";

/**
 * @dev Implementation 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.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    mapping(address => uint256) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private immutable _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        // solhint-disable-next-line not-rely-on-time
        _require(block.timestamp <= deadline, Errors.EXPIRED_PERMIT);

        uint256 nonce = _nonces[owner];
        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, nonce, deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ecrecover(hash, v, r, s);
        _require((signer != address(0)) && (signer == owner), Errors.INVALID_SIGNATURE);

        _nonces[owner] = nonce + 1;
        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view override returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }
}

File 15 of 32 : SafeMath.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../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 16 of 32 : IERC20Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.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 17 of 32 : EIP712.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _HASHED_NAME = keccak256(bytes(name));
        _HASHED_VERSION = keccak256(bytes(version));
        _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view virtual returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION, _getChainId(), address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
    }

    function _getChainId() private view returns (uint256 chainId) {
        // Silence state mutability warning without generating bytecode.
        // See https://github.com/ethereum/solidity/issues/10090#issuecomment-741789128 and
        // https://github.com/ethereum/solidity/issues/2691
        this;

        // solhint-disable-next-line no-inline-assembly
        assembly {
            chainId := chainid()
        }
    }
}

File 18 of 32 : IBasePool.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 "./IVault.sol";
import "./IPoolSwapStructs.sol";

/**
 * @dev Interface for adding and removing liquidity that all Pool contracts should implement. Note that this is not
 * the complete Pool contract interface, as it is missing the swap hooks. Pool contracts should also inherit from
 * either IGeneralPool or IMinimalSwapInfoPool
 */
interface IBasePool is IPoolSwapStructs {
    /**
     * @dev Called by the Vault when a user calls `IVault.joinPool` to add liquidity to this Pool. Returns how many of
     * each registered token the user should provide, as well as the amount of protocol fees the Pool owes to the Vault.
     * The Vault will then take tokens from `sender` and add them to the Pool's balances, as well as collect
     * the reported amount in protocol fees, which the pool should calculate based on `protocolSwapFeePercentage`.
     *
     * Protocol fees are reported and charged on join events so that the Pool is free of debt whenever new users join.
     *
     * `sender` is the account performing the join (from which tokens will be withdrawn), and `recipient` is the account
     * designated to receive any benefits (typically pool shares). `balances` contains the total balances
     * for each token the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
     *
     * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
     * balance.
     *
     * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
     * join (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
     *
     * Contracts implementing this function should check that the caller is indeed the Vault before performing any
     * state-changing operations, such as minting pool shares.
     */
    function onJoinPool(
        bytes32 poolId,
        address sender,
        address recipient,
        uint256[] memory balances,
        uint256 lastChangeBlock,
        uint256 protocolSwapFeePercentage,
        bytes memory userData
    ) external returns (uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts);

    /**
     * @dev Called by the Vault when a user calls `IVault.exitPool` to remove liquidity from this Pool. Returns how many
     * tokens the Vault should deduct from the Pool's balances, as well as the amount of protocol fees the Pool owes
     * to the Vault. The Vault will then take tokens from the Pool's balances and send them to `recipient`,
     * as well as collect the reported amount in protocol fees, which the Pool should calculate based on
     * `protocolSwapFeePercentage`.
     *
     * Protocol fees are charged on exit events to guarantee that users exiting the Pool have paid their share.
     *
     * `sender` is the account performing the exit (typically the pool shareholder), and `recipient` is the account
     * to which the Vault will send the proceeds. `balances` contains the total token balances for each token
     * the Pool registered in the Vault, in the same order that `IVault.getPoolTokens` would return.
     *
     * `lastChangeBlock` is the last block in which *any* of the Pool's registered tokens last changed its total
     * balance.
     *
     * `userData` contains any pool-specific instructions needed to perform the calculations, such as the type of
     * exit (e.g., proportional given an amount of pool shares, single-asset, multi-asset, etc.)
     *
     * Contracts implementing this function should check that the caller is indeed the Vault before performing any
     * state-changing operations, such as burning pool shares.
     */
    function onExitPool(
        bytes32 poolId,
        address sender,
        address recipient,
        uint256[] memory balances,
        uint256 lastChangeBlock,
        uint256 protocolSwapFeePercentage,
        bytes memory userData
    ) external returns (uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts);

    function getPoolId() external view returns (bytes32);
}

File 19 of 32 : IPoolSwapStructs.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/IERC20.sol";

import "./IVault.sol";

interface IPoolSwapStructs {
    // This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and
    // IMinimalSwapInfoPool.
    //
    // This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or
    // 'given out') which indicates whether or not the amount sent by the pool is known.
    //
    // The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take
    // in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`.
    //
    // All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in
    // some Pools.
    //
    // `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than
    // one Pool.
    //
    // The meaning of `lastChangeBlock` depends on the Pool specialization:
    //  - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total
    //    balance.
    //  - General: the last block in which *any* of the Pool's registered tokens changed its total balance.
    //
    // `from` is the origin address for the funds the Pool receives, and `to` is the destination address
    // where the Pool sends the outgoing tokens.
    //
    // `userData` is extra data provided by the caller - typically a signature from a trusted party.
    struct SwapRequest {
        IVault.SwapKind kind;
        IERC20 tokenIn;
        IERC20 tokenOut;
        uint256 amount;
        // Misc data
        bytes32 poolId;
        uint256 lastChangeBlock;
        address from;
        address to;
        bytes userData;
    }
}

File 20 of 32 : 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;

/**
 * @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 21 of 32 : 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;

/**
 * @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 22 of 32 : 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;

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 23 of 32 : 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;

/**
 * @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 24 of 32 : 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;

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 25 of 32 : 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;

// Inspired by Aave Protocol's IFlashLoanReceiver.

import "@balancer-labs/v2-solidity-utils/contracts/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 26 of 32 : 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;
pragma experimental ABIEncoderV2;

import "@balancer-labs/v2-solidity-utils/contracts/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 27 of 32 : IPriceOracle.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/>.

// Forked from balancer-v2-monorepo/pkg/pool-utils/contracts/oracle/**
// at commit ef246cf213541c4120a78f811560f100e5a7e15a

pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

/**
 * @dev Interface for querying historical data from a Pool that can be used as a Price Oracle.
 *
 * This lets third parties retrieve average prices of tokens held by a Pool over a given period of time, as well as the
 * price of the Pool share token (BPT) and invariant. Since the invariant is a sensible measure of Pool liquidity, it
 * can be used to compare two different price sources, and choose the most liquid one.
 *
 * Once the oracle is fully initialized, all queries are guaranteed to succeed as long as they require no data that
 * is not older than the largest safe query window.
 */
interface IPriceOracle {
    // The three values that can be queried:
    //
    // - PAIR_PRICE: the price of the tokens in the Pool, expressed as the price of the second token in units of the
    //   first token. For example, if token A is worth $2, and token B is worth $4, the pair price will be 2.0.
    //   Note that the price is computed *including* the tokens decimals. This means that the pair price of a Pool with
    //   DAI and USDC will be close to 1.0, despite DAI having 18 decimals and USDC 6.
    //
    // - BPT_PRICE: the price of the Pool share token (BPT), in units of the first token.
    //   Note that the price is computed *including* the tokens decimals. This means that the BPT price of a Pool with
    //   USDC in which BPT is worth $5 will be 5.0, despite the BPT having 18 decimals and USDC 6.
    //
    // - INVARIANT: the value of the Pool's invariant, which serves as a measure of its liquidity.
    enum Variable { PAIR_PRICE, BPT_PRICE, INVARIANT }

    /**
     * @dev Returns the time average weighted price corresponding to each of `queries`. Prices are represented as 18
     * decimal fixed point values.
     */
    function getTimeWeightedAverage(OracleAverageQuery[] memory queries)
        external
        view
        returns (uint256[] memory results);

    /**
     * @dev Returns latest sample of `variable`. Prices are represented as 18 decimal fixed point values.
     */
    function getLatest(Variable variable) external view returns (uint256);

    /**
     * @dev Information for a Time Weighted Average query.
     *
     * Each query computes the average over a window of duration `secs` seconds that ended `ago` seconds ago. For
     * example, the average over the past 30 minutes is computed by settings secs to 1800 and ago to 0. If secs is 1800
     * and ago is 1800 as well, the average between 60 and 30 minutes ago is computed instead.
     */
    struct OracleAverageQuery {
        Variable variable;
        uint256 secs;
        uint256 ago;
    }

    /**
     * @dev Returns largest time window that can be safely queried, where 'safely' means the Oracle is guaranteed to be
     * able to produce a result and not revert.
     *
     * If a query has a non-zero `ago` value, then `secs + ago` (the oldest point in time) must be smaller than this
     * value for 'safe' queries.
     */
    function getLargestSafeQueryWindow() external view returns (uint256);

    /**
     * @dev Returns the accumulators corresponding to each of `queries`.
     */
    function getPastAccumulators(OracleAccumulatorQuery[] memory queries)
        external
        view
        returns (int256[] memory results);

    /**
     * @dev Information for an Accumulator query.
     *
     * Each query estimates the accumulator at a time `ago` seconds ago.
     */
    struct OracleAccumulatorQuery {
        Variable variable;
        uint256 ago;
    }
}

File 28 of 32 : IPoolPriceOracle.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/>.

// Forked from balancer-v2-monorepo/pkg/pool-utils/contracts/oracle/**
// at commit ef246cf213541c4120a78f811560f100e5a7e15a

pragma solidity ^0.7.0;

interface IPoolPriceOracle {
    /**
     * @dev Returns the raw data of the sample at `index`.
     */
    function getSample(uint256 index)
        external
        view
        returns (
            int256 logPairPrice,
            int256 accLogPairPrice,
            int256 logBptPrice,
            int256 accLogBptPrice,
            int256 logInvariant,
            int256 accLogInvariant,
            uint256 timestamp
        );

    /**
     * @dev Returns the total number of samples.
     */
    function getTotalSamples() external view returns (uint256);
}

File 29 of 32 : Buffer.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/>.

// Forked from balancer-v2-monorepo/pkg/pool-utils/contracts/oracle/**
// at commit ef246cf213541c4120a78f811560f100e5a7e15a

pragma solidity ^0.7.0;

library Buffer {
    // The buffer is a circular storage structure with 20 slots.
    // solhint-disable-next-line private-vars-leading-underscore
    uint256 internal constant SIZE = 20;

    /**
     * @dev Returns the index of the element before the one pointed by `index`.
     */
    function prev(uint256 index) internal pure returns (uint256) {
        return sub(index, 1);
    }

    /**
     * @dev Returns the index of the element after the one pointed by `index`.
     */
    function next(uint256 index) internal pure returns (uint256) {
        return add(index, 1);
    }

    /**
     * @dev Returns the index of an element `offset` slots after the one pointed by `index`.
     */
    function add(uint256 index, uint256 offset) internal pure returns (uint256) {
        return (index + offset) % SIZE;
    }

    /**
     * @dev Returns the index of an element `offset` slots before the one pointed by `index`.
     */
    function sub(uint256 index, uint256 offset) internal pure returns (uint256) {
        return (index + SIZE - offset) % SIZE;
    }
}

File 30 of 32 : Samples.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/>.

// Forked from balancer-v2-monorepo/pkg/pool-utils/contracts/oracle/**
// at commit ef246cf213541c4120a78f811560f100e5a7e15a

pragma solidity ^0.7.0;

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

import "./interfaces/IPriceOracle.sol";

/**
 * @dev This library provides functions to help manipulating samples for Pool Price Oracles. It handles updates,
 * encoding, and decoding of samples.
 *
 * Each sample holds the timestamp of its last update, plus information about three pieces of data: the price pair, the
 * price of BPT (the associated Pool token), and the invariant.
 *
 * Prices and invariant are not stored directly: instead, we store their logarithm. These are known as the 'instant'
 * values: the exact value at that timestamp.
 *
 * Additionally, for each value we keep an accumulator with the sum of all past values, each weighted by the time
 * elapsed since the previous update. This lets us later subtract accumulators at different points in time and divide by
 * the time elapsed between them, arriving at the geometric mean of the values (also known as log-average).
 *
 * All samples are stored in a single 256 bit word with the following structure:
 *
 * [    log pair price     |        bpt price      |       invariant       |  timestamp ]
 * [ instant | accumulator | instant | accumulator | instant | accumulator |            ]
 * [  int22  |    int53    |  int22  |    int53    |  int22  |    int53    |    uint31  ]
 * MSB                                                                                LSB
 *
 * Assuming the timestamp doesn't overflow (which holds until the year 2038), the largest elapsed time is 2^31, which
 * means the largest possible accumulator value is 2^21 * 2^31, which can be represented using a signed 53 bit integer.
 */
library Samples {
    using WordCodec for int256;
    using WordCodec for uint256;
    using WordCodec for bytes32;

    uint256 internal constant _TIMESTAMP_OFFSET = 0;
    uint256 internal constant _ACC_LOG_INVARIANT_OFFSET = 31;
    uint256 internal constant _INST_LOG_INVARIANT_OFFSET = 84;
    uint256 internal constant _ACC_LOG_BPT_PRICE_OFFSET = 106;
    uint256 internal constant _INST_LOG_BPT_PRICE_OFFSET = 159;
    uint256 internal constant _ACC_LOG_PAIR_PRICE_OFFSET = 181;
    uint256 internal constant _INST_LOG_PAIR_PRICE_OFFSET = 234;

    /**
     * @dev Updates a sample, accumulating the new data based on the elapsed time since the previous update. Returns the
     * updated sample.
     *
     * IMPORTANT: This function does not perform any arithmetic checks. In particular, it assumes the caller will never
     * pass values that cannot be represented as 22 bit signed integers. Additionally, it also assumes
     * `currentTimestamp` is greater than `sample`'s timestamp.
     */
    function update(
        bytes32 sample,
        int256 instLogPairPrice,
        int256 instLogBptPrice,
        int256 instLogInvariant,
        uint256 currentTimestamp
    ) internal pure returns (bytes32) {
        // Because elapsed can be represented as a 31 bit unsigned integer, and the received values can be represented
        // as 22 bit signed integers, we don't need to perform checked arithmetic.

        int256 elapsed = int256(currentTimestamp - timestamp(sample));
        int256 accLogPairPrice = _accLogPairPrice(sample) + instLogPairPrice * elapsed;
        int256 accLogBptPrice = _accLogBptPrice(sample) + instLogBptPrice * elapsed;
        int256 accLogInvariant = _accLogInvariant(sample) + instLogInvariant * elapsed;

        return
            pack(
                instLogPairPrice,
                accLogPairPrice,
                instLogBptPrice,
                accLogBptPrice,
                instLogInvariant,
                accLogInvariant,
                currentTimestamp
            );
    }

    /**
     * @dev Returns the instant value stored in `sample` for `variable`.
     */
    function instant(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) {
        if (variable == IPriceOracle.Variable.PAIR_PRICE) {
            return _instLogPairPrice(sample);
        } else if (variable == IPriceOracle.Variable.BPT_PRICE) {
            return _instLogBptPrice(sample);
        } else {
            // variable == IPriceOracle.Variable.INVARIANT
            return _instLogInvariant(sample);
        }
    }

    /**
     * @dev Returns the accumulator value stored in `sample` for `variable`.
     */
    function accumulator(bytes32 sample, IPriceOracle.Variable variable) internal pure returns (int256) {
        if (variable == IPriceOracle.Variable.PAIR_PRICE) {
            return _accLogPairPrice(sample);
        } else if (variable == IPriceOracle.Variable.BPT_PRICE) {
            return _accLogBptPrice(sample);
        } else {
            // variable == IPriceOracle.Variable.INVARIANT
            return _accLogInvariant(sample);
        }
    }

    /**
     * @dev Returns `sample`'s timestamp.
     */
    function timestamp(bytes32 sample) internal pure returns (uint256) {
        return sample.decodeUint31(_TIMESTAMP_OFFSET);
    }

    /**
     * @dev Returns `sample`'s instant value for the logarithm of the pair price.
     */
    function _instLogPairPrice(bytes32 sample) private pure returns (int256) {
        return sample.decodeInt22(_INST_LOG_PAIR_PRICE_OFFSET);
    }

    /**
     * @dev Returns `sample`'s accumulator of the logarithm of the pair price.
     */
    function _accLogPairPrice(bytes32 sample) private pure returns (int256) {
        return sample.decodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET);
    }

    /**
     * @dev Returns `sample`'s instant value for the logarithm of the BPT price.
     */
    function _instLogBptPrice(bytes32 sample) private pure returns (int256) {
        return sample.decodeInt22(_INST_LOG_BPT_PRICE_OFFSET);
    }

    /**
     * @dev Returns `sample`'s accumulator of the logarithm of the BPT price.
     */
    function _accLogBptPrice(bytes32 sample) private pure returns (int256) {
        return sample.decodeInt53(_ACC_LOG_BPT_PRICE_OFFSET);
    }

    /**
     * @dev Returns `sample`'s instant value for the logarithm of the invariant.
     */
    function _instLogInvariant(bytes32 sample) private pure returns (int256) {
        return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET);
    }

    /**
     * @dev Returns `sample`'s accumulator of the logarithm of the invariant.
     */
    function _accLogInvariant(bytes32 sample) private pure returns (int256) {
        return sample.decodeInt53(_ACC_LOG_INVARIANT_OFFSET);
    }

    /**
     * @dev Returns a sample created by packing together its components.
     */
    function pack(
        int256 instLogPairPrice,
        int256 accLogPairPrice,
        int256 instLogBptPrice,
        int256 accLogBptPrice,
        int256 instLogInvariant,
        int256 accLogInvariant,
        uint256 _timestamp
    ) internal pure returns (bytes32) {
        return
            instLogPairPrice.encodeInt22(_INST_LOG_PAIR_PRICE_OFFSET) |
            accLogPairPrice.encodeInt53(_ACC_LOG_PAIR_PRICE_OFFSET) |
            instLogBptPrice.encodeInt22(_INST_LOG_BPT_PRICE_OFFSET) |
            accLogBptPrice.encodeInt53(_ACC_LOG_BPT_PRICE_OFFSET) |
            instLogInvariant.encodeInt22(_INST_LOG_INVARIANT_OFFSET) |
            accLogInvariant.encodeInt53(_ACC_LOG_INVARIANT_OFFSET) |
            _timestamp.encodeUint(_TIMESTAMP_OFFSET); // Using 31 bits
    }

    /**
     * @dev Unpacks a sample into its components.
     */
    function unpack(bytes32 sample)
        internal
        pure
        returns (
            int256 logPairPrice,
            int256 accLogPairPrice,
            int256 logBptPrice,
            int256 accLogBptPrice,
            int256 logInvariant,
            int256 accLogInvariant,
            uint256 _timestamp
        )
    {
        logPairPrice = _instLogPairPrice(sample);
        accLogPairPrice = _accLogPairPrice(sample);
        logBptPrice = _instLogBptPrice(sample);
        accLogBptPrice = _accLogBptPrice(sample);
        logInvariant = _instLogInvariant(sample);
        accLogInvariant = _accLogInvariant(sample);
        _timestamp = timestamp(sample);
    }
}

File 31 of 32 : QueryProcessor.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/>.

// Forked from balancer-v2-monorepo/pkg/pool-utils/contracts/oracle/**
// at commit ef246cf213541c4120a78f811560f100e5a7e15a

pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;

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

import "./interfaces/IPriceOracle.sol";

import "./Buffer.sol";
import "./Samples.sol";

/**
 * @dev Auxiliary library for PoolPriceOracle, offloading most of the query code to reduce bytecode size by using this
 * as a linked library. The downside is an extra DELEGATECALL is added (2600 gas as of the Berlin hardfork), but the
 * bytecode size gains are so big (specially of the oracle contract does not use `LogCompression.fromLowResLog`) that
 * it is worth it.
 */
library QueryProcessor {
    using Buffer for uint256;
    using Samples for bytes32;
    using LogCompression for int256;

    /**
     * @dev Returns the value for `variable` at the indexed sample.
     */
    function getInstantValue(
        mapping(uint256 => bytes32) storage samples,
        IPriceOracle.Variable variable,
        uint256 index
    ) external view returns (uint256) {
        bytes32 sample = samples[index];
        _require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED);

        int256 rawInstantValue = sample.instant(variable);
        return LogCompression.fromLowResLog(rawInstantValue);
    }

    /**
     * @dev Returns the time average weighted price corresponding to `query`.
     */
    function getTimeWeightedAverage(
        mapping(uint256 => bytes32) storage samples,
        IPriceOracle.OracleAverageQuery memory query,
        uint256 latestIndex
    ) external view returns (uint256) {
        _require(query.secs != 0, Errors.ORACLE_BAD_SECS);

        int256 beginAccumulator = getPastAccumulator(samples, query.variable, latestIndex, query.ago + query.secs);
        int256 endAccumulator = getPastAccumulator(samples, query.variable, latestIndex, query.ago);
        return LogCompression.fromLowResLog((endAccumulator - beginAccumulator) / int256(query.secs));
    }

    /**
     * @dev Returns the value of the accumulator for `variable` `ago` seconds ago. `latestIndex` must be the index of
     * the latest sample in the buffer.
     *
     * Reverts under the following conditions:
     *  - if the buffer is empty.
     *  - if querying past information and the buffer has not been fully initialized.
     *  - if querying older information than available in the buffer. Note that a full buffer guarantees queries for the
     *    past 34 hours will not revert.
     *
     * If requesting information for a timestamp later than the latest one, it is extrapolated using the latest
     * available data.
     *
     * When no exact information is available for the requested past timestamp (as usually happens, since at most one
     * timestamp is stored every two minutes), it is estimated by performing linear interpolation using the closest
     * values. This process is guaranteed to complete performing at most 10 storage reads.
     */
    function getPastAccumulator(
        mapping(uint256 => bytes32) storage samples,
        IPriceOracle.Variable variable,
        uint256 latestIndex,
        uint256 ago
    ) public view returns (int256) {
        // solhint-disable not-rely-on-time
        // `ago` must not be before the epoch.
        _require(block.timestamp >= ago, Errors.ORACLE_INVALID_SECONDS_QUERY);
        uint256 lookUpTime = block.timestamp - ago;

        bytes32 latestSample = samples[latestIndex];
        uint256 latestTimestamp = latestSample.timestamp();

        // The latest sample only has a non-zero timestamp if no data was ever processed and stored in the buffer.
        _require(latestTimestamp > 0, Errors.ORACLE_NOT_INITIALIZED);

        if (latestTimestamp <= lookUpTime) {
            // The accumulator at times ahead of the latest one are computed by extrapolating the latest data. This is
            // equivalent to the instant value not changing between the last timestamp and the look up time.

            // We can use unchecked arithmetic since the accumulator can be represented in 53 bits, timestamps in 31
            // bits, and the instant value in 22 bits.
            uint256 elapsed = lookUpTime - latestTimestamp;
            return latestSample.accumulator(variable) + (latestSample.instant(variable) * int256(elapsed));
        } else {
            // The look up time is before the latest sample, but we need to make sure that it is not before the oldest
            // sample as well.

            // Since we use a circular buffer, the oldest sample is simply the next one.
            uint256 bufferLength;
            uint256 oldestIndex = latestIndex.next();
            {
                // Local scope used to prevent stack-too-deep errors.
                bytes32 oldestSample = samples[oldestIndex];
                uint256 oldestTimestamp = oldestSample.timestamp();

                if (oldestTimestamp > 0) {
                    // If the oldest timestamp is not zero, it means the buffer was fully initialized.
                    bufferLength = Buffer.SIZE;
                } else {
                    // If the buffer was not fully initialized, we haven't wrapped around it yet,
                    // and can treat it as a regular array where the oldest index is the first one,
                    // and the length the number of samples.
                    bufferLength = oldestIndex; // Equal to latestIndex.next()
                    oldestIndex = 0;
                    oldestTimestamp = samples[0].timestamp();
                }

                // Finally check that the look up time is not previous to the oldest timestamp.
                _require(oldestTimestamp <= lookUpTime, Errors.ORACLE_QUERY_TOO_OLD);
            }

            // Perform binary search to find nearest samples to the desired timestamp.
            (bytes32 prev, bytes32 next) = findNearestSample(samples, lookUpTime, oldestIndex, bufferLength);

            // `next`'s timestamp is guaranteed to be larger than `prev`'s, so we can skip checked arithmetic.
            uint256 samplesTimeDiff = next.timestamp() - prev.timestamp();

            if (samplesTimeDiff > 0) {
                // We estimate the accumulator at the requested look up time by interpolating linearly between the
                // previous and next accumulators.

                // We can use unchecked arithmetic since the accumulators can be represented in 53 bits, and timestamps
                // in 31 bits.
                int256 samplesAccDiff = next.accumulator(variable) - prev.accumulator(variable);
                uint256 elapsed = lookUpTime - prev.timestamp();
                return prev.accumulator(variable) + ((samplesAccDiff * int256(elapsed)) / int256(samplesTimeDiff));
            } else {
                // Rarely, one of the samples will have the exact requested look up time, which is indicated by `prev`
                // and `next` being the same. In this case, we simply return the accumulator at that point in time.
                return prev.accumulator(variable);
            }
        }
    }

    /**
     * @dev Finds the two samples with timestamps before and after `lookUpDate`. If one of the samples matches exactly,
     * both `prev` and `next` will be it. `offset` is the index of the oldest sample in the buffer. `length` is the size
     * of the samples list.
     *
     * Assumes `lookUpDate` is greater or equal than the timestamp of the oldest sample, and less or equal than the
     * timestamp of the latest sample.
     */
    function findNearestSample(
        mapping(uint256 => bytes32) storage samples,
        uint256 lookUpDate,
        uint256 offset,
        uint256 length
    ) public view returns (bytes32 prev, bytes32 next) {
        // We're going to perform a binary search in the circular buffer, which requires it to be sorted. To achieve
        // this, we offset all buffer accesses by `offset`, making the first element the oldest one.

        // Auxiliary variables in a typical binary search: we will look at some value `mid` between `low` and `high`,
        // periodically increasing `low` or decreasing `high` until we either find a match or determine the element is
        // not in the array.
        uint256 low = 0;
        uint256 high = length - 1;
        uint256 mid;

        // If the search fails and no sample has a timestamp of `lookUpDate` (as is the most common scenario), `sample`
        // will be either the sample with the largest timestamp smaller than `lookUpDate`, or the one with the smallest
        // timestamp larger than `lookUpDate`.
        bytes32 sample;
        uint256 sampleTimestamp;

        while (low <= high) {
            // Mid is the floor of the average.
            uint256 midWithoutOffset = (high + low) / 2;

            // Recall that the buffer is not actually sorted: we need to apply the offset to access it in a sorted way.
            mid = midWithoutOffset.add(offset);
            sample = samples[mid];
            sampleTimestamp = sample.timestamp();

            if (sampleTimestamp < lookUpDate) {
                // If the mid sample is bellow the look up date, then increase the low index to start from there.
                low = midWithoutOffset + 1;
            } else if (sampleTimestamp > lookUpDate) {
                // If the mid sample is above the look up date, then decrease the high index to start from there.

                // We can skip checked arithmetic: it is impossible for `high` to ever be 0, as a scenario where `low`
                // equals 0 and `high` equals 1 would result in `low` increasing to 1 in the previous `if` clause.
                high = midWithoutOffset - 1;
            } else {
                // sampleTimestamp == lookUpDate
                // If we have an exact match, return the sample as both `prev` and `next`.
                return (sample, sample);
            }
        }

        // In case we reach here, it means we didn't find exactly the sample we where looking for.
        return sampleTimestamp < lookUpDate ? (sample, samples[mid.next()]) : (samples[mid.prev()], sample);
    }
}

File 32 of 32 : WordCodec.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;

/**
 * @dev Library for encoding and decoding values stored inside a 256 bit word. Typically used to pack multiple values in
 * a single storage slot, saving gas by performing less storage accesses.
 *
 * Each value is defined by its size and the least significant bit in the word, also known as offset. For example, two
 * 128 bit values may be encoded in a word by assigning one an offset of 0, and the other an offset of 128.
 */
library WordCodec {
    // Masks are values with the least significant N bits set. They can be used to extract an encoded value from a word,
    // or to insert a new one replacing the old.
    uint256 private constant _MASK_1 = 2**(1) - 1;
    uint256 private constant _MASK_5 = 2**(5) - 1;
    uint256 private constant _MASK_7 = 2**(7) - 1;
    uint256 private constant _MASK_10 = 2**(10) - 1;
    uint256 private constant _MASK_16 = 2**(16) - 1;
    uint256 private constant _MASK_22 = 2**(22) - 1;
    uint256 private constant _MASK_31 = 2**(31) - 1;
    uint256 private constant _MASK_32 = 2**(32) - 1;
    uint256 private constant _MASK_53 = 2**(53) - 1;
    uint256 private constant _MASK_64 = 2**(64) - 1;
    uint256 private constant _MASK_128 = 2**(128) - 1;
    uint256 private constant _MASK_192 = 2**(192) - 1;

    // Largest positive values that can be represented as N bits signed integers.
    int256 private constant _MAX_INT_22 = 2**(21) - 1;
    int256 private constant _MAX_INT_53 = 2**(52) - 1;

    // In-place insertion

    /**
     * @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
     * word.
     */
    function insertBool(
        bytes32 word,
        bool value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_1 << offset));
        return clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
    }

    // Unsigned

    /**
     * @dev Inserts a 5 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` only uses its least significant 5 bits, otherwise it may overwrite sibling bytes.
     */
    function insertUint5(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_5 << offset));
        return clearedWord | bytes32(value << offset);
    }

    /**
     * @dev Inserts a 7 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` only uses its least significant 7 bits, otherwise it may overwrite sibling bytes.
     */
    function insertUint7(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_7 << offset));
        return clearedWord | bytes32(value << offset);
    }

    /**
     * @dev Inserts a 10 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` only uses its least significant 10 bits, otherwise it may overwrite sibling bytes.
     */
    function insertUint10(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_10 << offset));
        return clearedWord | bytes32(value << offset);
    }

    /**
     * @dev Inserts a 16 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value.
     * Returns the new word.
     *
     * Assumes `value` only uses its least significant 16 bits, otherwise it may overwrite sibling bytes.
     */
    function insertUint16(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_16 << offset));
        return clearedWord | bytes32(value << offset);
    }

    /**
     * @dev Inserts a 31 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` can be represented using 31 bits.
     */
    function insertUint31(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_31 << offset));
        return clearedWord | bytes32(value << offset);
    }

    /**
     * @dev Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes.
     */
    function insertUint32(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_32 << offset));
        return clearedWord | bytes32(value << offset);
    }

    /**
     * @dev Inserts a 64 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` only uses its least significant 64 bits, otherwise it may overwrite sibling bytes.
     */
    function insertUint64(
        bytes32 word,
        uint256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_64 << offset));
        return clearedWord | bytes32(value << offset);
    }

    // Signed

    /**
     * @dev Inserts a 22 bits signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
     * the new word.
     *
     * Assumes `value` can be represented using 22 bits.
     */
    function insertInt22(
        bytes32 word,
        int256 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_22 << offset));
        // Integer values need masking to remove the upper bits of negative values.
        return clearedWord | bytes32((uint256(value) & _MASK_22) << offset);
    }

    // Bytes

    /**
     * @dev Inserts 192 bit shifted by an offset into a 256 bit word, replacing the old value. Returns the new word.
     *
     * Assumes `value` can be represented using 192 bits.
     */
    function insertBits192(
        bytes32 word,
        bytes32 value,
        uint256 offset
    ) internal pure returns (bytes32) {
        bytes32 clearedWord = bytes32(uint256(word) & ~(_MASK_192 << offset));
        return clearedWord | bytes32((uint256(value) & _MASK_192) << offset);
    }

    // Encoding

    // Unsigned

    /**
     * @dev Encodes an unsigned integer shifted by an offset. This performs no size checks: it is up to the caller to
     * ensure that the values are bounded.
     *
     * The return value can be logically ORed with other encoded values to form a 256 bit word.
     */
    function encodeUint(uint256 value, uint256 offset) internal pure returns (bytes32) {
        return bytes32(value << offset);
    }

    // Signed

    /**
     * @dev Encodes a 22 bits signed integer shifted by an offset.
     *
     * The return value can be logically ORed with other encoded values to form a 256 bit word.
     */
    function encodeInt22(int256 value, uint256 offset) internal pure returns (bytes32) {
        // Integer values need masking to remove the upper bits of negative values.
        return bytes32((uint256(value) & _MASK_22) << offset);
    }

    /**
     * @dev Encodes a 53 bits signed integer shifted by an offset.
     *
     * The return value can be logically ORed with other encoded values to form a 256 bit word.
     */
    function encodeInt53(int256 value, uint256 offset) internal pure returns (bytes32) {
        // Integer values need masking to remove the upper bits of negative values.
        return bytes32((uint256(value) & _MASK_53) << offset);
    }

    // Decoding

    /**
     * @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
     */
    function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool) {
        return (uint256(word >> offset) & _MASK_1) == 1;
    }

    // Unsigned

    /**
     * @dev Decodes and returns a 5 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint5(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_5;
    }

    /**
     * @dev Decodes and returns a 7 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint7(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_7;
    }

    /**
     * @dev Decodes and returns a 10 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint10(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_10;
    }

    /**
     * @dev Decodes and returns a 16 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint16(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_16;
    }

    /**
     * @dev Decodes and returns a 31 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint31(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_31;
    }

    /**
     * @dev Decodes and returns a 32 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint32(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_32;
    }

    /**
     * @dev Decodes and returns a 64 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint64(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_64;
    }

    /**
     * @dev Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word.
     */
    function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) {
        return uint256(word >> offset) & _MASK_128;
    }

    // Signed

    /**
     * @dev Decodes and returns a 22 bits signed integer shifted by an offset from a 256 bit word.
     */
    function decodeInt22(bytes32 word, uint256 offset) internal pure returns (int256) {
        int256 value = int256(uint256(word >> offset) & _MASK_22);
        // In case the decoded value is greater than the max positive integer that can be represented with 22 bits,
        // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
        // representation.
        return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
    }

    /**
     * @dev Decodes and returns a 53 bits signed integer shifted by an offset from a 256 bit word.
     */
    function decodeInt53(bytes32 word, uint256 offset) internal pure returns (int256) {
        int256 value = int256(uint256(word >> offset) & _MASK_53);
        // In case the decoded value is greater than the max positive integer that can be represented with 53 bits,
        // we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
        // representation.

        return value > _MAX_INT_53 ? (value | int256(~_MASK_53)) : value;
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 1500
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  },
  "libraries": {
    "lib/v1-space/src/oracle/QueryProcessor.sol": {
      "QueryProcessor": "0x7a9a8e8414ec8d059bb57db538d156a6bd89bd27"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IVault","name":"vault","type":"address"},{"internalType":"address","name":"_adapter","type":"address"},{"internalType":"uint256","name":"_maturity","type":"uint256"},{"internalType":"address","name":"pt","type":"address"},{"internalType":"uint256","name":"_ts","type":"uint256"},{"internalType":"uint256","name":"_g1","type":"uint256"},{"internalType":"uint256","name":"_g2","type":"uint256"},{"internalType":"bool","name":"_oracleEnabled","type":"bool"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_BPT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"adapter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"startIndex","type":"uint256"},{"internalType":"uint256","name":"endIndex","type":"uint256"}],"name":"dirtyUninitializedOracleSamples","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"g1","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"g2","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"ptTwapDuration","type":"uint256"}],"name":"getFairBPTPrice","outputs":[{"internalType":"uint256","name":"fairBptPriceInTarget","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"pTPriceInTarget","type":"uint256"}],"name":"getImpliedRateFromPrice","outputs":[{"internalType":"uint256","name":"impliedRate","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getIndices","outputs":[{"internalType":"uint256","name":"_pti","type":"uint256"},{"internalType":"uint256","name":"_targeti","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLargestSafeQueryWindow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"enum IPriceOracle.Variable","name":"variable","type":"uint8"}],"name":"getLatest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"enum IPriceOracle.Variable","name":"variable","type":"uint8"},{"internalType":"uint256","name":"ago","type":"uint256"}],"internalType":"struct IPriceOracle.OracleAccumulatorQuery[]","name":"queries","type":"tuple[]"}],"name":"getPastAccumulators","outputs":[{"internalType":"int256[]","name":"results","type":"int256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPoolId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"impliedRate","type":"uint256"}],"name":"getPriceFromImpliedRate","outputs":[{"internalType":"uint256","name":"pTPriceInTarget","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getSample","outputs":[{"internalType":"int256","name":"logPairPrice","type":"int256"},{"internalType":"int256","name":"accLogPairPrice","type":"int256"},{"internalType":"int256","name":"logBptPrice","type":"int256"},{"internalType":"int256","name":"accLogBptPrice","type":"int256"},{"internalType":"int256","name":"logInvariant","type":"int256"},{"internalType":"int256","name":"accLogInvariant","type":"int256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"enum IPriceOracle.Variable","name":"variable","type":"uint8"},{"internalType":"uint256","name":"secs","type":"uint256"},{"internalType":"uint256","name":"ago","type":"uint256"}],"internalType":"struct IPriceOracle.OracleAverageQuery[]","name":"queries","type":"tuple[]"}],"name":"getTimeWeightedAverage","outputs":[{"internalType":"uint256[]","name":"results","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalSamples","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getVault","outputs":[{"internalType":"contract IVault","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maturity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"reserves","type":"uint256[]"},{"internalType":"uint256","name":"lastChangeBlock","type":"uint256"},{"internalType":"uint256","name":"protocolSwapFeePercentage","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"onExitPool","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256[]","name":"reserves","type":"uint256[]"},{"internalType":"uint256","name":"lastChangeBlock","type":"uint256"},{"internalType":"uint256","name":"protocolSwapFeePercentage","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"name":"onJoinPool","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"enum IVault.SwapKind","name":"kind","type":"uint8"},{"internalType":"contract IERC20","name":"tokenIn","type":"address"},{"internalType":"contract IERC20","name":"tokenOut","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"lastChangeBlock","type":"uint256"},{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"userData","type":"bytes"}],"internalType":"struct IPoolSwapStructs.SwapRequest","name":"request","type":"tuple"},{"internalType":"uint256","name":"reservesTokenIn","type":"uint256"},{"internalType":"uint256","name":"reservesTokenOut","type":"uint256"}],"name":"onSwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","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":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pti","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"ts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

6102a06040527f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c960e0523480156200003657600080fd5b50604051620056b9380380620056b98339810160408190526200005991620007c2565b866001600160a01b03166306fdde036040518163ffffffff1660e01b815260040160006040518083038186803b1580156200009357600080fd5b505afa158015620000a8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052620000d2919081019062000856565b876001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b1580156200010c57600080fd5b505afa15801562000121573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200014b919081019062000856565b8180604051806040016040528060018152602001603160f81b8152508484816003908051906020019062000181929190620006d7565b50805162000197906004906020840190620006d7565b50506005805460ff19166012179055508151602092830120608052805191012060a05250507f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60c052506040516309b2760f60e01b81526000906001600160a01b038a16906309b2760f906200021390600290600401620009d2565b602060405180830381600087803b1580156200022e57600080fd5b505af115801562000243573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620002699190620007a9565b90506000886001600160a01b031663d4b839926040518163ffffffff1660e01b815260040160206040518083038186803b158015620002a757600080fd5b505afa158015620002bc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620002e2919062000783565b6040805160028082526060808301845293945090916020830190803683370190505090506000826001600160a01b0316896001600160a01b0316106200032a5760016200032d565b60005b60ff169050888282815181106200034057fe5b60200260200101906001600160a01b031690816001600160a01b031681525050828282600103815181106200037157fe5b6001600160a01b03928316602091820292909201015260408051600280825260608201909252918e16916366a9c7d29187918691816020016020820280368337019050506040518463ffffffff1660e01b8152600401620003d59392919062000938565b600060405180830381600087803b158015620003f057600080fd5b505af115801562000405573d6000803e3d6000fd5b5050506001600160601b031960608e901b1661026052506101c0849052815182906000906200043057fe5b60200260200101516001600160a01b03166101e0816001600160a01b031660601b81525050816001815181106200046357fe5b60200260200101516001600160a01b0316610200816001600160a01b031660601b815250508b6001600160a01b031663d2946c2b6040518163ffffffff1660e01b815260040160206040518083038186803b158015620004c257600080fd5b505afa158015620004d7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620004fd919062000783565b6001600160a01b0316610280816001600160a01b031660601b81525050620005a960128a6001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156200055a57600080fd5b505afa1580156200056f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000595919062000915565b60ff166200065760201b62001d391760201c565b600a0a6102208181525050620005f46012846001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156200055a57600080fd5b600a0a61024052610180969096525050506101a091909152610160929092526101405260609390931b6001600160601b031916610100525061012052600b805460ff60301b19166601000000000000921515929092029190911790555062000a00565b6000620006698383111560016200066f565b50900390565b816200068057620006808162000684565b5050565b62461bcd60e51b6000908152602060045260076024526642414c23000030600a808404818106603090810160081b95839006959095019082900491820690940160101b939093010160c81b604452606490fd5b828054600181600116156101000203166002900490600052602060002090601f0160209004810192826200070f57600085556200075a565b82601f106200072a57805160ff19168380011785556200075a565b828001600101855582156200075a579182015b828111156200075a5782518255916020019190600101906200073d565b50620007689291506200076c565b5090565b5b808211156200076857600081556001016200076d565b60006020828403121562000795578081fd5b8151620007a281620009e7565b9392505050565b600060208284031215620007bb578081fd5b5051919050565b600080600080600080600080610100898b031215620007df578384fd5b8851620007ec81620009e7565b60208a0151909850620007ff81620009e7565b60408a015160608b015191985096506200081981620009e7565b809550506080890151935060a0890151925060c0890151915060e0890151801515811462000845578182fd5b809150509295985092959890939650565b6000602080838503121562000869578182fd5b82516001600160401b038082111562000880578384fd5b818501915085601f83011262000894578384fd5b815181811115620008a157fe5b604051601f8201601f1916810185018381118282101715620008bf57fe5b6040528181528382018501881015620008d6578586fd5b8592505b81831015620008f95783830185015181840186015291840191620008da565b818311156200090a57858583830101525b979650505050505050565b60006020828403121562000927578081fd5b815160ff81168114620007a2578182fd5b60006060820185835260206060818501528186518084526080860191508288019350845b81811015620009835784516001600160a01b0316835293830193918301916001016200095c565b505084810360408601528551808252908201925081860190845b81811015620009c45782516001600160a01b0316855293830193918301916001016200099d565b509298975050505050505050565b6020810160038310620009e157fe5b91905290565b6001600160a01b0381168114620009fd57600080fd5b50565b60805160a05160c05160e0516101005160601c610120516101405161016051610180516101a0516101c0516101e05160601c6102005160601c61022051610240516102605160601c6102805160601c614aa862000c1160003980610c4a5280611aa0525080610e34528061133c5250806129a05250806129c752505080610ebc525080610842528061136b525080610a6c5280612abc5250806116955280612a9652508061090d52806114685280611bc55280611cca52806124e7528061280a5280612a5f5250806109fa5280610b475280610bd25280610c065280610ef95280610f2252806112b952806114a652806114fa528061194952806119c15280611a355280611a6952806122025280612245528061228052806122c15280612399528061254b528061258552806126ef5280612725528061275852806128ae52806128ea528061292c528061296b5280612c8a5280612ccd5280612d085280612d505280612d845280612e0d5280612e605280612eab5280612edf5280612f6f5280612fa85280612ff4528061303f52508061071952806108a352806108e55280611403528061143a52806118475280611beb5280611cf1528061248252806124b952806127a552806127dc52806129fd5280612a34525080610517528061093f5280610fa352806118ad5280611c245250806116e6525080611f25525080611f67525080611f465250614aa86000f3fe608060405234801561001057600080fd5b50600436106102775760003560e01c80636f48303111610160578063a9059cbb116100d8578063d5c096c41161008c578063e86d60bf11610071578063e86d60bf146104f2578063f3f586e5146104fa578063ffd088eb1461050d57610277565b8063d5c096c4146104cc578063dd62ed3e146104df57610277565b8063b48b5b40116100bd578063b48b5b40146104a9578063bdd8a366146104b1578063d505accf146104b957610277565b8063a9059cbb14610483578063b10be7391461049657610277565b80638d928af81161012f5780639d2c110c116101145780639d2c110c1461044a578063a457c2d71461045d578063a503e6281461047057610277565b80638d928af81461043a57806395d89b411461044257610277565b80636f483031146103eb57806370a08231146103f357806374f3b009146104065780637ecebe001461042757610277565b80633331bc36116101f357806358070223116101c257806360d1507c116101a757806360d1507c1461039d5780636970a924146103c35780636b843239146103cb57610277565b806358070223146103745780635863056d1461038757610277565b80633331bc361461033c5780633644e5151461035157806338fff2d014610359578063395093511461036157610277565b806318160ddd1161024a578063204f83f91161022f578063204f83f91461030c57806323b872dd14610314578063313ce5671461032757610277565b806318160ddd146102e45780631dccd830146102ec57610277565b806303eadcfc1461027c57806306fdde031461029a5780630845d030146102af578063095ea7b3146102c4575b600080fd5b610284610515565b6040516102919190614829565b60405180910390f35b6102a2610539565b60405161029191906149a9565b6102b76105cf565b6040516102919190614906565b6102d76102d2366004614257565b6105d6565b60405161029191906148fb565b6102b76105ed565b6102ff6102fa36600461441d565b6105f3565b60405161029191906148c3565b6102b7610717565b6102d76103223660046141a2565b61073b565b61032f6107b1565b6040516102919190614a0a565b61034f61034a3660046147a0565b6107ba565b005b6102b7610831565b6102b7610840565b6102d761036f366004614257565b610864565b6102b7610382366004614788565b61089f565b61038f6109f8565b6040516102919291906149fc565b6103b06103ab366004614788565b610a22565b604051610291979695949392919061490f565b6102b7610a6a565b6103de6103d936600461434e565b610a8e565b604051610291919061483d565b6102b7610b45565b6102b761040136600461414e565b610b69565b610419610414366004614562565b610b84565b6040516102919291906148d6565b6102b761043536600461414e565b610e17565b610284610e32565b6102a2610e56565b6102b7610458366004614691565b610eb7565b6102d761046b366004614257565b611172565b6102b761047e366004614788565b6111b0565b6102d7610491366004614257565b6115ec565b6102b76104a436600461465f565b6115f9565b6102b761168e565b6102b7611693565b61034f6104c73660046141e2565b6116b7565b6104196104da366004614562565b611827565b6102b76104ed36600461416a565b611b98565b6102b7611bc3565b6102b7610508366004614788565b611be7565b6102b7611d33565b7f000000000000000000000000000000000000000000000000000000000000000081565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156105c55780601f1061059a576101008083540402835291602001916105c5565b820191906000526020600020905b8154815290600101906020018083116105a857829003601f168201915b5050505050905090565b620f424081565b60006105e3338484611d4f565b5060015b92915050565b60025490565b6060815167ffffffffffffffff8111801561060d57600080fd5b50604051908082528060200260200182016040528015610637578160200160208202803683370190505b5090506000610644611db1565b905060005b835181101561071057737a9a8e8414ec8d059bb57db538d156a6bd89bd276379eaef82600786848151811061067a57fe5b6020026020010151856040518463ffffffff1660e01b81526004016106a193929190614987565b60206040518083038186803b1580156106b957600080fd5b505af41580156106cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106f19190614679565b8382815181106106fd57fe5b6020908102919091010152600101610649565b5050919050565b7f000000000000000000000000000000000000000000000000000000000000000081565b6000806107488533611b98565b905061076c336001600160a01b03871614806107645750838210155b61019e611dbb565b610777858585611dcd565b336001600160a01b0386161480159061079257506000198114155b156107a4576107a48533858403611d4f565b60019150505b9392505050565b60055460ff1690565b6107d481831080156107cd575060148211155b6064611dbb565b60006107e96001600080600080600080611eb5565b9050825b8281101561082b5760008181526007602052604090205461080d90611f15565b6108235760008181526007602052604090208290555b6001016107ed565b50505050565b600061083b611f21565b905090565b7f000000000000000000000000000000000000000000000000000000000000000090565b3360008181526001602090815260408083206001600160a01b038716845290915281205490916105e391859061089a9086611fdf565b611d4f565b60007f000000000000000000000000000000000000000000000000000000000000000042106108d0575060006109f3565b6109f0670de0b6b3a76400006109ea610937427f0000000000000000000000000000000000000000000000000000000000000000038302610931847f0000000000000000000000000000000000000000000000000000000000000000611ff1565b90611ff1565b6109e46109d57f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663226778496040518163ffffffff1660e01b815260040160206040518083038186803b15801561099657600080fd5b505afa1580156109aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109ce9190614679565b8890612042565b670de0b6b3a764000090611ff1565b90612078565b90611d39565b90505b919050565b7f000000000000000000000000000000000000000000000000000000000000000090600182900390565b6000806000806000806000610a3c6014891061013b611dbb565b6000610a47896120c7565b9050610a52816120d9565b959f949e50929c50909a509850965090945092505050565b7f000000000000000000000000000000000000000000000000000000000000000081565b6060815167ffffffffffffffff81118015610aa857600080fd5b50604051908082528060200260200182016040528015610ad2578160200160208202803683370190505b5090506000610adf611db1565b9050610ae9614017565b60005b8451811015610b3d57848181518110610b0157fe5b60200260200101519150610b1e826000015184846020015161213c565b848281518110610b2a57fe5b6020908102919091010152600101610aec565b505050919050565b7f000000000000000000000000000000000000000000000000000000000000000081565b6001600160a01b031660009081526020819052604090205490565b60608088610bae610b93610e32565b6001600160a01b0316336001600160a01b03161460646121ee565b610bc2610bb9610840565b821460676121ee565b610bcb876121fc565b610c3f86887f000000000000000000000000000000000000000000000000000000000000000081518110610bfb57fe5b6020026020010151897f000000000000000000000000000000000000000000000000000000000000000060010381518110610c3257fe5b60200260200101516122fc565b8415610c7857610c787f0000000000000000000000000000000000000000000000000000000000000000610c73898861247c565b612645565b600084806020019051810190610c8e9190614679565b6040805160028082526060808301845293945090916020830190803683370190505090506000610cbc6105ed565b9050610cef81610ce9858d600081518110610cd357fe5b602002602001015161264f90919063ffffffff16565b90612693565b82600081518110610cfc57fe5b602002602001018181525050610d1d81610ce9858d600181518110610cd357fe5b82600181518110610d2a57fe5b602002602001018181525050610d408c846126d5565b610d7b82600081518110610d5057fe5b60200260200101518b600081518110610d6557fe5b6020026020010151611d3990919063ffffffff16565b8a600081518110610d8857fe5b602002602001018181525050610db982600181518110610da457fe5b60200260200101518b600181518110610d6557fe5b8a600181518110610dc657fe5b602002602001018181525050610ddb8a6126df565b610de4826128a1565b604080516002808252606082018352849260208301908036833701905050955095505050505b5097509795505050505050565b6001600160a01b031660009081526006602052604090205490565b7f000000000000000000000000000000000000000000000000000000000000000090565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156105c55780601f1061059a576101008083540402835291602001916105c5565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031685602001516001600160a01b031614610f20577f0000000000000000000000000000000000000000000000000000000000000000600114610f43565b7f0000000000000000000000000000000000000000000000000000000000000000155b90506000610f5082612997565b90506000610f5e8315612997565b9050610f6a86836129eb565b9550610f7685826129eb565b9450610f9f8760a0015184610f8b5786610f8d565b875b85610f985788610f9a565b875b6122fc565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f51e181a6040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610ffc57600080fd5b505af1158015611010573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110349190614679565b9050831561106c5761104e6110476105ed565b8890611fdf565b96506110656008548761204290919063ffffffff16565b9550611091565b60085461107a908890612042565b965061108e6110876105ed565b8790611fdf565b95505b6000885160018111156110a057fe5b1415611112576110b48860600151846129eb565b6060890152836110d35760608801516110cd9082612042565b60608901525b60006110e78560018b606001518b8b6129f7565b905084156110fc576110f98183611ff1565b90505b6111068184612bd8565b955050505050506107aa565b6111208860600151836129eb565b6060890152831561114057606088015161113a9082612042565b60608901525b60006111548560008b606001518b8b6129f7565b905084611168576111658183611ff1565b90505b6111068185612beb565b60008061117f3385611b98565b90508083106111995761119433856000611d4f565b6111a6565b6111a63385858403611d4f565b5060019392505050565b60408051600180825281830190925260009160609190816020015b6111d361402e565b8152602001906001900390816111cb5790505060408051606081019091529091508060008152602001848152602001610e108152508160008151811061121557fe5b60209081029190910101526040517f1dccd8300000000000000000000000000000000000000000000000000000000081526060903090631dccd8309061125f908590600401614881565b60006040518083038186803b15801561127757600080fd5b505afa15801561128b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526112b391908101906144ea565b905060007f00000000000000000000000000000000000000000000000000000000000000006001146113135761130e826000815181106112ef57fe5b6020026020010151670de0b6b3a7640000611ff190919063ffffffff16565b611329565b8160008151811061132057fe5b60200260200101515b905060006113368261089f565b905060607f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f94d46687f00000000000000000000000000000000000000000000000000000000000000006040518263ffffffff1660e01b81526004016113a69190614906565b60006040518083038186803b1580156113be57600080fd5b505afa1580156113d2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526113fa9190810190614282565b509150506000427f00000000000000000000000000000000000000000000000000000000000000001161142e57600061145c565b670de0b6b3a7640000427f000000000000000000000000000000000000000000000000000000000000000003025b9050600061149261148d7f000000000000000000000000000000000000000000000000000000000000000084612042565b612bf7565b9050600061153f6114e8836109e4600854887f0000000000000000000000000000000000000000000000000000000000000000600103815181106114d257fe5b602002602001015161204290919063ffffffff16565b611539846109e46114f76105ed565b897f00000000000000000000000000000000000000000000000000000000000000008151811061152357fe5b6020026020010151611fdf90919063ffffffff16565b90611fdf565b9050600061157d611558670de0b6b3a764000085611ff1565b6109e4611576670de0b6b3a76400006115396109d58985848f611fdf565b8590611ff1565b905060006115a96115a2611599670de0b6b3a76400008a611fdf565b60085490612042565b8390611ff1565b90506115dc6115b66105ed565b6109316115d58b6115cf6115c86105ed565b8890611d39565b90612042565b8490611fdf565b9c9b505050505050505050505050565b60006105e3338484611dcd565b6000737a9a8e8414ec8d059bb57db538d156a6bd89bd27630397bee0600784611620611db1565b6040518463ffffffff1660e01b815260040161163e9392919061493f565b60206040518083038186803b15801561165657600080fd5b505af415801561166a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109f09190614679565b601490565b7f000000000000000000000000000000000000000000000000000000000000000081565b6116c58442111560d1611dbb565b6001600160a01b0380881660008181526006602090815260408083205481517f00000000000000000000000000000000000000000000000000000000000000008185015280830195909552948b166060850152608084018a905260a0840185905260c08085018a90528151808603909101815260e0909401905282519201919091209061175182612c1d565b9050600060018288888860405160008152602001604052604051808581526020018460ff1681526020018381526020018281526020019450505050506020604051602081039080840390855afa1580156117af573d6000803e3d6000fd5b5050604051601f19015191506117f190506001600160a01b038216158015906117e957508b6001600160a01b0316826001600160a01b0316145b6101f8611dbb565b6001600160a01b038b16600090815260066020526040902060018501905561181a8b8b8b611d4f565b5050505050505050505050565b60608088611836610b93610e32565b611841610bb9610840565b61186f427f0000000000000000000000000000000000000000000000000000000000000000101560696121ee565b6060600085806020019051810190611887919061451d565b91509150611894896121fc565b61189d826121fc565b6118a56105ed565b611a2e5760007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f51e181a6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561190657600080fd5b505af115801561191a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061193e9190614679565b9050600061197582857f0000000000000000000000000000000000000000000000000000000000000000600103815181106114d257fe5b90506119856000620f4240612645565b600061199482620f4240611d39565b90506119a08d82612645565b6119ae84821015606c6121ee565b6119b785612c84565b82600881905550847f0000000000000000000000000000000000000000000000000000000000000000815181106119ea57fe5b602002602001016000815250849b50611a028c6126df565b604080516002808252606082018352879260208301908036833701905050975097505050505050610e0a565b611a95888a7f000000000000000000000000000000000000000000000000000000000000000081518110611a5e57fe5b60200260200101518b7f000000000000000000000000000000000000000000000000000000000000000060010381518110610c3257fe5b8615611ac957611ac97f0000000000000000000000000000000000000000000000000000000000000000610c738b8a61247c565b60006060611ad7848c612d46565b91509150611ae983831015606c6121ee565b611af38c83612645565b80600081518110611b0057fe5b60200260200101518b600081518110611b1557fe5b60200260200101818151019150818152505080600181518110611b3457fe5b60200260200101518b600181518110611b4957fe5b602002602001018181510191508181525050611b648b6126df565b611b6d81612c84565b6040805160028082526060820183528392602083019080368337019050509650965050505050610e0a565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b7f000000000000000000000000000000000000000000000000000000000000000081565b60007f00000000000000000000000000000000000000000000000000000000000000004210611c1f5750670de0b6b3a76400006109f3565b6109f07f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663226778496040518163ffffffff1660e01b815260040160206040518083038186803b158015611c7b57600080fd5b505afa158015611c8f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cb39190614679565b6109316109d5611d21611cee670de0b6b3a76400007f0000000000000000000000000000000000000000000000000000000000000000611ff1565b427f000000000000000000000000000000000000000000000000000000000000000003670de0b6b3a76400000290611ff1565b6109e487670de0b6b3a7640000611fdf565b615da890565b6000611d49838311156001611dbb565b50900390565b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600b5461ffff1690565b81611dc957611dc98161308e565b5050565b611de46001600160a01b0384161515610198611dbb565b611dfb6001600160a01b0383161515610199611dbb565b611e06838383612477565b6001600160a01b038316600090815260208190526040902054611e2c90826101a06130e1565b6001600160a01b038085166000908152602081905260408082209390935590841681522054611e5b9082611fdf565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b6000611ec182826130f7565b611ecc84601f6130fb565b611ed786605461310c565b611ee288606a6130fb565b611eed8a609f61310c565b611ef88c60b56130fb565b611f038e60ea61310c565b17171717171798975050505050505050565b60006109f08282613119565b60007f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000611f8e613123565b3060405160200180868152602001858152602001848152602001838152602001826001600160a01b031681526020019550505050505060405160208183030381529060405280519060200120905090565b60008282016107aa8482101583611dbb565b60006120008215156004611dbb565b8261200d575060006105e7565b670de0b6b3a7640000838102906120309085838161202757fe5b04146005611dbb565b82818161203957fe5b049150506105e7565b600082820261206684158061205f57508385838161205c57fe5b04145b6003611dbb565b670de0b6b3a764000090049392505050565b6000806120858484613127565b9050600061209f6120988361271061264f565b6001611fdf565b9050808210156120b4576000925050506105e7565b6120be8282611d39565b925050506105e7565b60009081526007602052604090205490565b60008060008060008060006120ed8861324e565b96506120f88861325b565b955061210388613268565b945061210e88613275565b935061211988613282565b92506121248861328f565b915061212f88611f15565b9050919395979092949650565b6040517f34171a85000000000000000000000000000000000000000000000000000000008152600090737a9a8e8414ec8d059bb57db538d156a6bd89bd27906334171a859061219690600790889088908890600401614961565b60206040518083038186803b1580156121ae57600080fd5b505af41580156121c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e69190614679565b949350505050565b81611dc957611dc98161329c565b612242817f00000000000000000000000000000000000000000000000000000000000000008151811061222b57fe5b602002602001015161223d6001612997565b6132f0565b817f00000000000000000000000000000000000000000000000000000000000000008151811061226e57fe5b6020026020010181815250506122be817f0000000000000000000000000000000000000000000000000000000000000000600103815181106122ac57fe5b602002602001015161223d6000612997565b817f0000000000000000000000000000000000000000000000000000000000000000600103815181106122ed57fe5b60200260200101818152505050565b600b546601000000000000900460ff16801561231757508243115b801561232a5750662386f26fc100008110155b1561247757600061235b6123496008548461204290919063ffffffff16565b6109316123546105ed565b8690611fdf565b9050670de0b6b3a764000081106123835761237e81670de0b6b3a7640000611d39565b612386565b60005b9050600061239382611be7565b905060007f0000000000000000000000000000000000000000000000000000000000000000156123c357816123d5565b6123d5670de0b6b3a764000083611ff1565b600b5490915060009061243a9063ffffffff620100008204169061ffff166123fc8561330a565b620f424088106124145761240f8861330a565b612420565b612420620f424061330a565b600b546701000000000000009004601890810b900b61334a565b600b5490915061ffff16811461247257600b805465ffffffff00001916620100004263ffffffff16021761ffff191661ffff83161790555b505050505b505050565b600080427f0000000000000000000000000000000000000000000000000000000000000000116124ad5760006124db565b670de0b6b3a7640000427f000000000000000000000000000000000000000000000000000000000000000003025b9050600061250c61148d7f000000000000000000000000000000000000000000000000000000000000000084612042565b9050600061253561252883600a5461207890919063ffffffff16565b6009546115399085612078565b90506000612574836109e46125486105ed565b8a7f00000000000000000000000000000000000000000000000000000000000000008151811061152357fe5b905060006125b1846109e46008548b7f0000000000000000000000000000000000000000000000000000000000000000600103815181106114d257fe5b905060006125bf8383611fdf565b90508381116125d757600096505050505050506105e7565b60006125f86125ee670de0b6b3a764000088611ff1565b6109e48488611ff1565b9050600061261c8261093161261582670de0b6b3a7640000611d39565b8d90612042565b905061263661262a82612bf7565b610931836115cf6105ed565b9b9a5050505050505050505050565b611dc982826133a2565b600082820261266984158061205f57508385838161205c57fe5b806126785760009150506105e7565b670de0b6b3a764000060001982015b046001019150506105e7565b60006126a28215156004611dbb565b826126af575060006105e7565b670de0b6b3a7640000838102906126c99085838161202757fe5b82600182038161268757fe5b611dc98282613437565b60006127186126ec6105ed565b837f00000000000000000000000000000000000000000000000000000000000000008151811061152357fe5b90506000612751600854847f0000000000000000000000000000000000000000000000000000000000000000600103815181106114d257fe5b90506000807f000000000000000000000000000000000000000000000000000000000000000061278557508290508161278b565b50819050825b600b546601000000000000900460ff1615612893576000427f0000000000000000000000000000000000000000000000000000000000000000116127d05760006127fe565b670de0b6b3a7640000427f000000000000000000000000000000000000000000000000000000000000000003025b9050600061282f61148d7f000000000000000000000000000000000000000000000000000000000000000084612042565b905061285061284b6128418584612078565b6115398785612078565b61330a565b600b805460189290920b78ffffffffffffffffffffffffffffffffffffffffffffffffff166701000000000000000266ffffffffffffff90921691909117905550505b600991909155600a55505050565b6128ab6001612997565b817f0000000000000000000000000000000000000000000000000000000000000000815181106128d757fe5b6020026020010151816128e657fe5b04817f00000000000000000000000000000000000000000000000000000000000000008151811061291357fe5b6020026020010181815250506129296000612997565b817f00000000000000000000000000000000000000000000000000000000000000006001038151811061295857fe5b60200260200101518161296757fe5b04817f0000000000000000000000000000000000000000000000000000000000000000600103815181106122ed57fe5b6000816129c4577f00000000000000000000000000000000000000000000000000000000000000006109f0565b507f0000000000000000000000000000000000000000000000000000000000000000919050565b60006107aa83836132f0565b600080427f000000000000000000000000000000000000000000000000000000000000000011612a28576000612a56565b670de0b6b3a7640000427f000000000000000000000000000000000000000000000000000000000000000003025b90506000612a847f000000000000000000000000000000000000000000000000000000000000000083612042565b90506000612ae261148d838b612aba577f0000000000000000000000000000000000000000000000000000000000000000612adc565b7f00000000000000000000000000000000000000000000000000000000000000005b9061264f565b90506000612af087836134ee565b90506000612afe87846134ee565b905060008a612b1657612b11888b611d39565b612b1a565b8989015b90506000612b288286612078565b90506000612b55612b41670de0b6b3a764000088611ff1565b612b4f846109ea8989611fdf565b906134ee565b9050612b6d8d1580612b665750818b115b606a6121ee565b8c15612ba957612b908e612b845781841115612b89565b818410155b606b6121ee565b612b9a8a82611d39565b98505050505050505050612bcf565b612bc58e612bba5783821115612b89565b83821015606b6121ee565b612b9a818c611d39565b95945050505050565b6000818381612be357fe5b049392505050565b60006107aa838361351a565b6000670de0b6b3a76400008210612c0f5760006109f0565b50670de0b6b3a76400000390565b6000612c27611f21565b8260405160200180807f190100000000000000000000000000000000000000000000000000000000000081525060020183815260200182815260200192505050604051602081830303815290604052805190602001209050919050565b612cca817f000000000000000000000000000000000000000000000000000000000000000081518110612cb357fe5b6020026020010151612cc56001612997565b61351a565b817f000000000000000000000000000000000000000000000000000000000000000081518110612cf657fe5b6020026020010181815250506122be817f000000000000000000000000000000000000000000000000000000000000000060010381518110612d3457fe5b6020026020010151612cc56000612997565b60006060600080847f000000000000000000000000000000000000000000000000000000000000000081518110612d7957fe5b6020026020010151857f000000000000000000000000000000000000000000000000000000000000000060010381518110612db057fe5b6020026020010151915091506060600267ffffffffffffffff81118015612dd657600080fd5b50604051908082528060200260200182016040528015612e00578160200160208202803683370190505b50905082612ea5576000877f000000000000000000000000000000000000000000000000000000000000000060010381518110612e3957fe5b602002602001015190506000612e5a6008548361204290919063ffffffff16565b905081837f000000000000000000000000000000000000000000000000000000000000000060010381518110612e8c57fe5b6020908102919091010152955090935061308792505050565b600080887f000000000000000000000000000000000000000000000000000000000000000081518110612ed457fe5b6020026020010151897f000000000000000000000000000000000000000000000000000000000000000060010381518110612f0b57fe5b6020026020010151915091506000612f216105ed565b9050600085612f3083856132f0565b81612f3757fe5b049050600087612f4784876132f0565b81612f4e57fe5b04905080821015612ff05786612f6489866132f0565b81612f6b57fe5b04867f000000000000000000000000000000000000000000000000000000000000000081518110612f9857fe5b60200260200101818152505083867f000000000000000000000000000000000000000000000000000000000000000060010381518110612fd457fe5b6020908102919091010152509750929550613087945050505050565b84867f00000000000000000000000000000000000000000000000000000000000000008151811061301d57fe5b6020026020010181815250508761303488876132f0565b8161303b57fe5b04867f00000000000000000000000000000000000000000000000000000000000000006001038151811061306b57fe5b6020908102919091010152985093965061308795505050505050565b9250929050565b62461bcd60e51b6000908152602060045260076024526642414c23000030600a808404818106603090810160081b95839006959095019082900491820690940160101b939093010160c81b604452606490fd5b60006130f08484111583611dbb565b5050900390565b1b90565b661fffffffffffff91909116901b90565b623fffff91909116901b90565b1c637fffffff1690565b4690565b60008161313d5750670de0b6b3a76400006105e7565b8261314a575060006105e7565b6131777f800000000000000000000000000000000000000000000000000000000000000084106006611dbb565b8261319d770bce5086492111aea88f4bb1ca6bcf584181ea8059f7653284106007611dbb565b826000670c7d713b49da0000831380156131be5750670f43fc2c04ee000083125b156131f55760006131ce8461354d565b9050670de0b6b3a764000080820784020583670de0b6b3a764000083050201915050613203565b816131ff84613684565b0290505b670de0b6b3a7640000900561323b680238fd42c5cf03ffff198212801590613234575068070c1cc73b00c800008213155b6008611dbb565b61324481613a24565b9695505050505050565b60006109f08260ea613ede565b60006109f08260b5613f05565b60006109f082609f613ede565b60006109f082606a613f05565b60006109f0826054613ede565b60006109f082601f613f05565b62461bcd60e51b600090815260206004526007602452673f534e5323000030600a808404818106603090810160081b95839006959095019082900491820690940160101b939093010160c81b604452606490fd5b60008282026107aa84158061205f57508385838161205c57fe5b60008061331683613f38565b9050600080821361332f57652d79883d20008203613339565b652d79883d200082015b655af3107a40009005949350505050565b6000806133668585854261335d8b6120c7565b93929190613f94565b90506104b04288900310158061337c5786613385565b61338587613ff4565b600081815260076020526040902092909255509695505050505050565b6133ae60008383612477565b6002546133bb9082611fdf565b6002556001600160a01b0382166000908152602081905260409020546133e19082611fdf565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b61344e6001600160a01b038316151561019b611dbb565b61345a82600083612477565b6001600160a01b03821660009081526020819052604090205461348090826101a16130e1565b6001600160a01b0383166000908152602081905260409020556002546134a69082614001565b6002556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b6000806134fb8484613127565b9050600061350e6120988361271061264f565b9050612bcf8282611fdf565b60006135298215156004611dbb565b82613536575060006105e7565b81600184038161354257fe5b0460010190506105e7565b670de0b6b3a7640000026000806ec097ce7bc90715b34b9f1000000000808401907fffffffffffffffffffffffffffffffffff3f68318436f8ea4cb460f0000000008501028161359957fe5b05905060006ec097ce7bc90715b34b9f100000000082800205905081806ec097ce7bc90715b34b9f100000000081840205915060038205016ec097ce7bc90715b34b9f100000000082840205915060058205016ec097ce7bc90715b34b9f100000000082840205915060078205016ec097ce7bc90715b34b9f100000000082840205915060098205016ec097ce7bc90715b34b9f1000000000828402059150600b8205016ec097ce7bc90715b34b9f1000000000828402059150600d8205016ec097ce7bc90715b34b9f1000000000828402059150600f826002919005919091010295945050505050565b6000670de0b6b3a76400008212156136c1576136b7826ec097ce7bc90715b34b9f1000000000816136b157fe5b05613684565b60000390506109f3565b60007e1600ef3172e58d2e933ec884fde10064c63b5372d805e203c0000000000000831261371257770195e54c5dd42177f53a27172fa9ec630262827000000000830592506806f05b59d3b2000000015b73011798004d755d3c8bc8e03204cf44619e000000831261374a576b1425982cf597cd205cef7380830592506803782dace9d9000000015b606492830292026e01855144814a7ff805980ff00840008312613792576e01855144814a7ff805980ff008400068056bc75e2d63100000840205925068ad78ebc5ac62000000015b6b02df0ab5a80a22c61ab5a70083126137cd576b02df0ab5a80a22c61ab5a70068056bc75e2d6310000084020592506856bc75e2d631000000015b693f1fce3da636ea5cf850831261380457693f1fce3da636ea5cf85068056bc75e2d631000008402059250682b5e3af16b18800000015b690127fa27722cc06cc5e2831261383b57690127fa27722cc06cc5e268056bc75e2d6310000084020592506815af1d78b58c400000015b68280e60114edb805d0383126138705768280e60114edb805d0368056bc75e2d631000008402059250680ad78ebc5ac6200000015b680ebc5fb41746121110831261389b57680ebc5fb4174612111068056bc75e2d631000009384020592015b6808f00f760a4b2db55d83126138d0576808f00f760a4b2db55d68056bc75e2d6310000084020592506802b5e3af16b1880000015b6806f5f17757889379378312613905576806f5f177578893793768056bc75e2d63100000840205925068015af1d78b58c40000015b6806248f33704b2866038312613939576806248f33704b28660368056bc75e2d63100000840205925067ad78ebc5ac620000015b6805c548670b9510e7ac831261396d576805c548670b9510e7ac68056bc75e2d6310000084020592506756bc75e2d6310000015b600068056bc75e2d63100000840168056bc75e2d63100000808603028161399057fe5b059050600068056bc75e2d63100000828002059050818068056bc75e2d63100000818402059150600382050168056bc75e2d63100000828402059150600582050168056bc75e2d63100000828402059150600782050168056bc75e2d63100000828402059150600982050168056bc75e2d63100000828402059150600b820501600202606485820105979650505050505050565b6000613a53680238fd42c5cf03ffff198312158015613a4c575068070c1cc73b00c800008313155b6009611dbb565b6000821215613a8757613a6882600003613a24565b6ec097ce7bc90715b34b9f100000000081613a7f57fe5b0590506109f3565b60006806f05b59d3b20000008312613add57507ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e00000090910190770195e54c5dd42177f53a27172fa9ec630262827000000000613b29565b6803782dace9d90000008312613b2557507ffffffffffffffffffffffffffffffffffffffffffffffffc87d2531627000000909101906b1425982cf597cd205cef7380613b29565b5060015b6064929092029168056bc75e2d6310000068ad78ebc5ac620000008412613b8f577fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e0000009093019268056bc75e2d631000006e01855144814a7ff805980ff008400082020590505b6856bc75e2d6310000008412613be1577fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf0000009093019268056bc75e2d631000006b02df0ab5a80a22c61ab5a70082020590505b682b5e3af16b188000008412613c31577fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e78000009093019268056bc75e2d63100000693f1fce3da636ea5cf85082020590505b6815af1d78b58c4000008412613c81577fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000009093019268056bc75e2d63100000690127fa27722cc06cc5e282020590505b680ad78ebc5ac62000008412613cd0577ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000009093019268056bc75e2d6310000068280e60114edb805d0382020590505b68056bc75e2d631000008412613d1f577ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000009093019268056bc75e2d63100000680ebc5fb4174612111082020590505b6802b5e3af16b18800008412613d6e577ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800009093019268056bc75e2d631000006808f00f760a4b2db55d82020590505b68015af1d78b58c400008412613dbd577ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00009093019268056bc75e2d631000006806f5f177578893793782020590505b68056bc75e2d631000008481019085906002908280020505918201919050600368056bc75e2d631000008783020505918201919050600468056bc75e2d631000008783020505918201919050600568056bc75e2d631000008783020505918201919050600668056bc75e2d631000008783020505918201919050600768056bc75e2d631000008783020505918201919050600868056bc75e2d631000008783020505918201919050600968056bc75e2d631000008783020505918201919050600a68056bc75e2d631000008783020505918201919050600b68056bc75e2d631000008783020505918201919050600c68056bc75e2d631000008783020505918201919050606468056bc75e2d63100000848402058502059695505050505050565b600082821c623fffff16621fffff8113613ef857806121e6565b623fffff19179392505050565b600082821c661fffffffffffff16660fffffffffffff8113613f2757806121e6565b661fffffffffffff19179392505050565b6000613f48600083136064611dbb565b670c7d713b49da000082138015613f665750670f43fc2c04ee000082125b15613f8457670de0b6b3a7640000613f7d8361354d565b81613a7f57fe5b613f8d82613684565b90506109f3565b600080613fa087611f15565b830390506000818702613fb28961325b565b0190506000828702613fc38a613275565b0190506000838702613fd48b61328f565b019050613fe689848a858b868c611eb5565b9a9950505050505050505050565b60006109f082600161400f565b60006107aa838360016130e1565b601491010690565b604080518082019091526000808252602082015290565b6040805160608101909152806000815260200160008152602001600081525090565b80356109f381614a5a565b600082601f83011261406b578081fd5b815161407e61407982614a3c565b614a18565b81815291506020808301908481018184028601820187101561409f57600080fd5b60005b848110156140be578151845292820192908201906001016140a2565b505050505092915050565b600082601f8301126140d9578081fd5b813567ffffffffffffffff8111156140ed57fe5b614100601f8201601f1916602001614a18565b915080825283602082850101111561411757600080fd5b8060208401602084013760009082016020015292915050565b8035600281106109f357600080fd5b8035600381106109f357600080fd5b60006020828403121561415f578081fd5b81356107aa81614a5a565b6000806040838503121561417c578081fd5b823561418781614a5a565b9150602083013561419781614a5a565b809150509250929050565b6000806000606084860312156141b6578081fd5b83356141c181614a5a565b925060208401356141d181614a5a565b929592945050506040919091013590565b600080600080600080600060e0888a0312156141fc578485fd5b873561420781614a5a565b9650602088013561421781614a5a565b95506040880135945060608801359350608088013560ff8116811461423a578384fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614269578182fd5b823561427481614a5a565b946020939093013593505050565b600080600060608486031215614296578081fd5b835167ffffffffffffffff808211156142ad578283fd5b818601915086601f8301126142c0578283fd5b81516142ce61407982614a3c565b80828252602080830192508086018b8283870289010111156142ee578788fd5b8796505b8487101561431957805161430581614a5a565b8452600196909601959281019281016142f2565b508901519097509350505080821115614330578283fd5b5061433d8682870161405b565b925050604084015190509250925092565b60006020808385031215614360578182fd5b823567ffffffffffffffff80821115614377578384fd5b818501915085601f83011261438a578384fd5b813561439861407982614a3c565b818152848101908486016040808502870188018b10156143b6578889fd5b8896505b8487101561440e5780828c0312156143d0578889fd5b805181810181811088821117156143e357fe5b82526143ee8361413f565b8152828901358982015284526001969096019592870192908101906143ba565b50909998505050505050505050565b6000602080838503121561442f578182fd5b823567ffffffffffffffff80821115614446578384fd5b818501915085601f830112614459578384fd5b813561446761407982614a3c565b818152848101908486016060808502870188018b1015614485578889fd5b8896505b8487101561440e5780828c03121561449f578889fd5b6040805182810181811089821117156144b457fe5b82526144bf8461413f565b8152838a01358a82015281840135918101919091528452600196909601959287019290810190614489565b6000602082840312156144fb578081fd5b815167ffffffffffffffff811115614511578182fd5b6121e68482850161405b565b6000806040838503121561452f578182fd5b825167ffffffffffffffff811115614545578283fd5b6145518582860161405b565b925050602083015190509250929050565b600080600080600080600060e0888a03121561457c578081fd5b8735965060208089013561458f81614a5a565b9650604089013561459f81614a5a565b9550606089013567ffffffffffffffff808211156145bb578384fd5b818b0191508b601f8301126145ce578384fd5b81356145dc61407982614a3c565b8082825285820191508585018f8788860288010111156145fa578788fd5b8795505b8386101561461c5780358352600195909501949186019186016145fe565b509850505060808b0135955060a08b0135945060c08b0135925080831115614642578384fd5b50506146508a828b016140c9565b91505092959891949750929550565b600060208284031215614670578081fd5b6107aa8261413f565b60006020828403121561468a578081fd5b5051919050565b6000806000606084860312156146a5578081fd5b833567ffffffffffffffff808211156146bc578283fd5b81860191506101208083890312156146d2578384fd5b6146db81614a18565b90506146e683614130565b81526146f460208401614050565b602082015261470560408401614050565b6040820152606083013560608201526080830135608082015260a083013560a082015261473460c08401614050565b60c082015261474560e08401614050565b60e0820152610100808401358381111561475d578586fd5b6147698a8287016140c9565b9183019190915250976020870135975060409096013595945050505050565b600060208284031215614799578081fd5b5035919050565b600080604083850312156147b2578182fd5b50508035926020909101359150565b6000815180845260208085019450808401835b838110156147f0578151875295820195908201906001016147d4565b509495945050505050565b6003811061480557fe5b9052565b6148148282516147fb565b60208181015190830152604090810151910152565b6001600160a01b0391909116815260200190565b6020808252825182820181905260009190848201906040850190845b8181101561487557835183529284019291840191600101614859565b50909695505050505050565b6020808252825182820181905260009190848201906040850190845b81811015614875576148b0838551614809565b928401926060929092019160010161489d565b6000602082526107aa60208301846147c1565b6000604082526148e960408301856147c1565b8281036020840152612bcf81856147c1565b901515815260200190565b90815260200190565b968752602087019590955260408601939093526060850191909152608084015260a083015260c082015260e00190565b8381526060810161495360208301856147fb565b826040830152949350505050565b8481526080810161497560208301866147fb565b60408201939093526060015292915050565b83815260a0810161499b6020830185614809565b826080830152949350505050565b6000602080835283518082850152825b818110156149d5578581018301518582016040015282016149b9565b818111156149e65783604083870101525b50601f01601f1916929092016040019392505050565b918252602082015260400190565b60ff91909116815260200190565b60405181810167ffffffffffffffff81118282101715614a3457fe5b604052919050565b600067ffffffffffffffff821115614a5057fe5b5060209081020190565b6001600160a01b0381168114614a6f57600080fd5b5056fea2646970667358221220518e3e6ced12cef564687643b88bb8d971ee7b1e2a8311a54b6922602a5e3ab264736f6c63430007050033000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000e917edbbd4abcb9d995ce2126e93a02ca144f3b400000000000000000000000000000000000000000000000000000000626dcd8000000000000000000000000085594a73bc9dcdda3198fd5675bee1beee294db7000000000000000000000000000000000000000000000000000000009d648d0e0000000000000000000000000000000000000000000000000d2f13f7789f00000000000000000000000000000000000000000000000000000e9bb2d80e8435e50000000000000000000000000000000000000000000000000000000000000001

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106102775760003560e01c80636f48303111610160578063a9059cbb116100d8578063d5c096c41161008c578063e86d60bf11610071578063e86d60bf146104f2578063f3f586e5146104fa578063ffd088eb1461050d57610277565b8063d5c096c4146104cc578063dd62ed3e146104df57610277565b8063b48b5b40116100bd578063b48b5b40146104a9578063bdd8a366146104b1578063d505accf146104b957610277565b8063a9059cbb14610483578063b10be7391461049657610277565b80638d928af81161012f5780639d2c110c116101145780639d2c110c1461044a578063a457c2d71461045d578063a503e6281461047057610277565b80638d928af81461043a57806395d89b411461044257610277565b80636f483031146103eb57806370a08231146103f357806374f3b009146104065780637ecebe001461042757610277565b80633331bc36116101f357806358070223116101c257806360d1507c116101a757806360d1507c1461039d5780636970a924146103c35780636b843239146103cb57610277565b806358070223146103745780635863056d1461038757610277565b80633331bc361461033c5780633644e5151461035157806338fff2d014610359578063395093511461036157610277565b806318160ddd1161024a578063204f83f91161022f578063204f83f91461030c57806323b872dd14610314578063313ce5671461032757610277565b806318160ddd146102e45780631dccd830146102ec57610277565b806303eadcfc1461027c57806306fdde031461029a5780630845d030146102af578063095ea7b3146102c4575b600080fd5b610284610515565b6040516102919190614829565b60405180910390f35b6102a2610539565b60405161029191906149a9565b6102b76105cf565b6040516102919190614906565b6102d76102d2366004614257565b6105d6565b60405161029191906148fb565b6102b76105ed565b6102ff6102fa36600461441d565b6105f3565b60405161029191906148c3565b6102b7610717565b6102d76103223660046141a2565b61073b565b61032f6107b1565b6040516102919190614a0a565b61034f61034a3660046147a0565b6107ba565b005b6102b7610831565b6102b7610840565b6102d761036f366004614257565b610864565b6102b7610382366004614788565b61089f565b61038f6109f8565b6040516102919291906149fc565b6103b06103ab366004614788565b610a22565b604051610291979695949392919061490f565b6102b7610a6a565b6103de6103d936600461434e565b610a8e565b604051610291919061483d565b6102b7610b45565b6102b761040136600461414e565b610b69565b610419610414366004614562565b610b84565b6040516102919291906148d6565b6102b761043536600461414e565b610e17565b610284610e32565b6102a2610e56565b6102b7610458366004614691565b610eb7565b6102d761046b366004614257565b611172565b6102b761047e366004614788565b6111b0565b6102d7610491366004614257565b6115ec565b6102b76104a436600461465f565b6115f9565b6102b761168e565b6102b7611693565b61034f6104c73660046141e2565b6116b7565b6104196104da366004614562565b611827565b6102b76104ed36600461416a565b611b98565b6102b7611bc3565b6102b7610508366004614788565b611be7565b6102b7611d33565b7f000000000000000000000000e917edbbd4abcb9d995ce2126e93a02ca144f3b481565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156105c55780601f1061059a576101008083540402835291602001916105c5565b820191906000526020600020905b8154815290600101906020018083116105a857829003601f168201915b5050505050905090565b620f424081565b60006105e3338484611d4f565b5060015b92915050565b60025490565b6060815167ffffffffffffffff8111801561060d57600080fd5b50604051908082528060200260200182016040528015610637578160200160208202803683370190505b5090506000610644611db1565b905060005b835181101561071057737a9a8e8414ec8d059bb57db538d156a6bd89bd276379eaef82600786848151811061067a57fe5b6020026020010151856040518463ffffffff1660e01b81526004016106a193929190614987565b60206040518083038186803b1580156106b957600080fd5b505af41580156106cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106f19190614679565b8382815181106106fd57fe5b6020908102919091010152600101610649565b5050919050565b7f00000000000000000000000000000000000000000000000000000000626dcd8081565b6000806107488533611b98565b905061076c336001600160a01b03871614806107645750838210155b61019e611dbb565b610777858585611dcd565b336001600160a01b0386161480159061079257506000198114155b156107a4576107a48533858403611d4f565b60019150505b9392505050565b60055460ff1690565b6107d481831080156107cd575060148211155b6064611dbb565b60006107e96001600080600080600080611eb5565b9050825b8281101561082b5760008181526007602052604090205461080d90611f15565b6108235760008181526007602052604090208290555b6001016107ed565b50505050565b600061083b611f21565b905090565b7f3f9fee026fcebb40719a69416c72b714d89a17d900020000000000000000017c90565b3360008181526001602090815260408083206001600160a01b038716845290915281205490916105e391859061089a9086611fdf565b611d4f565b60007f00000000000000000000000000000000000000000000000000000000626dcd8042106108d0575060006109f3565b6109f0670de0b6b3a76400006109ea610937427f00000000000000000000000000000000000000000000000000000000626dcd80038302610931847f000000000000000000000000000000000000000000000000000000009d648d0e611ff1565b90611ff1565b6109e46109d57f000000000000000000000000e917edbbd4abcb9d995ce2126e93a02ca144f3b46001600160a01b031663226778496040518163ffffffff1660e01b815260040160206040518083038186803b15801561099657600080fd5b505afa1580156109aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109ce9190614679565b8890612042565b670de0b6b3a764000090611ff1565b90612078565b90611d39565b90505b919050565b7f000000000000000000000000000000000000000000000000000000000000000190600182900390565b6000806000806000806000610a3c6014891061013b611dbb565b6000610a47896120c7565b9050610a52816120d9565b959f949e50929c50909a509850965090945092505050565b7f0000000000000000000000000000000000000000000000000e9bb2d80e8435e581565b6060815167ffffffffffffffff81118015610aa857600080fd5b50604051908082528060200260200182016040528015610ad2578160200160208202803683370190505b5090506000610adf611db1565b9050610ae9614017565b60005b8451811015610b3d57848181518110610b0157fe5b60200260200101519150610b1e826000015184846020015161213c565b848281518110610b2a57fe5b6020908102919091010152600101610aec565b505050919050565b7f000000000000000000000000000000000000000000000000000000000000000181565b6001600160a01b031660009081526020819052604090205490565b60608088610bae610b93610e32565b6001600160a01b0316336001600160a01b03161460646121ee565b610bc2610bb9610840565b821460676121ee565b610bcb876121fc565b610c3f86887f000000000000000000000000000000000000000000000000000000000000000181518110610bfb57fe5b6020026020010151897f000000000000000000000000000000000000000000000000000000000000000160010381518110610c3257fe5b60200260200101516122fc565b8415610c7857610c787f000000000000000000000000ce88686553686da562ce7cea497ce749da109f9f610c73898861247c565b612645565b600084806020019051810190610c8e9190614679565b6040805160028082526060808301845293945090916020830190803683370190505090506000610cbc6105ed565b9050610cef81610ce9858d600081518110610cd357fe5b602002602001015161264f90919063ffffffff16565b90612693565b82600081518110610cfc57fe5b602002602001018181525050610d1d81610ce9858d600181518110610cd357fe5b82600181518110610d2a57fe5b602002602001018181525050610d408c846126d5565b610d7b82600081518110610d5057fe5b60200260200101518b600081518110610d6557fe5b6020026020010151611d3990919063ffffffff16565b8a600081518110610d8857fe5b602002602001018181525050610db982600181518110610da457fe5b60200260200101518b600181518110610d6557fe5b8a600181518110610dc657fe5b602002602001018181525050610ddb8a6126df565b610de4826128a1565b604080516002808252606082018352849260208301908036833701905050955095505050505b5097509795505050505050565b6001600160a01b031660009081526006602052604090205490565b7f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c890565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156105c55780601f1061059a576101008083540402835291602001916105c5565b6000807f0000000000000000000000007f39c581f595b53c5cb19bd0b3f8da6c935e2ca06001600160a01b031685602001516001600160a01b031614610f20577f0000000000000000000000000000000000000000000000000000000000000001600114610f43565b7f0000000000000000000000000000000000000000000000000000000000000001155b90506000610f5082612997565b90506000610f5e8315612997565b9050610f6a86836129eb565b9550610f7685826129eb565b9450610f9f8760a0015184610f8b5786610f8d565b875b85610f985788610f9a565b875b6122fc565b60007f000000000000000000000000e917edbbd4abcb9d995ce2126e93a02ca144f3b46001600160a01b031663f51e181a6040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610ffc57600080fd5b505af1158015611010573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110349190614679565b9050831561106c5761104e6110476105ed565b8890611fdf565b96506110656008548761204290919063ffffffff16565b9550611091565b60085461107a908890612042565b965061108e6110876105ed565b8790611fdf565b95505b6000885160018111156110a057fe5b1415611112576110b48860600151846129eb565b6060890152836110d35760608801516110cd9082612042565b60608901525b60006110e78560018b606001518b8b6129f7565b905084156110fc576110f98183611ff1565b90505b6111068184612bd8565b955050505050506107aa565b6111208860600151836129eb565b6060890152831561114057606088015161113a9082612042565b60608901525b60006111548560008b606001518b8b6129f7565b905084611168576111658183611ff1565b90505b6111068185612beb565b60008061117f3385611b98565b90508083106111995761119433856000611d4f565b6111a6565b6111a63385858403611d4f565b5060019392505050565b60408051600180825281830190925260009160609190816020015b6111d361402e565b8152602001906001900390816111cb5790505060408051606081019091529091508060008152602001848152602001610e108152508160008151811061121557fe5b60209081029190910101526040517f1dccd8300000000000000000000000000000000000000000000000000000000081526060903090631dccd8309061125f908590600401614881565b60006040518083038186803b15801561127757600080fd5b505afa15801561128b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526112b391908101906144ea565b905060007f00000000000000000000000000000000000000000000000000000000000000016001146113135761130e826000815181106112ef57fe5b6020026020010151670de0b6b3a7640000611ff190919063ffffffff16565b611329565b8160008151811061132057fe5b60200260200101515b905060006113368261089f565b905060607f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b031663f94d46687f3f9fee026fcebb40719a69416c72b714d89a17d900020000000000000000017c6040518263ffffffff1660e01b81526004016113a69190614906565b60006040518083038186803b1580156113be57600080fd5b505afa1580156113d2573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526113fa9190810190614282565b509150506000427f00000000000000000000000000000000000000000000000000000000626dcd801161142e57600061145c565b670de0b6b3a7640000427f00000000000000000000000000000000000000000000000000000000626dcd8003025b9050600061149261148d7f000000000000000000000000000000000000000000000000000000009d648d0e84612042565b612bf7565b9050600061153f6114e8836109e4600854887f0000000000000000000000000000000000000000000000000000000000000001600103815181106114d257fe5b602002602001015161204290919063ffffffff16565b611539846109e46114f76105ed565b897f00000000000000000000000000000000000000000000000000000000000000018151811061152357fe5b6020026020010151611fdf90919063ffffffff16565b90611fdf565b9050600061157d611558670de0b6b3a764000085611ff1565b6109e4611576670de0b6b3a76400006115396109d58985848f611fdf565b8590611ff1565b905060006115a96115a2611599670de0b6b3a76400008a611fdf565b60085490612042565b8390611ff1565b90506115dc6115b66105ed565b6109316115d58b6115cf6115c86105ed565b8890611d39565b90612042565b8490611fdf565b9c9b505050505050505050505050565b60006105e3338484611dcd565b6000737a9a8e8414ec8d059bb57db538d156a6bd89bd27630397bee0600784611620611db1565b6040518463ffffffff1660e01b815260040161163e9392919061493f565b60206040518083038186803b15801561165657600080fd5b505af415801561166a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109f09190614679565b601490565b7f0000000000000000000000000000000000000000000000000d2f13f7789f000081565b6116c58442111560d1611dbb565b6001600160a01b0380881660008181526006602090815260408083205481517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98185015280830195909552948b166060850152608084018a905260a0840185905260c08085018a90528151808603909101815260e0909401905282519201919091209061175182612c1d565b9050600060018288888860405160008152602001604052604051808581526020018460ff1681526020018381526020018281526020019450505050506020604051602081039080840390855afa1580156117af573d6000803e3d6000fd5b5050604051601f19015191506117f190506001600160a01b038216158015906117e957508b6001600160a01b0316826001600160a01b0316145b6101f8611dbb565b6001600160a01b038b16600090815260066020526040902060018501905561181a8b8b8b611d4f565b5050505050505050505050565b60608088611836610b93610e32565b611841610bb9610840565b61186f427f00000000000000000000000000000000000000000000000000000000626dcd80101560696121ee565b6060600085806020019051810190611887919061451d565b91509150611894896121fc565b61189d826121fc565b6118a56105ed565b611a2e5760007f000000000000000000000000e917edbbd4abcb9d995ce2126e93a02ca144f3b46001600160a01b031663f51e181a6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561190657600080fd5b505af115801561191a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061193e9190614679565b9050600061197582857f0000000000000000000000000000000000000000000000000000000000000001600103815181106114d257fe5b90506119856000620f4240612645565b600061199482620f4240611d39565b90506119a08d82612645565b6119ae84821015606c6121ee565b6119b785612c84565b82600881905550847f0000000000000000000000000000000000000000000000000000000000000001815181106119ea57fe5b602002602001016000815250849b50611a028c6126df565b604080516002808252606082018352879260208301908036833701905050975097505050505050610e0a565b611a95888a7f000000000000000000000000000000000000000000000000000000000000000181518110611a5e57fe5b60200260200101518b7f000000000000000000000000000000000000000000000000000000000000000160010381518110610c3257fe5b8615611ac957611ac97f000000000000000000000000ce88686553686da562ce7cea497ce749da109f9f610c738b8a61247c565b60006060611ad7848c612d46565b91509150611ae983831015606c6121ee565b611af38c83612645565b80600081518110611b0057fe5b60200260200101518b600081518110611b1557fe5b60200260200101818151019150818152505080600181518110611b3457fe5b60200260200101518b600181518110611b4957fe5b602002602001018181510191508181525050611b648b6126df565b611b6d81612c84565b6040805160028082526060820183528392602083019080368337019050509650965050505050610e0a565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b7f000000000000000000000000000000000000000000000000000000009d648d0e81565b60007f00000000000000000000000000000000000000000000000000000000626dcd804210611c1f5750670de0b6b3a76400006109f3565b6109f07f000000000000000000000000e917edbbd4abcb9d995ce2126e93a02ca144f3b46001600160a01b031663226778496040518163ffffffff1660e01b815260040160206040518083038186803b158015611c7b57600080fd5b505afa158015611c8f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cb39190614679565b6109316109d5611d21611cee670de0b6b3a76400007f000000000000000000000000000000000000000000000000000000009d648d0e611ff1565b427f00000000000000000000000000000000000000000000000000000000626dcd8003670de0b6b3a76400000290611ff1565b6109e487670de0b6b3a7640000611fdf565b615da890565b6000611d49838311156001611dbb565b50900390565b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600b5461ffff1690565b81611dc957611dc98161308e565b5050565b611de46001600160a01b0384161515610198611dbb565b611dfb6001600160a01b0383161515610199611dbb565b611e06838383612477565b6001600160a01b038316600090815260208190526040902054611e2c90826101a06130e1565b6001600160a01b038085166000908152602081905260408082209390935590841681522054611e5b9082611fdf565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b6000611ec182826130f7565b611ecc84601f6130fb565b611ed786605461310c565b611ee288606a6130fb565b611eed8a609f61310c565b611ef88c60b56130fb565b611f038e60ea61310c565b17171717171798975050505050505050565b60006109f08282613119565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f7f8d38ade1c111dad8327b776bdacd4e268bba4620d0e2ca0606ec6bac7a3e1a5c7fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6611f8e613123565b3060405160200180868152602001858152602001848152602001838152602001826001600160a01b031681526020019550505050505060405160208183030381529060405280519060200120905090565b60008282016107aa8482101583611dbb565b60006120008215156004611dbb565b8261200d575060006105e7565b670de0b6b3a7640000838102906120309085838161202757fe5b04146005611dbb565b82818161203957fe5b049150506105e7565b600082820261206684158061205f57508385838161205c57fe5b04145b6003611dbb565b670de0b6b3a764000090049392505050565b6000806120858484613127565b9050600061209f6120988361271061264f565b6001611fdf565b9050808210156120b4576000925050506105e7565b6120be8282611d39565b925050506105e7565b60009081526007602052604090205490565b60008060008060008060006120ed8861324e565b96506120f88861325b565b955061210388613268565b945061210e88613275565b935061211988613282565b92506121248861328f565b915061212f88611f15565b9050919395979092949650565b6040517f34171a85000000000000000000000000000000000000000000000000000000008152600090737a9a8e8414ec8d059bb57db538d156a6bd89bd27906334171a859061219690600790889088908890600401614961565b60206040518083038186803b1580156121ae57600080fd5b505af41580156121c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121e69190614679565b949350505050565b81611dc957611dc98161329c565b612242817f00000000000000000000000000000000000000000000000000000000000000018151811061222b57fe5b602002602001015161223d6001612997565b6132f0565b817f00000000000000000000000000000000000000000000000000000000000000018151811061226e57fe5b6020026020010181815250506122be817f0000000000000000000000000000000000000000000000000000000000000001600103815181106122ac57fe5b602002602001015161223d6000612997565b817f0000000000000000000000000000000000000000000000000000000000000001600103815181106122ed57fe5b60200260200101818152505050565b600b546601000000000000900460ff16801561231757508243115b801561232a5750662386f26fc100008110155b1561247757600061235b6123496008548461204290919063ffffffff16565b6109316123546105ed565b8690611fdf565b9050670de0b6b3a764000081106123835761237e81670de0b6b3a7640000611d39565b612386565b60005b9050600061239382611be7565b905060007f0000000000000000000000000000000000000000000000000000000000000001156123c357816123d5565b6123d5670de0b6b3a764000083611ff1565b600b5490915060009061243a9063ffffffff620100008204169061ffff166123fc8561330a565b620f424088106124145761240f8861330a565b612420565b612420620f424061330a565b600b546701000000000000009004601890810b900b61334a565b600b5490915061ffff16811461247257600b805465ffffffff00001916620100004263ffffffff16021761ffff191661ffff83161790555b505050505b505050565b600080427f00000000000000000000000000000000000000000000000000000000626dcd80116124ad5760006124db565b670de0b6b3a7640000427f00000000000000000000000000000000000000000000000000000000626dcd8003025b9050600061250c61148d7f000000000000000000000000000000000000000000000000000000009d648d0e84612042565b9050600061253561252883600a5461207890919063ffffffff16565b6009546115399085612078565b90506000612574836109e46125486105ed565b8a7f00000000000000000000000000000000000000000000000000000000000000018151811061152357fe5b905060006125b1846109e46008548b7f0000000000000000000000000000000000000000000000000000000000000001600103815181106114d257fe5b905060006125bf8383611fdf565b90508381116125d757600096505050505050506105e7565b60006125f86125ee670de0b6b3a764000088611ff1565b6109e48488611ff1565b9050600061261c8261093161261582670de0b6b3a7640000611d39565b8d90612042565b905061263661262a82612bf7565b610931836115cf6105ed565b9b9a5050505050505050505050565b611dc982826133a2565b600082820261266984158061205f57508385838161205c57fe5b806126785760009150506105e7565b670de0b6b3a764000060001982015b046001019150506105e7565b60006126a28215156004611dbb565b826126af575060006105e7565b670de0b6b3a7640000838102906126c99085838161202757fe5b82600182038161268757fe5b611dc98282613437565b60006127186126ec6105ed565b837f00000000000000000000000000000000000000000000000000000000000000018151811061152357fe5b90506000612751600854847f0000000000000000000000000000000000000000000000000000000000000001600103815181106114d257fe5b90506000807f000000000000000000000000000000000000000000000000000000000000000161278557508290508161278b565b50819050825b600b546601000000000000900460ff1615612893576000427f00000000000000000000000000000000000000000000000000000000626dcd80116127d05760006127fe565b670de0b6b3a7640000427f00000000000000000000000000000000000000000000000000000000626dcd8003025b9050600061282f61148d7f000000000000000000000000000000000000000000000000000000009d648d0e84612042565b905061285061284b6128418584612078565b6115398785612078565b61330a565b600b805460189290920b78ffffffffffffffffffffffffffffffffffffffffffffffffff166701000000000000000266ffffffffffffff90921691909117905550505b600991909155600a55505050565b6128ab6001612997565b817f0000000000000000000000000000000000000000000000000000000000000001815181106128d757fe5b6020026020010151816128e657fe5b04817f00000000000000000000000000000000000000000000000000000000000000018151811061291357fe5b6020026020010181815250506129296000612997565b817f00000000000000000000000000000000000000000000000000000000000000016001038151811061295857fe5b60200260200101518161296757fe5b04817f0000000000000000000000000000000000000000000000000000000000000001600103815181106122ed57fe5b6000816129c4577f00000000000000000000000000000000000000000000000000000000000000016109f0565b507f0000000000000000000000000000000000000000000000000000000000000001919050565b60006107aa83836132f0565b600080427f00000000000000000000000000000000000000000000000000000000626dcd8011612a28576000612a56565b670de0b6b3a7640000427f00000000000000000000000000000000000000000000000000000000626dcd8003025b90506000612a847f000000000000000000000000000000000000000000000000000000009d648d0e83612042565b90506000612ae261148d838b612aba577f0000000000000000000000000000000000000000000000000d2f13f7789f0000612adc565b7f0000000000000000000000000000000000000000000000000e9bb2d80e8435e55b9061264f565b90506000612af087836134ee565b90506000612afe87846134ee565b905060008a612b1657612b11888b611d39565b612b1a565b8989015b90506000612b288286612078565b90506000612b55612b41670de0b6b3a764000088611ff1565b612b4f846109ea8989611fdf565b906134ee565b9050612b6d8d1580612b665750818b115b606a6121ee565b8c15612ba957612b908e612b845781841115612b89565b818410155b606b6121ee565b612b9a8a82611d39565b98505050505050505050612bcf565b612bc58e612bba5783821115612b89565b83821015606b6121ee565b612b9a818c611d39565b95945050505050565b6000818381612be357fe5b049392505050565b60006107aa838361351a565b6000670de0b6b3a76400008210612c0f5760006109f0565b50670de0b6b3a76400000390565b6000612c27611f21565b8260405160200180807f190100000000000000000000000000000000000000000000000000000000000081525060020183815260200182815260200192505050604051602081830303815290604052805190602001209050919050565b612cca817f000000000000000000000000000000000000000000000000000000000000000181518110612cb357fe5b6020026020010151612cc56001612997565b61351a565b817f000000000000000000000000000000000000000000000000000000000000000181518110612cf657fe5b6020026020010181815250506122be817f000000000000000000000000000000000000000000000000000000000000000160010381518110612d3457fe5b6020026020010151612cc56000612997565b60006060600080847f000000000000000000000000000000000000000000000000000000000000000181518110612d7957fe5b6020026020010151857f000000000000000000000000000000000000000000000000000000000000000160010381518110612db057fe5b6020026020010151915091506060600267ffffffffffffffff81118015612dd657600080fd5b50604051908082528060200260200182016040528015612e00578160200160208202803683370190505b50905082612ea5576000877f000000000000000000000000000000000000000000000000000000000000000160010381518110612e3957fe5b602002602001015190506000612e5a6008548361204290919063ffffffff16565b905081837f000000000000000000000000000000000000000000000000000000000000000160010381518110612e8c57fe5b6020908102919091010152955090935061308792505050565b600080887f000000000000000000000000000000000000000000000000000000000000000181518110612ed457fe5b6020026020010151897f000000000000000000000000000000000000000000000000000000000000000160010381518110612f0b57fe5b6020026020010151915091506000612f216105ed565b9050600085612f3083856132f0565b81612f3757fe5b049050600087612f4784876132f0565b81612f4e57fe5b04905080821015612ff05786612f6489866132f0565b81612f6b57fe5b04867f000000000000000000000000000000000000000000000000000000000000000181518110612f9857fe5b60200260200101818152505083867f000000000000000000000000000000000000000000000000000000000000000160010381518110612fd457fe5b6020908102919091010152509750929550613087945050505050565b84867f00000000000000000000000000000000000000000000000000000000000000018151811061301d57fe5b6020026020010181815250508761303488876132f0565b8161303b57fe5b04867f00000000000000000000000000000000000000000000000000000000000000016001038151811061306b57fe5b6020908102919091010152985093965061308795505050505050565b9250929050565b62461bcd60e51b6000908152602060045260076024526642414c23000030600a808404818106603090810160081b95839006959095019082900491820690940160101b939093010160c81b604452606490fd5b60006130f08484111583611dbb565b5050900390565b1b90565b661fffffffffffff91909116901b90565b623fffff91909116901b90565b1c637fffffff1690565b4690565b60008161313d5750670de0b6b3a76400006105e7565b8261314a575060006105e7565b6131777f800000000000000000000000000000000000000000000000000000000000000084106006611dbb565b8261319d770bce5086492111aea88f4bb1ca6bcf584181ea8059f7653284106007611dbb565b826000670c7d713b49da0000831380156131be5750670f43fc2c04ee000083125b156131f55760006131ce8461354d565b9050670de0b6b3a764000080820784020583670de0b6b3a764000083050201915050613203565b816131ff84613684565b0290505b670de0b6b3a7640000900561323b680238fd42c5cf03ffff198212801590613234575068070c1cc73b00c800008213155b6008611dbb565b61324481613a24565b9695505050505050565b60006109f08260ea613ede565b60006109f08260b5613f05565b60006109f082609f613ede565b60006109f082606a613f05565b60006109f0826054613ede565b60006109f082601f613f05565b62461bcd60e51b600090815260206004526007602452673f534e5323000030600a808404818106603090810160081b95839006959095019082900491820690940160101b939093010160c81b604452606490fd5b60008282026107aa84158061205f57508385838161205c57fe5b60008061331683613f38565b9050600080821361332f57652d79883d20008203613339565b652d79883d200082015b655af3107a40009005949350505050565b6000806133668585854261335d8b6120c7565b93929190613f94565b90506104b04288900310158061337c5786613385565b61338587613ff4565b600081815260076020526040902092909255509695505050505050565b6133ae60008383612477565b6002546133bb9082611fdf565b6002556001600160a01b0382166000908152602081905260409020546133e19082611fdf565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b61344e6001600160a01b038316151561019b611dbb565b61345a82600083612477565b6001600160a01b03821660009081526020819052604090205461348090826101a16130e1565b6001600160a01b0383166000908152602081905260409020556002546134a69082614001565b6002556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b6000806134fb8484613127565b9050600061350e6120988361271061264f565b9050612bcf8282611fdf565b60006135298215156004611dbb565b82613536575060006105e7565b81600184038161354257fe5b0460010190506105e7565b670de0b6b3a7640000026000806ec097ce7bc90715b34b9f1000000000808401907fffffffffffffffffffffffffffffffffff3f68318436f8ea4cb460f0000000008501028161359957fe5b05905060006ec097ce7bc90715b34b9f100000000082800205905081806ec097ce7bc90715b34b9f100000000081840205915060038205016ec097ce7bc90715b34b9f100000000082840205915060058205016ec097ce7bc90715b34b9f100000000082840205915060078205016ec097ce7bc90715b34b9f100000000082840205915060098205016ec097ce7bc90715b34b9f1000000000828402059150600b8205016ec097ce7bc90715b34b9f1000000000828402059150600d8205016ec097ce7bc90715b34b9f1000000000828402059150600f826002919005919091010295945050505050565b6000670de0b6b3a76400008212156136c1576136b7826ec097ce7bc90715b34b9f1000000000816136b157fe5b05613684565b60000390506109f3565b60007e1600ef3172e58d2e933ec884fde10064c63b5372d805e203c0000000000000831261371257770195e54c5dd42177f53a27172fa9ec630262827000000000830592506806f05b59d3b2000000015b73011798004d755d3c8bc8e03204cf44619e000000831261374a576b1425982cf597cd205cef7380830592506803782dace9d9000000015b606492830292026e01855144814a7ff805980ff00840008312613792576e01855144814a7ff805980ff008400068056bc75e2d63100000840205925068ad78ebc5ac62000000015b6b02df0ab5a80a22c61ab5a70083126137cd576b02df0ab5a80a22c61ab5a70068056bc75e2d6310000084020592506856bc75e2d631000000015b693f1fce3da636ea5cf850831261380457693f1fce3da636ea5cf85068056bc75e2d631000008402059250682b5e3af16b18800000015b690127fa27722cc06cc5e2831261383b57690127fa27722cc06cc5e268056bc75e2d6310000084020592506815af1d78b58c400000015b68280e60114edb805d0383126138705768280e60114edb805d0368056bc75e2d631000008402059250680ad78ebc5ac6200000015b680ebc5fb41746121110831261389b57680ebc5fb4174612111068056bc75e2d631000009384020592015b6808f00f760a4b2db55d83126138d0576808f00f760a4b2db55d68056bc75e2d6310000084020592506802b5e3af16b1880000015b6806f5f17757889379378312613905576806f5f177578893793768056bc75e2d63100000840205925068015af1d78b58c40000015b6806248f33704b2866038312613939576806248f33704b28660368056bc75e2d63100000840205925067ad78ebc5ac620000015b6805c548670b9510e7ac831261396d576805c548670b9510e7ac68056bc75e2d6310000084020592506756bc75e2d6310000015b600068056bc75e2d63100000840168056bc75e2d63100000808603028161399057fe5b059050600068056bc75e2d63100000828002059050818068056bc75e2d63100000818402059150600382050168056bc75e2d63100000828402059150600582050168056bc75e2d63100000828402059150600782050168056bc75e2d63100000828402059150600982050168056bc75e2d63100000828402059150600b820501600202606485820105979650505050505050565b6000613a53680238fd42c5cf03ffff198312158015613a4c575068070c1cc73b00c800008313155b6009611dbb565b6000821215613a8757613a6882600003613a24565b6ec097ce7bc90715b34b9f100000000081613a7f57fe5b0590506109f3565b60006806f05b59d3b20000008312613add57507ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e00000090910190770195e54c5dd42177f53a27172fa9ec630262827000000000613b29565b6803782dace9d90000008312613b2557507ffffffffffffffffffffffffffffffffffffffffffffffffc87d2531627000000909101906b1425982cf597cd205cef7380613b29565b5060015b6064929092029168056bc75e2d6310000068ad78ebc5ac620000008412613b8f577fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e0000009093019268056bc75e2d631000006e01855144814a7ff805980ff008400082020590505b6856bc75e2d6310000008412613be1577fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf0000009093019268056bc75e2d631000006b02df0ab5a80a22c61ab5a70082020590505b682b5e3af16b188000008412613c31577fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e78000009093019268056bc75e2d63100000693f1fce3da636ea5cf85082020590505b6815af1d78b58c4000008412613c81577fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000009093019268056bc75e2d63100000690127fa27722cc06cc5e282020590505b680ad78ebc5ac62000008412613cd0577ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000009093019268056bc75e2d6310000068280e60114edb805d0382020590505b68056bc75e2d631000008412613d1f577ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000009093019268056bc75e2d63100000680ebc5fb4174612111082020590505b6802b5e3af16b18800008412613d6e577ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800009093019268056bc75e2d631000006808f00f760a4b2db55d82020590505b68015af1d78b58c400008412613dbd577ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00009093019268056bc75e2d631000006806f5f177578893793782020590505b68056bc75e2d631000008481019085906002908280020505918201919050600368056bc75e2d631000008783020505918201919050600468056bc75e2d631000008783020505918201919050600568056bc75e2d631000008783020505918201919050600668056bc75e2d631000008783020505918201919050600768056bc75e2d631000008783020505918201919050600868056bc75e2d631000008783020505918201919050600968056bc75e2d631000008783020505918201919050600a68056bc75e2d631000008783020505918201919050600b68056bc75e2d631000008783020505918201919050600c68056bc75e2d631000008783020505918201919050606468056bc75e2d63100000848402058502059695505050505050565b600082821c623fffff16621fffff8113613ef857806121e6565b623fffff19179392505050565b600082821c661fffffffffffff16660fffffffffffff8113613f2757806121e6565b661fffffffffffff19179392505050565b6000613f48600083136064611dbb565b670c7d713b49da000082138015613f665750670f43fc2c04ee000082125b15613f8457670de0b6b3a7640000613f7d8361354d565b81613a7f57fe5b613f8d82613684565b90506109f3565b600080613fa087611f15565b830390506000818702613fb28961325b565b0190506000828702613fc38a613275565b0190506000838702613fd48b61328f565b019050613fe689848a858b868c611eb5565b9a9950505050505050505050565b60006109f082600161400f565b60006107aa838360016130e1565b601491010690565b604080518082019091526000808252602082015290565b6040805160608101909152806000815260200160008152602001600081525090565b80356109f381614a5a565b600082601f83011261406b578081fd5b815161407e61407982614a3c565b614a18565b81815291506020808301908481018184028601820187101561409f57600080fd5b60005b848110156140be578151845292820192908201906001016140a2565b505050505092915050565b600082601f8301126140d9578081fd5b813567ffffffffffffffff8111156140ed57fe5b614100601f8201601f1916602001614a18565b915080825283602082850101111561411757600080fd5b8060208401602084013760009082016020015292915050565b8035600281106109f357600080fd5b8035600381106109f357600080fd5b60006020828403121561415f578081fd5b81356107aa81614a5a565b6000806040838503121561417c578081fd5b823561418781614a5a565b9150602083013561419781614a5a565b809150509250929050565b6000806000606084860312156141b6578081fd5b83356141c181614a5a565b925060208401356141d181614a5a565b929592945050506040919091013590565b600080600080600080600060e0888a0312156141fc578485fd5b873561420781614a5a565b9650602088013561421781614a5a565b95506040880135945060608801359350608088013560ff8116811461423a578384fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215614269578182fd5b823561427481614a5a565b946020939093013593505050565b600080600060608486031215614296578081fd5b835167ffffffffffffffff808211156142ad578283fd5b818601915086601f8301126142c0578283fd5b81516142ce61407982614a3c565b80828252602080830192508086018b8283870289010111156142ee578788fd5b8796505b8487101561431957805161430581614a5a565b8452600196909601959281019281016142f2565b508901519097509350505080821115614330578283fd5b5061433d8682870161405b565b925050604084015190509250925092565b60006020808385031215614360578182fd5b823567ffffffffffffffff80821115614377578384fd5b818501915085601f83011261438a578384fd5b813561439861407982614a3c565b818152848101908486016040808502870188018b10156143b6578889fd5b8896505b8487101561440e5780828c0312156143d0578889fd5b805181810181811088821117156143e357fe5b82526143ee8361413f565b8152828901358982015284526001969096019592870192908101906143ba565b50909998505050505050505050565b6000602080838503121561442f578182fd5b823567ffffffffffffffff80821115614446578384fd5b818501915085601f830112614459578384fd5b813561446761407982614a3c565b818152848101908486016060808502870188018b1015614485578889fd5b8896505b8487101561440e5780828c03121561449f578889fd5b6040805182810181811089821117156144b457fe5b82526144bf8461413f565b8152838a01358a82015281840135918101919091528452600196909601959287019290810190614489565b6000602082840312156144fb578081fd5b815167ffffffffffffffff811115614511578182fd5b6121e68482850161405b565b6000806040838503121561452f578182fd5b825167ffffffffffffffff811115614545578283fd5b6145518582860161405b565b925050602083015190509250929050565b600080600080600080600060e0888a03121561457c578081fd5b8735965060208089013561458f81614a5a565b9650604089013561459f81614a5a565b9550606089013567ffffffffffffffff808211156145bb578384fd5b818b0191508b601f8301126145ce578384fd5b81356145dc61407982614a3c565b8082825285820191508585018f8788860288010111156145fa578788fd5b8795505b8386101561461c5780358352600195909501949186019186016145fe565b509850505060808b0135955060a08b0135945060c08b0135925080831115614642578384fd5b50506146508a828b016140c9565b91505092959891949750929550565b600060208284031215614670578081fd5b6107aa8261413f565b60006020828403121561468a578081fd5b5051919050565b6000806000606084860312156146a5578081fd5b833567ffffffffffffffff808211156146bc578283fd5b81860191506101208083890312156146d2578384fd5b6146db81614a18565b90506146e683614130565b81526146f460208401614050565b602082015261470560408401614050565b6040820152606083013560608201526080830135608082015260a083013560a082015261473460c08401614050565b60c082015261474560e08401614050565b60e0820152610100808401358381111561475d578586fd5b6147698a8287016140c9565b9183019190915250976020870135975060409096013595945050505050565b600060208284031215614799578081fd5b5035919050565b600080604083850312156147b2578182fd5b50508035926020909101359150565b6000815180845260208085019450808401835b838110156147f0578151875295820195908201906001016147d4565b509495945050505050565b6003811061480557fe5b9052565b6148148282516147fb565b60208181015190830152604090810151910152565b6001600160a01b0391909116815260200190565b6020808252825182820181905260009190848201906040850190845b8181101561487557835183529284019291840191600101614859565b50909695505050505050565b6020808252825182820181905260009190848201906040850190845b81811015614875576148b0838551614809565b928401926060929092019160010161489d565b6000602082526107aa60208301846147c1565b6000604082526148e960408301856147c1565b8281036020840152612bcf81856147c1565b901515815260200190565b90815260200190565b968752602087019590955260408601939093526060850191909152608084015260a083015260c082015260e00190565b8381526060810161495360208301856147fb565b826040830152949350505050565b8481526080810161497560208301866147fb565b60408201939093526060015292915050565b83815260a0810161499b6020830185614809565b826080830152949350505050565b6000602080835283518082850152825b818110156149d5578581018301518582016040015282016149b9565b818111156149e65783604083870101525b50601f01601f1916929092016040019392505050565b918252602082015260400190565b60ff91909116815260200190565b60405181810167ffffffffffffffff81118282101715614a3457fe5b604052919050565b600067ffffffffffffffff821115614a5057fe5b5060209081020190565b6001600160a01b0381168114614a6f57600080fd5b5056fea2646970667358221220518e3e6ced12cef564687643b88bb8d971ee7b1e2a8311a54b6922602a5e3ab264736f6c63430007050033

Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.