ETH Price: $2,332.32 (-0.69%)

Contract

0xf4BF4D5a5631d29Bd0B7A33a0a1870bcC4529f03
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
0x61016060182469762023-09-30 7:16:59354 days ago1696058219IN
 Create: JBBuybackDelegate
0 ETH0.028422519.8844113

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
207670222024-09-17 1:21:3544 hrs ago1726536095
0xf4BF4D5a...cC4529f03
0.03699452 ETH
207670222024-09-17 1:21:3544 hrs ago1726536095
0xf4BF4D5a...cC4529f03
0.03699452 ETH
207306412024-09-11 23:25:596 days ago1726097159
0xf4BF4D5a...cC4529f03
0.04684023 ETH
207306412024-09-11 23:25:596 days ago1726097159
0xf4BF4D5a...cC4529f03
0.04684023 ETH
207148792024-09-09 18:35:239 days ago1725906923
0xf4BF4D5a...cC4529f03
0.06577321 ETH
207148792024-09-09 18:35:239 days ago1725906923
0xf4BF4D5a...cC4529f03
0.06577321 ETH
207036292024-09-08 4:53:1110 days ago1725771191
0xf4BF4D5a...cC4529f03
0.12877911 ETH
207036292024-09-08 4:53:1110 days ago1725771191
0xf4BF4D5a...cC4529f03
0.12877911 ETH
207036042024-09-08 4:48:1110 days ago1725770891
0xf4BF4D5a...cC4529f03
0.12877911 ETH
207036042024-09-08 4:48:1110 days ago1725770891
0xf4BF4D5a...cC4529f03
0.12877911 ETH
207036032024-09-08 4:47:5910 days ago1725770879
0xf4BF4D5a...cC4529f03
0.09882496 ETH
207036032024-09-08 4:47:5910 days ago1725770879
0xf4BF4D5a...cC4529f03
0.09882496 ETH
207014942024-09-07 21:43:5911 days ago1725745439
0xf4BF4D5a...cC4529f03
0.12686366 ETH
207014942024-09-07 21:43:5911 days ago1725745439
0xf4BF4D5a...cC4529f03
0.12686366 ETH
206687562024-09-03 8:08:3515 days ago1725350915
0xf4BF4D5a...cC4529f03
0.00295121 ETH
206687562024-09-03 8:08:3515 days ago1725350915
0xf4BF4D5a...cC4529f03
0.00295121 ETH
206376272024-08-29 23:50:1119 days ago1724975411
0xf4BF4D5a...cC4529f03
0.0577317 ETH
206376272024-08-29 23:50:1119 days ago1724975411
0xf4BF4D5a...cC4529f03
0.0577317 ETH
206308772024-08-29 1:10:2320 days ago1724893823
0xf4BF4D5a...cC4529f03
0.00536585 ETH
206308772024-08-29 1:10:2320 days ago1724893823
0xf4BF4D5a...cC4529f03
0.00536585 ETH
206219882024-08-27 19:23:3522 days ago1724786615
0xf4BF4D5a...cC4529f03
0.03902439 ETH
206219882024-08-27 19:23:3522 days ago1724786615
0xf4BF4D5a...cC4529f03
0.03902439 ETH
206215392024-08-27 17:53:2322 days ago1724781203
0xf4BF4D5a...cC4529f03
0.01170731 ETH
206215392024-08-27 17:53:2322 days ago1724781203
0xf4BF4D5a...cC4529f03
0.01170731 ETH
206127892024-08-26 12:33:1123 days ago1724675591
0xf4BF4D5a...cC4529f03
0.07659677 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
JBBuybackDelegate

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
File 1 of 76 : JBBuybackDelegate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IJBPaymentTerminal} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPaymentTerminal.sol";
import {IJBPayoutRedemptionPaymentTerminal3_1_1} from
    "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPayoutRedemptionPaymentTerminal3_1_1.sol";
import {JBDidPayData3_1_1} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBDidPayData3_1_1.sol";
import {JBOperatable} from "@jbx-protocol/juice-contracts-v3/contracts/abstract/JBOperatable.sol";
import {IJBDirectory} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBDirectory.sol";
import {IJBController3_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBController3_1.sol";
import {IJBProjects} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBController3_1.sol";
import {IJBOperatable} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBOperatable.sol";
import {IJBFundingCycleDataSource3_1_1} from
    "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBFundingCycleDataSource3_1_1.sol";
import {IJBPayDelegate3_1_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPayDelegate3_1_1.sol";
import {JBPayDelegateAllocation3_1_1} from
    "@jbx-protocol/juice-contracts-v3/contracts/structs/JBPayDelegateAllocation3_1_1.sol";
import {JBPayParamsData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBPayParamsData.sol";
import {JBRedeemParamsData} from "@jbx-protocol/juice-contracts-v3/contracts/structs/JBRedeemParamsData.sol";
import {JBRedemptionDelegateAllocation3_1_1} from
    "@jbx-protocol/juice-contracts-v3/contracts/structs/JBRedemptionDelegateAllocation3_1_1.sol";
import {JBTokens} from "@jbx-protocol/juice-contracts-v3/contracts/libraries/JBTokens.sol";
import {JBDelegateMetadataLib} from "@jbx-protocol/juice-delegate-metadata-lib/src/JBDelegateMetadataLib.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {ERC165, IERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {mulDiv} from "@prb/math/src/Common.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {OracleLibrary} from "@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {JBBuybackDelegateOperations} from "./libraries/JBBuybackDelegateOperations.sol";
import {IJBBuybackDelegate} from "./interfaces/IJBBuybackDelegate.sol";
import {IWETH9} from "./interfaces/external/IWETH9.sol";

/// @custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
/// @title JBBuybackDelegate
/// @notice Generic Buyback Delegate compatible with any Juicebox payment terminal and any project token that can be pooled.
/// @notice Functions as a Data Source and Delegate allowing beneficiaries of payments to get the highest amount
/// of a project's token between minting using the project weight and swapping in a given Uniswap V3 pool.
contract JBBuybackDelegate is ERC165, JBOperatable, IJBBuybackDelegate {
    //*********************************************************************//
    // --------------------- internal stored properties ------------------ //
    //*********************************************************************//

    /// @notice The TWAP max deviation acepted and timeframe to use for the pool twap, packed in a uint256.
    /// @custom:param _projectId The ID of the project to which the TWAP params apply.
    mapping(uint256 _projectId => uint256) internal _twapParamsOf;

    //*********************************************************************//
    // --------------------- public constant properties ------------------ //
    //*********************************************************************//

    /// @notice The unit of the max slippage.
    uint256 public constant SLIPPAGE_DENOMINATOR = 10_000;

    /// @notice The minimum twap deviation allowed, out of MAX_SLIPPAGE.
    /// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
    uint256 public constant MIN_TWAP_SLIPPAGE_TOLERANCE = 100;

    /// @notice The maximum twap deviation allowed, out of MAX_SLIPPAGE.
    /// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
    uint256 public constant MAX_TWAP_SLIPPAGE_TOLERANCE = 9000;

    /// @notice The smallest TWAP period allowed, in seconds.
    /// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
    uint256 public constant MIN_TWAP_WINDOW = 2 minutes;

    /// @notice The largest TWAP period allowed, in seconds.
    /// @dev This serves to avoid operators settings values that force the bypassing the swap when a quote is not provided in payment metadata.
    uint256 public constant MAX_TWAP_WINDOW = 2 days;

    //*********************************************************************//
    // -------------------- public immutable properties ------------------ //
    //*********************************************************************//

    /// @notice The uniswap v3 factory used to reference pools from.
    address public immutable UNISWAP_V3_FACTORY;

    /// @notice The directory of terminals and controllers.
    IJBDirectory public immutable DIRECTORY;

    /// @notice The controller used to mint and burn tokens from.
    IJBController3_1 public immutable CONTROLLER;

    /// @notice The project registry.
    IJBProjects public immutable PROJECTS;

    /// @notice The WETH contract.
    IWETH9 public immutable WETH;

    /// @notice The 4bytes ID of this delegate, used for metadata parsing.
    bytes4 public immutable DELEGATE_ID;

    //*********************************************************************//
    // --------------------- public stored properties -------------------- //
    //*********************************************************************//

    /// @notice The uniswap pool corresponding to the project token <-> terminal token pair.
    /// @custom:param _projectId The ID of the project to which the pool applies.
    /// @custom:param _terminalToken The address of the token being used to make payments in.
    mapping(uint256 _projectId => mapping(address _terminalToken => IUniswapV3Pool)) public poolOf;

    /// @notice Each project's token.
    /// @custom:param _projectId The ID of the project to which the token belongs.
    mapping(uint256 _projectId => address) public projectTokenOf;

    //*********************************************************************//
    // ---------------------------- constructor -------------------------- //
    //*********************************************************************//

    /// @param _weth The WETH contract.
    /// @param _factory The uniswap v3 factory used to reference pools from.
    /// @param _directory The directory of terminals and controllers.
    /// @param _controller The controller used to mint and burn tokens from.
    /// @param _delegateId The 4bytes ID of this delegate, used for metadata parsing.
    constructor(
        IWETH9 _weth,
        address _factory,
        IJBDirectory _directory,
        IJBController3_1 _controller,
        bytes4 _delegateId
    ) JBOperatable(IJBOperatable(address(_controller)).operatorStore()) {
        WETH = _weth;
        DIRECTORY = _directory;
        CONTROLLER = _controller;
        UNISWAP_V3_FACTORY = _factory;
        DELEGATE_ID = _delegateId;
        PROJECTS = _controller.projects();
    }

    //*********************************************************************//
    // ------------------------- external views -------------------------- //
    //*********************************************************************//

    /// @notice The DataSource implementation that determines if a swap path and/or a mint path should be taken.
    /// @param  _data The data passed to the data source in terminal.pay(..). _data.metadata can have a Uniswap quote and specify how much of the payment should be used to swap, otherwise a quote will be determined from a TWAP and use the full amount paid in.
    /// @return weight The weight to use, which is the original weight passed in if no swap path is taken, 0 if only the swap path is taken, and an adjusted weight if the both the swap and mint paths are taken.
    /// @return memo the original memo passed
    /// @return delegateAllocations The amount to send to delegates instead of adding to the local balance. This is empty if only the mint path is taken.
    function payParams(JBPayParamsData calldata _data)
        external
        view
        override
        returns (uint256 weight, string memory memo, JBPayDelegateAllocation3_1_1[] memory delegateAllocations)
    {
        // Keep a reference to the payment total
        uint256 _totalPaid = _data.amount.value;

        // Keep a reference to the weight
        uint256 _weight = _data.weight;

        // Keep a reference to the minimum number of tokens expected to be swapped for.
        uint256 _minimumSwapAmountOut;

        // Keep a reference to the amount from the payment to allocate towards a swap.
        uint256 _amountToSwapWith;

        // Keep a reference to a flag indicating if the quote passed into the metadata exists.
        bool _quoteExists;

        // Scoped section to prevent Stack Too Deep.
        {
            bytes memory _metadata;

            // Unpack the quote from the pool, given by the frontend.
            (_quoteExists, _metadata) = JBDelegateMetadataLib.getMetadata(DELEGATE_ID, _data.metadata);
            if (_quoteExists) (_amountToSwapWith, _minimumSwapAmountOut) = abi.decode(_metadata, (uint256, uint256));
        }

        // If no amount was specified to swap with, default to the full amount of the payment.
        if (_amountToSwapWith == 0) _amountToSwapWith = _totalPaid;

        // Find the default total number of tokens to mint as if no Buyback Delegate were installed, as a fixed point number with 18 decimals
        
        uint256 _tokenCountWithoutDelegate = mulDiv(_amountToSwapWith, _weight, 10 ** _data.amount.decimals);

        // Keep a reference to the project's token.
        address _projectToken = projectTokenOf[_data.projectId];

        // Keep a reference to the token being used by the terminal that is calling this delegate. Use weth is ETH.
        address _terminalToken = _data.amount.token == JBTokens.ETH ? address(WETH) : _data.amount.token;

        // If a minimum amount of tokens to swap for wasn't specified, resolve a value as good as possible using a TWAP.
        if (_minimumSwapAmountOut == 0) {
            _minimumSwapAmountOut = _getQuote(_data.projectId, _projectToken, _amountToSwapWith, _terminalToken);
        }

        // If the minimum amount received from swapping is greather than received when minting, use the swap path.
        if (_tokenCountWithoutDelegate < _minimumSwapAmountOut) {
            // Make sure the amount to swap with is at most the full amount being paid.
            if (_amountToSwapWith > _totalPaid) revert JuiceBuyback_InsufficientPayAmount();

            // Keep a reference to a flag indicating if the pool will reference the project token as the first in the pair.
            bool _projectTokenIs0 = address(_projectToken) < _terminalToken;

            // Return this delegate as the one to use, while forwarding the amount to swap with. Speficy metadata that allows the swap to be executed.
            delegateAllocations = new JBPayDelegateAllocation3_1_1[](1);
            delegateAllocations[0] = JBPayDelegateAllocation3_1_1({
                delegate: IJBPayDelegate3_1_1(this),
                amount: _amountToSwapWith,
                metadata: abi.encode(_quoteExists, _projectTokenIs0, _totalPaid == _amountToSwapWith ? 0 : _totalPaid - _amountToSwapWith, _minimumSwapAmountOut, _weight)
            });

            // All the mint will be done in didPay, return 0 as weight to avoid minting via the terminal
            return (
                0,
                _data.memo,
                delegateAllocations
            );
        }

        // If only minting, delegateAllocations is left uninitialised and the full weight is returned for the terminal to mint.
        return (_data.weight, _data.memo, delegateAllocations);
    }

    /// @notice The timeframe to use for the pool TWAP.
    /// @param  _projectId The ID of the project for which the value applies.
    /// @return _secondsAgo The period over which the TWAP is computed.
    function twapWindowOf(uint256 _projectId) external view returns (uint32) {
        return uint32(_twapParamsOf[_projectId]);
    }

    /// @notice The TWAP max deviation acepted, out of SLIPPAGE_DENOMINATOR.
    /// @param  _projectId The ID of the project for which the value applies.
    /// @return _delta the maximum deviation allowed between the token amount received and the TWAP quote.
    function twapSlippageToleranceOf(uint256 _projectId) external view returns (uint256) {
        return _twapParamsOf[_projectId] >> 128;
    }

    /// @notice Generic redeem params, for interface completion.
    /// @dev This is a passthrough of the redemption parameters
    /// @param _data The redeem data passed by the terminal.
    function redeemParams(JBRedeemParamsData calldata _data)
        external
        pure
        override
        returns (uint256, string memory, JBRedemptionDelegateAllocation3_1_1[] memory delegateAllocations)
    {
        return (_data.reclaimAmount.value, _data.memo, delegateAllocations);
    }

    //*********************************************************************//
    // -------------------------- public views --------------------------- //
    //*********************************************************************//

    function supportsInterface(bytes4 _interfaceId) public view override(ERC165, IERC165) returns (bool) {
        return _interfaceId == type(IJBFundingCycleDataSource3_1_1).interfaceId
            || _interfaceId == type(IJBPayDelegate3_1_1).interfaceId
            || _interfaceId == type(IJBBuybackDelegate).interfaceId
            || super.supportsInterface(_interfaceId);
    }

    //*********************************************************************//
    // ---------------------- external transactions ---------------------- //
    //*********************************************************************//

    /// @notice Delegate used to swap a provided amount to the beneficiary, using any leftover amount to mint.
    /// @dev This delegate is called only if the quote for the swap is bigger than the quote when minting.
    /// If the swap reverts (slippage, liquidity, etc), the delegate will then mint the same amount of token as if the delegate was not used.
    /// @param _data The delegate data passed by the terminal.
    function didPay(JBDidPayData3_1_1 calldata _data) external payable override {
        // Make sure only a payment terminal belonging to the project can access this functionality.
        if (!DIRECTORY.isTerminalOf(_data.projectId, IJBPaymentTerminal(msg.sender))) {
            revert JuiceBuyback_Unauthorized();
        }

        // Parse the metadata passed in from the data source.
        (
            bool _quoteExists,
            bool _projectTokenIs0,
            uint256 _amountToMintWith,
            uint256 _minimumSwapAmountOut,
            uint256 _weight
        ) = abi.decode(_data.dataSourceMetadata, (bool, bool, uint256, uint256, uint256));

        // Get a reference to the amount of tokens that was swapped for.
        uint256 _exactSwapAmountOut = _swap(_data, _projectTokenIs0);

        // Make sure the slippage is tolerable if passed in via an explicit quote.
        if (_quoteExists && _exactSwapAmountOut < _minimumSwapAmountOut) revert JuiceBuyback_MaximumSlippage();

        // Get a reference to any amount of tokens paid in remaining in this contract.
        uint256 _terminalTokenInThisContract = _data.forwardedAmount.token == JBTokens.ETH
            ? address(this).balance
            : IERC20(_data.forwardedAmount.token).balanceOf(address(this));

        // Use any leftover amount of tokens paid in remaining to mint.
        // Keep a reference to the number of tokens being minted.
        uint256 _partialMintTokenCount;
        if (_terminalTokenInThisContract != 0) {
            _partialMintTokenCount = mulDiv(_terminalTokenInThisContract, _weight, 10 ** _data.amount.decimals);

            // If the token paid in wasn't ETH, give the terminal permission to pull them back into its balance.
            if (_data.forwardedAmount.token != JBTokens.ETH) {
                IERC20(_data.forwardedAmount.token).approve(msg.sender, _terminalTokenInThisContract);
            }

            // Add the paid amount back to the project's terminal balance.
            IJBPayoutRedemptionPaymentTerminal3_1_1(msg.sender).addToBalanceOf{
                value: _data.forwardedAmount.token == JBTokens.ETH ? _terminalTokenInThisContract : 0
            }(_data.projectId, _terminalTokenInThisContract, _data.forwardedAmount.token, "", "");

            emit BuybackDelegate_Mint(_data.projectId, _terminalTokenInThisContract, _partialMintTokenCount, msg.sender);
        } 

        // Add amount to mint to leftover mint amount (avoiding stack too deep here)
        _partialMintTokenCount += mulDiv(_amountToMintWith, _weight, 10 ** _data.amount.decimals);

        // Mint the whole amount of tokens again together with the (optional partial mint), such that the correct portion of reserved tokens get taken into account.
        CONTROLLER.mintTokensOf({
            projectId: _data.projectId,
            tokenCount: _exactSwapAmountOut + _partialMintTokenCount,
            beneficiary: address(_data.beneficiary),
            memo: _data.memo,
            preferClaimedTokens: _data.preferClaimedTokens,
            useReservedRate: true
        });
    }

    /// @notice The Uniswap V3 pool callback where the token transfer is expected to happen.
    /// @param _amount0Delta The amount of token 0 being used for the swap.
    /// @param _amount1Delta The amount of token 1 being used for the swap.
    /// @param _data Data passed in by the swap operation.
    function uniswapV3SwapCallback(int256 _amount0Delta, int256 _amount1Delta, bytes calldata _data)
        external
        override
    {
        // Unpack the data passed in through the swap hook.
        (uint256 _projectId, address _terminalToken) = abi.decode(_data, (uint256, address));

        // Get the terminal token, using WETH if the token paid in is ETH.
        address _terminalTokenWithWETH = _terminalToken == JBTokens.ETH ? address(WETH) : _terminalToken;

        // Make sure this call is being made from within the swap execution.
        if (msg.sender != address(poolOf[_projectId][_terminalTokenWithWETH])) revert JuiceBuyback_Unauthorized();

        // Keep a reference to the amount of tokens that should be sent to fulfill the swap (the positive delta)
        uint256 _amountToSendToPool = _amount0Delta < 0 ? uint256(_amount1Delta) : uint256(_amount0Delta);

        // Wrap ETH into WETH if relevant (do not rely on ETH delegate balance to support pure WETH terminals)
        if (_terminalToken == JBTokens.ETH) WETH.deposit{value: _amountToSendToPool}();

        // Transfer the token to the pool.
        IERC20(_terminalTokenWithWETH).transfer(msg.sender, _amountToSendToPool);
    }

    /// @notice Add a pool for a given project. This pool the becomes the default for a given token project <--> terminal token pair.
    /// @dev Uses create2 for callback auth and allows adding a pool not deployed yet.
    /// This can be called by the project owner or an address having the SET_POOL permission in JBOperatorStore
    /// @param _projectId The ID of the project having its pool set.
    /// @param _fee The fee that is used in the pool being set.
    /// @param _twapWindow The period over which the TWAP is computed.
    /// @param _twapSlippageTolerance The maximum deviation allowed between amount received and TWAP.
    /// @param _terminalToken The terminal token that payments are made in.
    /// @return newPool The pool that was created.
    function setPoolFor(uint256 _projectId, uint24 _fee, uint32 _twapWindow, uint256 _twapSlippageTolerance, address _terminalToken)
        external
        requirePermission(PROJECTS.ownerOf(_projectId), _projectId, JBBuybackDelegateOperations.CHANGE_POOL)
        returns (IUniswapV3Pool newPool)
    {
        // Make sure the provided delta is within sane bounds.
        if (_twapSlippageTolerance < MIN_TWAP_SLIPPAGE_TOLERANCE || _twapSlippageTolerance > MAX_TWAP_SLIPPAGE_TOLERANCE) revert JuiceBuyback_InvalidTwapSlippageTolerance();

        // Make sure the provided period is within sane bounds.
        if (_twapWindow < MIN_TWAP_WINDOW || _twapWindow > MAX_TWAP_WINDOW) revert JuiceBuyback_InvalidTwapWindow();

        // Keep a reference to the project's token.
        address _projectToken = address(CONTROLLER.tokenStore().tokenOf(_projectId));

        // Make sure the project has issued a token.
        if (_projectToken == address(0)) revert JuiceBuyback_NoProjectToken();

        // If the terminal token specified in ETH, use WETH instead.
        if (_terminalToken == JBTokens.ETH) _terminalToken = address(WETH);

        // Keep a reference to a flag indicating if the pool will reference the project token as the first in the pair.
        bool _projectTokenIs0 = address(_projectToken) < _terminalToken;

        // Compute the corresponding pool's address, which is a function of both tokens and the specified fee.
        newPool = IUniswapV3Pool(
            address(
                uint160(
                    uint256(
                        keccak256(
                            abi.encodePacked(
                                hex"ff",
                                UNISWAP_V3_FACTORY,
                                keccak256(
                                    abi.encode(
                                        _projectTokenIs0 ? _projectToken : _terminalToken,
                                        _projectTokenIs0 ? _terminalToken : _projectToken,
                                        _fee
                                    )
                                ),
                                // POOL_INIT_CODE_HASH from https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/PoolAddress.sol
                                bytes32(0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54)
                            )
                        )
                    )
                )
            )
        );

        // Make sure this pool has yet to be specified in this delegate.
        if (poolOf[_projectId][_terminalToken] == newPool) revert JuiceBuyback_PoolAlreadySet();

        // Store the pool.
        poolOf[_projectId][_terminalToken] = newPool;

        // Store the twap period and max slipage.
        _twapParamsOf[_projectId] = _twapSlippageTolerance << 128 | _twapWindow;
        projectTokenOf[_projectId] = address(_projectToken);

        emit BuybackDelegate_TwapWindowChanged(_projectId, 0, _twapWindow, msg.sender);
        emit BuybackDelegate_TwapSlippageToleranceChanged(_projectId, 0, _twapSlippageTolerance, msg.sender);
        emit BuybackDelegate_PoolAdded(_projectId, _terminalToken, address(newPool), msg.sender);
    }

    /// @notice Increase the period over which the TWAP is computed.
    /// @dev This can be called by the project owner or an address having the SET_TWAP_PERIOD permission in JBOperatorStore.
    /// @param _projectId The ID for which the new value applies.
    /// @param _newWindow The new TWAP period.
    function setTwapWindowOf(uint256 _projectId, uint32 _newWindow)
        external
        requirePermission(PROJECTS.ownerOf(_projectId), _projectId, JBBuybackDelegateOperations.SET_POOL_PARAMS)
    {
        // Make sure the provided period is within sane bounds.
        if (_newWindow < MIN_TWAP_WINDOW || _newWindow > MAX_TWAP_WINDOW) {
            revert JuiceBuyback_InvalidTwapWindow();
        }

        // Keep a reference to the currently stored TWAP params.
        uint256 _twapParams = _twapParamsOf[_projectId];

        // Keep a reference to the old window value.
        uint256 _oldWindow = uint128(_twapParams);

        // Store the new packed value of the TWAP params.
        _twapParamsOf[_projectId] = uint256(_newWindow) | ((_twapParams >> 128) << 128);

        emit BuybackDelegate_TwapWindowChanged(_projectId, _oldWindow, _newWindow, msg.sender);
    }

    /// @notice Set the maximum deviation allowed between amount received and TWAP.
    /// @dev This can be called by the project owner or an address having the SET_POOL permission in JBOperatorStore.
    /// @param _projectId The ID for which the new value applies.
    /// @param _newSlippageTolerance the new delta, out of SLIPPAGE_DENOMINATOR.
    function setTwapSlippageToleranceOf(uint256 _projectId, uint256 _newSlippageTolerance)
        external
        requirePermission(PROJECTS.ownerOf(_projectId), _projectId, JBBuybackDelegateOperations.SET_POOL_PARAMS)
    {
        // Make sure the provided delta is within sane bounds.
        if (_newSlippageTolerance < MIN_TWAP_SLIPPAGE_TOLERANCE || _newSlippageTolerance > MAX_TWAP_SLIPPAGE_TOLERANCE) revert JuiceBuyback_InvalidTwapSlippageTolerance();

        // Keep a reference to the currently stored TWAP params.
        uint256 _twapParams = _twapParamsOf[_projectId];

        // Keep a reference to the old slippage value.
        uint256 _oldSlippageTolerance = _twapParams >> 128;

        // Store the new packed value of the TWAP params.
        _twapParamsOf[_projectId] = _newSlippageTolerance << 128 | ((_twapParams << 128) >> 128);

        emit BuybackDelegate_TwapSlippageToleranceChanged(_projectId, _oldSlippageTolerance, _newSlippageTolerance, msg.sender);
    }

    //*********************************************************************//
    // ---------------------- internal functions ------------------------- //
    //*********************************************************************//

    /// @notice Get a quote based on TWAP over a secondsAgo period, taking into account a twapDelta max deviation.
    /// @param _projectId The ID of the project for which the swap is being made.
    /// @param _projectToken The project's token being swapped for.
    /// @param _amountIn The amount being used to swap.
    /// @param _terminalToken The token paid in being used to swap.
    /// @return amountOut the minimum amount received according to the TWAP.
    function _getQuote(uint256 _projectId, address _projectToken, uint256 _amountIn, address _terminalToken)
        internal
        view
        returns (uint256 amountOut)
    {
        // Get a reference to the pool that'll be used to make the swap.
        IUniswapV3Pool _pool = poolOf[_projectId][address(_terminalToken)];

        // Make sure the pool exists.
        try _pool.slot0() returns (uint160, int24, uint16, uint16, uint16, uint8, bool unlocked) {
            // If the pool hasn't been initialized, return an empty quote.
            if (!unlocked) return 0;
        } catch {
            // If the address is invalid or if the pool has not yet been deployed, return an empty quote.
            return 0;
        }

        // Unpack the TWAP params and get a reference to the period and slippage.
        uint256 _twapParams = _twapParamsOf[_projectId];
        uint32 _quotePeriod = uint32(_twapParams);
        uint256 _maxDelta = _twapParams >> 128;

        // Keep a reference to the TWAP tick.
        (int24 arithmeticMeanTick,) = OracleLibrary.consult(address(_pool), _quotePeriod);

        // Get a quote based on this TWAP tick.
        amountOut = OracleLibrary.getQuoteAtTick({
            tick: arithmeticMeanTick,
            baseAmount: uint128(_amountIn),
            baseToken: _terminalToken,
            quoteToken: address(_projectToken)
        });

        // Return the lowest TWAP tolerable.
        amountOut -= (amountOut * _maxDelta) / SLIPPAGE_DENOMINATOR;
    }

    /// @notice Swap the terminal token to receive the project token.
    /// @param _data The didPayData passed by the terminal.
    /// @param _projectTokenIs0 A flag indicating if the pool will reference the project token as the first in the pair.
    /// @return amountReceived The amount of tokens received from the swap.
    function _swap(
        JBDidPayData3_1_1 calldata _data,
        bool _projectTokenIs0
    ) internal returns (uint256 amountReceived) {
        // The amount of tokens that are being used with which to make the swap.
        uint256 _amountToSwapWith = _data.forwardedAmount.value;

        // Get the terminal token, using WETH if the token paid in is ETH.
        address _terminalTokenWithWETH = _data.forwardedAmount.token == JBTokens.ETH ? address(WETH) : _data.forwardedAmount.token;

        // Get a reference to the pool that'll be used to make the swap.
        IUniswapV3Pool _pool = poolOf[_data.projectId][_terminalTokenWithWETH];

        // Try swapping.
        try _pool.swap({
            recipient: address(this),
            zeroForOne: !_projectTokenIs0,
            amountSpecified: int256(_amountToSwapWith),
            sqrtPriceLimitX96: _projectTokenIs0 ? TickMath.MAX_SQRT_RATIO - 1 : TickMath.MIN_SQRT_RATIO + 1,
            data: abi.encode(_data.projectId, _data.forwardedAmount.token)
        }) returns (int256 amount0, int256 amount1) {
            // If the swap succeded, take note of the amount of tokens received. This will return as negative since it is an exact input.
            amountReceived = uint256(-(_projectTokenIs0 ? amount0 : amount1));
        } catch {
            // If the swap failed, return.
            return 0;
        }

        // Burn the whole amount received.
        CONTROLLER.burnTokensOf({
            holder: address(this),
            projectId: _data.projectId,
            tokenCount: amountReceived,
            memo: "",
            preferClaimedTokens: true
        });

        // We return the amount we received/burned and we will mint them to the user later

        emit BuybackDelegate_Swap(_data.projectId, _amountToSwapWith, _pool, amountReceived, msg.sender);
    }
}

File 2 of 76 : IJBPaymentTerminal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';

interface IJBPaymentTerminal is IERC165 {
  function acceptsToken(address token, uint256 projectId) external view returns (bool);

  function currencyForToken(address token) external view returns (uint256);

  function decimalsForToken(address token) external view returns (uint256);

  // Return value must be a fixed point number with 18 decimals.
  function currentEthOverflowOf(uint256 projectId) external view returns (uint256);

  function pay(
    uint256 projectId,
    uint256 amount,
    address token,
    address beneficiary,
    uint256 minReturnedTokens,
    bool preferClaimedTokens,
    string calldata memo,
    bytes calldata metadata
  ) external payable returns (uint256 beneficiaryTokenCount);

  function addToBalanceOf(
    uint256 projectId,
    uint256 amount,
    address token,
    string calldata memo,
    bytes calldata metadata
  ) external payable;
}

File 3 of 76 : IJBPayoutRedemptionPaymentTerminal3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBFee} from './../structs/JBFee.sol';
import {JBDidRedeemData3_1_1} from './../structs/JBDidRedeemData3_1_1.sol';
import {JBDidPayData3_1_1} from './../structs/JBDidPayData3_1_1.sol';
import {IJBPayDelegate3_1_1} from './IJBPayDelegate3_1_1.sol';
import {IJBRedemptionDelegate3_1_1} from './IJBRedemptionDelegate3_1_1.sol';
import {IJBPayoutRedemptionPaymentTerminal3_1} from './IJBPayoutRedemptionPaymentTerminal3_1.sol';

interface IJBPayoutRedemptionPaymentTerminal3_1_1 is IJBPayoutRedemptionPaymentTerminal3_1 {
  event DelegateDidRedeem(
    IJBRedemptionDelegate3_1_1 indexed delegate,
    JBDidRedeemData3_1_1 data,
    uint256 delegatedAmount,
    uint256 fee,
    address caller
  );

  event DelegateDidPay(
    IJBPayDelegate3_1_1 indexed delegate,
    JBDidPayData3_1_1 data,
    uint256 delegatedAmount,
    address caller
  );
}

File 4 of 76 : JBDidPayData3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBTokenAmount} from './JBTokenAmount.sol';

/// @custom:member payer The address from which the payment originated.
/// @custom:member projectId The ID of the project for which the payment was made.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the payment is being made.
/// @custom:member amount The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member projectTokenCount The number of project tokens minted for the beneficiary.
/// @custom:member beneficiary The address to which the tokens were minted.
/// @custom:member preferClaimedTokens A flag indicating whether the request prefered to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract.
/// @custom:member memo The memo that is being emitted alongside the payment.
/// @custom:member dataSourceMetadata Extra data to send to the delegate sent by the data source.
/// @custom:member payerMetadata Extra data to send to the delegate sent by the payer.
struct JBDidPayData3_1_1 {
  address payer;
  uint256 projectId;
  uint256 currentFundingCycleConfiguration;
  JBTokenAmount amount;
  JBTokenAmount forwardedAmount;
  uint256 projectTokenCount;
  address beneficiary;
  bool preferClaimedTokens;
  string memo;
  bytes dataSourceMetadata;
  bytes payerMetadata;
}

File 5 of 76 : JBOperatable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

import {IJBOperatable} from './../interfaces/IJBOperatable.sol';
import {IJBOperatorStore} from './../interfaces/IJBOperatorStore.sol';

/// @notice Modifiers to allow access to functions based on the message sender's operator status.
abstract contract JBOperatable is IJBOperatable {
  //*********************************************************************//
  // --------------------------- custom errors -------------------------- //
  //*********************************************************************//
  error UNAUTHORIZED();

  //*********************************************************************//
  // ---------------------------- modifiers ---------------------------- //
  //*********************************************************************//

  /// @notice Only allows the speficied account or an operator of the account to proceed.
  /// @param _account The account to check for.
  /// @param _domain The domain namespace to look for an operator within.
  /// @param _permissionIndex The index of the permission to check for.
  modifier requirePermission(
    address _account,
    uint256 _domain,
    uint256 _permissionIndex
  ) {
    _requirePermission(_account, _domain, _permissionIndex);
    _;
  }

  /// @notice Only allows the speficied account, an operator of the account to proceed, or a truthy override flag.
  /// @param _account The account to check for.
  /// @param _domain The domain namespace to look for an operator within.
  /// @param _permissionIndex The index of the permission to check for.
  /// @param _override A condition to force allowance for.
  modifier requirePermissionAllowingOverride(
    address _account,
    uint256 _domain,
    uint256 _permissionIndex,
    bool _override
  ) {
    _requirePermissionAllowingOverride(_account, _domain, _permissionIndex, _override);
    _;
  }

  //*********************************************************************//
  // ---------------- public immutable stored properties --------------- //
  //*********************************************************************//

  /// @notice A contract storing operator assignments.
  IJBOperatorStore public immutable override operatorStore;

  //*********************************************************************//
  // -------------------------- constructor ---------------------------- //
  //*********************************************************************//

  /// @param _operatorStore A contract storing operator assignments.
  constructor(IJBOperatorStore _operatorStore) {
    operatorStore = _operatorStore;
  }

  //*********************************************************************//
  // -------------------------- internal views ------------------------- //
  //*********************************************************************//

  /// @notice Require the message sender is either the account or has the specified permission.
  /// @param _account The account to allow.
  /// @param _domain The domain namespace within which the permission index will be checked.
  /// @param _permissionIndex The permission index that an operator must have within the specified domain to be allowed.
  function _requirePermission(
    address _account,
    uint256 _domain,
    uint256 _permissionIndex
  ) internal view {
    if (
      msg.sender != _account &&
      !operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
      !operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
    ) revert UNAUTHORIZED();
  }

  /// @notice Require the message sender is either the account, has the specified permission, or the override condition is true.
  /// @param _account The account to allow.
  /// @param _domain The domain namespace within which the permission index will be checked.
  /// @param _domain The permission index that an operator must have within the specified domain to be allowed.
  /// @param _override The override condition to allow.
  function _requirePermissionAllowingOverride(
    address _account,
    uint256 _domain,
    uint256 _permissionIndex,
    bool _override
  ) internal view {
    if (
      !_override &&
      msg.sender != _account &&
      !operatorStore.hasPermission(msg.sender, _account, _domain, _permissionIndex) &&
      !operatorStore.hasPermission(msg.sender, _account, 0, _permissionIndex)
    ) revert UNAUTHORIZED();
  }
}

File 6 of 76 : IJBDirectory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBFundingCycleStore} from './IJBFundingCycleStore.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
import {IJBProjects} from './IJBProjects.sol';

interface IJBDirectory {
  event SetController(uint256 indexed projectId, address indexed controller, address caller);

  event AddTerminal(uint256 indexed projectId, IJBPaymentTerminal indexed terminal, address caller);

  event SetTerminals(uint256 indexed projectId, IJBPaymentTerminal[] terminals, address caller);

  event SetPrimaryTerminal(
    uint256 indexed projectId,
    address indexed token,
    IJBPaymentTerminal indexed terminal,
    address caller
  );

  event SetIsAllowedToSetFirstController(address indexed addr, bool indexed flag, address caller);

  function projects() external view returns (IJBProjects);

  function fundingCycleStore() external view returns (IJBFundingCycleStore);

  function controllerOf(uint256 projectId) external view returns (address);

  function isAllowedToSetFirstController(address account) external view returns (bool);

  function terminalsOf(uint256 projectId) external view returns (IJBPaymentTerminal[] memory);

  function isTerminalOf(
    uint256 projectId,
    IJBPaymentTerminal terminal
  ) external view returns (bool);

  function primaryTerminalOf(
    uint256 projectId,
    address token
  ) external view returns (IJBPaymentTerminal);

  function setControllerOf(uint256 projectId, address controller) external;

  function setTerminalsOf(uint256 projectId, IJBPaymentTerminal[] calldata terminals) external;

  function setPrimaryTerminalOf(
    uint256 projectId,
    address token,
    IJBPaymentTerminal terminal
  ) external;

  function setIsAllowedToSetFirstController(address account, bool flag) external;
}

File 7 of 76 : IJBController3_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBBallotState} from './../enums/JBBallotState.sol';
import {JBFundAccessConstraints} from './../structs/JBFundAccessConstraints.sol';
import {JBFundingCycle} from './../structs/JBFundingCycle.sol';
import {JBFundingCycleData} from './../structs/JBFundingCycleData.sol';
import {JBFundingCycleMetadata} from './../structs/JBFundingCycleMetadata.sol';
import {JBGroupedSplits} from './../structs/JBGroupedSplits.sol';
import {JBProjectMetadata} from './../structs/JBProjectMetadata.sol';
import {JBSplit} from './../structs/JBSplit.sol';
import {IJBController3_0_1} from './IJBController3_0_1.sol';
import {IJBDirectory} from './IJBDirectory.sol';
import {IJBFundAccessConstraintsStore} from './IJBFundAccessConstraintsStore.sol';
import {IJBFundingCycleStore} from './IJBFundingCycleStore.sol';
import {IJBMigratable} from './IJBMigratable.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
import {IJBProjects} from './IJBProjects.sol';
import {IJBSplitsStore} from './IJBSplitsStore.sol';
import {IJBTokenStore} from './IJBTokenStore.sol';

interface IJBController3_1 is IJBController3_0_1, IERC165 {
  event LaunchProject(uint256 configuration, uint256 projectId, string memo, address caller);

  event LaunchFundingCycles(uint256 configuration, uint256 projectId, string memo, address caller);

  event ReconfigureFundingCycles(
    uint256 configuration,
    uint256 projectId,
    string memo,
    address caller
  );

  event DistributeReservedTokens(
    uint256 indexed fundingCycleConfiguration,
    uint256 indexed fundingCycleNumber,
    uint256 indexed projectId,
    address beneficiary,
    uint256 tokenCount,
    uint256 beneficiaryTokenCount,
    string memo,
    address caller
  );

  event DistributeToReservedTokenSplit(
    uint256 indexed projectId,
    uint256 indexed domain,
    uint256 indexed group,
    JBSplit split,
    uint256 tokenCount,
    address caller
  );

  event MintTokens(
    address indexed beneficiary,
    uint256 indexed projectId,
    uint256 tokenCount,
    uint256 beneficiaryTokenCount,
    string memo,
    uint256 reservedRate,
    address caller
  );

  event BurnTokens(
    address indexed holder,
    uint256 indexed projectId,
    uint256 tokenCount,
    string memo,
    address caller
  );

  event Migrate(uint256 indexed projectId, IJBMigratable to, address caller);

  event PrepMigration(uint256 indexed projectId, address from, address caller);

  function projects() external view returns (IJBProjects);

  function fundingCycleStore() external view returns (IJBFundingCycleStore);

  function tokenStore() external view returns (IJBTokenStore);

  function splitsStore() external view returns (IJBSplitsStore);

  function fundAccessConstraintsStore() external view returns (IJBFundAccessConstraintsStore);

  function directory() external view returns (IJBDirectory);

  function reservedTokenBalanceOf(uint256 projectId) external view returns (uint256);

  function totalOutstandingTokensOf(uint256 projectId) external view returns (uint256);

  function getFundingCycleOf(
    uint256 projectId,
    uint256 configuration
  )
    external
    view
    returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);

  function latestConfiguredFundingCycleOf(
    uint256 projectId
  )
    external
    view
    returns (JBFundingCycle memory, JBFundingCycleMetadata memory metadata, JBBallotState);

  function currentFundingCycleOf(
    uint256 projectId
  )
    external
    view
    returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);

  function queuedFundingCycleOf(
    uint256 projectId
  )
    external
    view
    returns (JBFundingCycle memory fundingCycle, JBFundingCycleMetadata memory metadata);

  function launchProjectFor(
    address owner,
    JBProjectMetadata calldata projectMetadata,
    JBFundingCycleData calldata data,
    JBFundingCycleMetadata calldata metadata,
    uint256 mustStartAtOrAfter,
    JBGroupedSplits[] memory groupedSplits,
    JBFundAccessConstraints[] memory fundAccessConstraints,
    IJBPaymentTerminal[] memory terminals,
    string calldata memo
  ) external returns (uint256 projectId);

  function launchFundingCyclesFor(
    uint256 projectId,
    JBFundingCycleData calldata data,
    JBFundingCycleMetadata calldata metadata,
    uint256 mustStartAtOrAfter,
    JBGroupedSplits[] memory groupedSplits,
    JBFundAccessConstraints[] memory fundAccessConstraints,
    IJBPaymentTerminal[] memory terminals,
    string calldata memo
  ) external returns (uint256 configuration);

  function reconfigureFundingCyclesOf(
    uint256 projectId,
    JBFundingCycleData calldata data,
    JBFundingCycleMetadata calldata metadata,
    uint256 mustStartAtOrAfter,
    JBGroupedSplits[] memory groupedSplits,
    JBFundAccessConstraints[] memory fundAccessConstraints,
    string calldata memo
  ) external returns (uint256);

  function mintTokensOf(
    uint256 projectId,
    uint256 tokenCount,
    address beneficiary,
    string calldata memo,
    bool preferClaimedTokens,
    bool useReservedRate
  ) external returns (uint256 beneficiaryTokenCount);

  function burnTokensOf(
    address holder,
    uint256 projectId,
    uint256 tokenCount,
    string calldata memo,
    bool preferClaimedTokens
  ) external;

  function distributeReservedTokensOf(
    uint256 projectId,
    string memory memo
  ) external returns (uint256);

  function migrate(uint256 projectId, IJBMigratable to) external;
}

File 8 of 76 : IJBOperatable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBOperatorStore} from './IJBOperatorStore.sol';

interface IJBOperatable {
  function operatorStore() external view returns (IJBOperatorStore);
}

File 9 of 76 : IJBFundingCycleDataSource3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBPayDelegateAllocation3_1_1} from './../structs/JBPayDelegateAllocation3_1_1.sol';
import {JBPayParamsData} from './../structs/JBPayParamsData.sol';
import {JBRedeemParamsData} from './../structs/JBRedeemParamsData.sol';
import {JBRedemptionDelegateAllocation3_1_1} from './../structs/JBRedemptionDelegateAllocation3_1_1.sol';

/// @title Datasource
/// @notice The datasource is called by JBPayoutRedemptionPaymentTerminals on pay and redemption, and provide an extra layer of logic to use a custom weight, a custom memo and/or a pay/redeem delegate
interface IJBFundingCycleDataSource3_1_1 is IERC165 {
  /// @notice The datasource implementation for JBPaymentTerminal.pay(..)
  /// @param data the data passed to the data source in terminal.pay(..), as a JBPayParamsData struct:
  /// @return weight the weight to use to override the funding cycle weight
  /// @return memo the memo to override the pay(..) memo
  /// @return delegateAllocations The amount to send to delegates instead of adding to the local balance.
  function payParams(
    JBPayParamsData calldata data
  )
    external
    view
    returns (
      uint256 weight,
      string memory memo,
      JBPayDelegateAllocation3_1_1[] memory delegateAllocations
    );

  /// @notice The datasource implementation for JBPaymentTerminal.redeemTokensOf(..)
  /// @param data the data passed to the data source in terminal.redeemTokensOf(..), as a JBRedeemParamsData struct:
  /// @return reclaimAmount The amount to claim, overriding the terminal logic.
  /// @return memo The memo to override the redeemTokensOf(..) memo.
  /// @return delegateAllocations The amount to send to delegates instead of adding to the beneficiary.
  function redeemParams(
    JBRedeemParamsData calldata data
  )
    external
    view
    returns (
      uint256 reclaimAmount,
      string memory memo,
      JBRedemptionDelegateAllocation3_1_1[] memory delegateAllocations
    );
}

File 10 of 76 : IJBPayDelegate3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidPayData3_1_1} from './../structs/JBDidPayData3_1_1.sol';

/// @title Pay delegate
/// @notice Delegate called after JBTerminal.pay(..) logic completion (if passed by the funding cycle datasource)
interface IJBPayDelegate3_1_1 is IERC165 {
  /// @notice This function is called by JBPaymentTerminal.pay(..), after the execution of its logic
  /// @dev Critical business logic should be protected by an appropriate access control
  /// @param data the data passed by the terminal, as a JBDidPayData3_1_1 struct:
  function didPay(JBDidPayData3_1_1 calldata data) external payable;
}

File 11 of 76 : JBPayDelegateAllocation3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBPayDelegate3_1_1} from '../interfaces/IJBPayDelegate3_1_1.sol';

/// @custom:member delegate A delegate contract to use for subsequent calls.
/// @custom:member amount The amount to send to the delegate.
/// @custom:member metadata Metadata to pass the delegate.
struct JBPayDelegateAllocation3_1_1 {
  IJBPayDelegate3_1_1 delegate;
  uint256 amount;
  bytes metadata;
}

File 12 of 76 : JBPayParamsData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';
import {JBTokenAmount} from './JBTokenAmount.sol';

/// @custom:member terminal The terminal that is facilitating the payment.
/// @custom:member payer The address from which the payment originated.
/// @custom:member amount The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member projectId The ID of the project being paid.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the payment is being made.
/// @custom:member beneficiary The specified address that should be the beneficiary of anything that results from the payment.
/// @custom:member weight The weight of the funding cycle during which the payment is being made.
/// @custom:member reservedRate The reserved rate of the funding cycle during which the payment is being made.
/// @custom:member memo The memo that was sent alongside the payment.
/// @custom:member metadata Extra data provided by the payer.
struct JBPayParamsData {
  IJBPaymentTerminal terminal;
  address payer;
  JBTokenAmount amount;
  uint256 projectId;
  uint256 currentFundingCycleConfiguration;
  address beneficiary;
  uint256 weight;
  uint256 reservedRate;
  string memo;
  bytes metadata;
}

File 13 of 76 : JBRedeemParamsData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';
import {JBTokenAmount} from './JBTokenAmount.sol';

/// @custom:member terminal The terminal that is facilitating the redemption.
/// @custom:member holder The holder of the tokens being redeemed.
/// @custom:member projectId The ID of the project whos tokens are being redeemed.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the redemption is being made.
/// @custom:member tokenCount The proposed number of tokens being redeemed, as a fixed point number with 18 decimals.
/// @custom:member totalSupply The total supply of tokens used in the calculation, as a fixed point number with 18 decimals.
/// @custom:member overflow The amount of overflow used in the reclaim amount calculation.
/// @custom:member reclaimAmount The amount that should be reclaimed by the redeemer using the protocol's standard bonding curve redemption formula. Includes the token being reclaimed, the reclaim value, the number of decimals included, and the currency of the reclaim amount.
/// @custom:member useTotalOverflow If overflow across all of a project's terminals is being used when making redemptions.
/// @custom:member redemptionRate The redemption rate of the funding cycle during which the redemption is being made.
/// @custom:member memo The proposed memo that is being emitted alongside the redemption.
/// @custom:member metadata Extra data provided by the redeemer.
struct JBRedeemParamsData {
  IJBPaymentTerminal terminal;
  address holder;
  uint256 projectId;
  uint256 currentFundingCycleConfiguration;
  uint256 tokenCount;
  uint256 totalSupply;
  uint256 overflow;
  JBTokenAmount reclaimAmount;
  bool useTotalOverflow;
  uint256 redemptionRate;
  string memo;
  bytes metadata;
}

File 14 of 76 : JBRedemptionDelegateAllocation3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBRedemptionDelegate3_1_1} from '../interfaces/IJBRedemptionDelegate3_1_1.sol';

/// @custom:member delegate A delegate contract to use for subsequent calls.
/// @custom:member amount The amount to send to the delegate.
/// @custom:member metadata Metadata to pass the delegate.
struct JBRedemptionDelegateAllocation3_1_1 {
  IJBRedemptionDelegate3_1_1 delegate;
  uint256 amount;
  bytes metadata;
}

File 15 of 76 : JBTokens.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

library JBTokens {
  /// @notice The ETH token address in Juicebox is represented by 0x000000000000000000000000000000000000EEEe.
  address public constant ETH = address(0x000000000000000000000000000000000000EEEe);
}

File 16 of 76 : JBDelegateMetadataLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import './JBDelegateMetadataConstants.sol';

/**
 * @notice Library to parse and create delegate metadata
 *
 * @dev    Metadata are built as:
 *         - 32B of reserved space for the protocol
 *         - a lookup table `delegateId: offset`, defining the offset of the metadata for each delegate.
 *           The offset fits 1 bytes, the ID 4 bytes. This table is padded to 32B.
 *         - the metadata for each delegate, padded to 32B each
 *
 *            +-----------------------+ offset: 0
 *            | 32B reserved          |
 *            +-----------------------+ offset: 1 = end of first 32B
 *            | (delegate1 ID,offset1)|
 *            | (delegate2 ID,offset2)|
 *            | 0's padding           |
 *            +-----------------------+ offset: offset1 = 1 + number of words taken by the padded table
 *            | delegate 1 metadata1  |
 *            | 0's padding           |
 *            +-----------------------+ offset: offset2 = offset1 + number of words taken by the metadata1
 *            | delegate 2 metadata2  |
 *            | 0's padding           |
 *            +-----------------------+
 */
library JBDelegateMetadataLib {
    /**
     * @notice Parse the metadata to find the metadata for a specific delegate
     *
     * @dev    Returns false and an empty bytes if no metadata is found
     *
     * @param  _id             The delegate id to find
     * @param  _metadata       The metadata to parse
     *
     * @return _found          Whether the metadata was found
     * @return _targetMetadata The metadata for the delegate
     */
    function getMetadata(bytes4 _id, bytes calldata _metadata) internal pure returns (bool _found, bytes memory _targetMetadata) {
        // Either no metadata or empty one with only one selector (32+4+1)
        if (_metadata.length <= MIN_METADATA_LENGTH) return (false, "");

        // Get the first data offset - upcast to avoid overflow (same for other offset)
        uint256 _firstOffset = uint8(_metadata[RESERVED_SIZE + ID_SIZE]);

        // Parse the id's to find _id, stop when next offset == 0 or current = first offset
        for (uint256 _i = RESERVED_SIZE; _metadata[_i + ID_SIZE] != bytes1(0) && _i < _firstOffset * WORD_SIZE;) {
            uint256 _currentOffset = uint256(uint8(_metadata[_i + ID_SIZE]));

            // _id found?
            if (bytes4(_metadata[_i:_i + ID_SIZE]) == _id) {
                // Are we at the end of the lookup table (either at the start of data's or next offset is 0/in the padding)
                // If not, only return until from this offset to the begining of the next offset
                uint256 _end = (_i + NEXT_DELEGATE_OFFSET >= _firstOffset * WORD_SIZE || _metadata[_i + NEXT_DELEGATE_OFFSET] == 0)
                    ? _metadata.length
                    : uint256(uint8(_metadata[_i + NEXT_DELEGATE_OFFSET])) * WORD_SIZE;

                return (true, _metadata[_currentOffset * WORD_SIZE:_end]);
            }
            unchecked {
                _i += TOTAL_ID_SIZE;
            }
        }
    }

    /**
     * @notice Add a delegate to an existing metadata
     *
     * @param _idToAdd         The id of the delegate to add
     * @param _dataToAdd       The metadata of the delegate to add
     * @param _originalMetadata The original metadata
     *
     * @return _newMetadata    The new metadata with the delegate added
     */
    function addToMetadata(bytes4 _idToAdd, bytes calldata _dataToAdd, bytes calldata _originalMetadata) public pure returns (bytes memory _newMetadata) {
        // Get the first data offset - upcast to avoid overflow (same for other offset)...
        uint256 _firstOffset = uint8(_originalMetadata[RESERVED_SIZE + ID_SIZE]);

        // ...go back to the beginning of the previous word (ie the last word of the table, as it can be padded)
        uint256 _lastWordOfTable = _firstOffset - 1;

        // The last offset stored in the table and its index
        uint256 _lastOffset;

        uint256 _lastOffsetIndex;

        // The number of words taken by the last data stored
        uint256 _numberOfWordslastData;

        // Iterate to find the last entry of the table, _lastOffset - we start from the end as the first value encountered
        // will be the last offset
        for(uint256 _i = _firstOffset * WORD_SIZE - 1; _i > _lastWordOfTable * WORD_SIZE - 1;) {

            // If the byte is not 0, this is the last offset we're looking for
            if (_originalMetadata[_i] != 0) {
                _lastOffset = uint8(_originalMetadata[_i]);
                _lastOffsetIndex = _i;

                // No rounding as this should be padded to 32B
                _numberOfWordslastData = (_originalMetadata.length - _lastOffset * WORD_SIZE) / WORD_SIZE;

                // Copy the reserved word and the table and remove the previous padding
                _newMetadata = _originalMetadata[0 : _lastOffsetIndex + 1];

                // Check if the new entry is still fitting in this word
                if(_i + TOTAL_ID_SIZE >= _firstOffset * WORD_SIZE) {
                    // Increment every offset by 1 (as the table now takes one more word)
                    for (uint256 _j = RESERVED_SIZE + ID_SIZE; _j < _lastOffsetIndex + 1; _j += TOTAL_ID_SIZE) {
                        _newMetadata[_j] = bytes1(uint8(_originalMetadata[_j]) + 1);
                    }

                    // Increment the last offset so the new offset will be properly set too
                    _lastOffset++;
                }

                break;
            }

            unchecked {
                _i -= 1;
            }
        }

        // Add the new entry after the last entry of the table, the new offset is the last offset + the number of words taken by the last data
        _newMetadata = abi.encodePacked(_newMetadata, _idToAdd, bytes1(uint8(_lastOffset + _numberOfWordslastData)));

        // Pad as needed - inlined for gas saving
        uint256 _paddedLength =
            _newMetadata.length % WORD_SIZE == 0 ? _newMetadata.length : (_newMetadata.length / WORD_SIZE + 1) * WORD_SIZE;
        assembly {
            mstore(_newMetadata, _paddedLength)
        }

        // Add existing data at the end
        _newMetadata = abi.encodePacked(_newMetadata, _originalMetadata[_firstOffset * WORD_SIZE : _originalMetadata.length]);

        // Pad as needed
        _paddedLength =
            _newMetadata.length % WORD_SIZE == 0 ? _newMetadata.length : (_newMetadata.length / WORD_SIZE + 1) * WORD_SIZE;
        assembly {
            mstore(_newMetadata, _paddedLength)
        }

        // Append new data at the end
        _newMetadata = abi.encodePacked(_newMetadata, _dataToAdd);

        // Pad again again as needed
        _paddedLength =
            _newMetadata.length % WORD_SIZE == 0 ? _newMetadata.length : (_newMetadata.length / WORD_SIZE + 1) * WORD_SIZE;

        assembly {
            mstore(_newMetadata, _paddedLength)
        }
    }
}

File 17 of 76 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";

File 18 of 76 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 19 of 76 : Common.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

// Common.sol
//
// Common mathematical functions needed by both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.

/*//////////////////////////////////////////////////////////////////////////
                                CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);

/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);

/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();

/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);

/*//////////////////////////////////////////////////////////////////////////
                                    CONSTANTS
//////////////////////////////////////////////////////////////////////////*/

/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;

/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;

/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;

/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;

/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;

/*//////////////////////////////////////////////////////////////////////////
                                    FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
    unchecked {
        // Start from 0.5 in the 192.64-bit fixed-point format.
        result = 0x800000000000000000000000000000000000000000000000;

        // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
        //
        // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
        // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
        // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
        // we know that `x & 0xFF` is also 1.
        if (x & 0xFF00000000000000 > 0) {
            if (x & 0x8000000000000000 > 0) {
                result = (result * 0x16A09E667F3BCC909) >> 64;
            }
            if (x & 0x4000000000000000 > 0) {
                result = (result * 0x1306FE0A31B7152DF) >> 64;
            }
            if (x & 0x2000000000000000 > 0) {
                result = (result * 0x1172B83C7D517ADCE) >> 64;
            }
            if (x & 0x1000000000000000 > 0) {
                result = (result * 0x10B5586CF9890F62A) >> 64;
            }
            if (x & 0x800000000000000 > 0) {
                result = (result * 0x1059B0D31585743AE) >> 64;
            }
            if (x & 0x400000000000000 > 0) {
                result = (result * 0x102C9A3E778060EE7) >> 64;
            }
            if (x & 0x200000000000000 > 0) {
                result = (result * 0x10163DA9FB33356D8) >> 64;
            }
            if (x & 0x100000000000000 > 0) {
                result = (result * 0x100B1AFA5ABCBED61) >> 64;
            }
        }

        if (x & 0xFF000000000000 > 0) {
            if (x & 0x80000000000000 > 0) {
                result = (result * 0x10058C86DA1C09EA2) >> 64;
            }
            if (x & 0x40000000000000 > 0) {
                result = (result * 0x1002C605E2E8CEC50) >> 64;
            }
            if (x & 0x20000000000000 > 0) {
                result = (result * 0x100162F3904051FA1) >> 64;
            }
            if (x & 0x10000000000000 > 0) {
                result = (result * 0x1000B175EFFDC76BA) >> 64;
            }
            if (x & 0x8000000000000 > 0) {
                result = (result * 0x100058BA01FB9F96D) >> 64;
            }
            if (x & 0x4000000000000 > 0) {
                result = (result * 0x10002C5CC37DA9492) >> 64;
            }
            if (x & 0x2000000000000 > 0) {
                result = (result * 0x1000162E525EE0547) >> 64;
            }
            if (x & 0x1000000000000 > 0) {
                result = (result * 0x10000B17255775C04) >> 64;
            }
        }

        if (x & 0xFF0000000000 > 0) {
            if (x & 0x800000000000 > 0) {
                result = (result * 0x1000058B91B5BC9AE) >> 64;
            }
            if (x & 0x400000000000 > 0) {
                result = (result * 0x100002C5C89D5EC6D) >> 64;
            }
            if (x & 0x200000000000 > 0) {
                result = (result * 0x10000162E43F4F831) >> 64;
            }
            if (x & 0x100000000000 > 0) {
                result = (result * 0x100000B1721BCFC9A) >> 64;
            }
            if (x & 0x80000000000 > 0) {
                result = (result * 0x10000058B90CF1E6E) >> 64;
            }
            if (x & 0x40000000000 > 0) {
                result = (result * 0x1000002C5C863B73F) >> 64;
            }
            if (x & 0x20000000000 > 0) {
                result = (result * 0x100000162E430E5A2) >> 64;
            }
            if (x & 0x10000000000 > 0) {
                result = (result * 0x1000000B172183551) >> 64;
            }
        }

        if (x & 0xFF00000000 > 0) {
            if (x & 0x8000000000 > 0) {
                result = (result * 0x100000058B90C0B49) >> 64;
            }
            if (x & 0x4000000000 > 0) {
                result = (result * 0x10000002C5C8601CC) >> 64;
            }
            if (x & 0x2000000000 > 0) {
                result = (result * 0x1000000162E42FFF0) >> 64;
            }
            if (x & 0x1000000000 > 0) {
                result = (result * 0x10000000B17217FBB) >> 64;
            }
            if (x & 0x800000000 > 0) {
                result = (result * 0x1000000058B90BFCE) >> 64;
            }
            if (x & 0x400000000 > 0) {
                result = (result * 0x100000002C5C85FE3) >> 64;
            }
            if (x & 0x200000000 > 0) {
                result = (result * 0x10000000162E42FF1) >> 64;
            }
            if (x & 0x100000000 > 0) {
                result = (result * 0x100000000B17217F8) >> 64;
            }
        }

        if (x & 0xFF000000 > 0) {
            if (x & 0x80000000 > 0) {
                result = (result * 0x10000000058B90BFC) >> 64;
            }
            if (x & 0x40000000 > 0) {
                result = (result * 0x1000000002C5C85FE) >> 64;
            }
            if (x & 0x20000000 > 0) {
                result = (result * 0x100000000162E42FF) >> 64;
            }
            if (x & 0x10000000 > 0) {
                result = (result * 0x1000000000B17217F) >> 64;
            }
            if (x & 0x8000000 > 0) {
                result = (result * 0x100000000058B90C0) >> 64;
            }
            if (x & 0x4000000 > 0) {
                result = (result * 0x10000000002C5C860) >> 64;
            }
            if (x & 0x2000000 > 0) {
                result = (result * 0x1000000000162E430) >> 64;
            }
            if (x & 0x1000000 > 0) {
                result = (result * 0x10000000000B17218) >> 64;
            }
        }

        if (x & 0xFF0000 > 0) {
            if (x & 0x800000 > 0) {
                result = (result * 0x1000000000058B90C) >> 64;
            }
            if (x & 0x400000 > 0) {
                result = (result * 0x100000000002C5C86) >> 64;
            }
            if (x & 0x200000 > 0) {
                result = (result * 0x10000000000162E43) >> 64;
            }
            if (x & 0x100000 > 0) {
                result = (result * 0x100000000000B1721) >> 64;
            }
            if (x & 0x80000 > 0) {
                result = (result * 0x10000000000058B91) >> 64;
            }
            if (x & 0x40000 > 0) {
                result = (result * 0x1000000000002C5C8) >> 64;
            }
            if (x & 0x20000 > 0) {
                result = (result * 0x100000000000162E4) >> 64;
            }
            if (x & 0x10000 > 0) {
                result = (result * 0x1000000000000B172) >> 64;
            }
        }

        if (x & 0xFF00 > 0) {
            if (x & 0x8000 > 0) {
                result = (result * 0x100000000000058B9) >> 64;
            }
            if (x & 0x4000 > 0) {
                result = (result * 0x10000000000002C5D) >> 64;
            }
            if (x & 0x2000 > 0) {
                result = (result * 0x1000000000000162E) >> 64;
            }
            if (x & 0x1000 > 0) {
                result = (result * 0x10000000000000B17) >> 64;
            }
            if (x & 0x800 > 0) {
                result = (result * 0x1000000000000058C) >> 64;
            }
            if (x & 0x400 > 0) {
                result = (result * 0x100000000000002C6) >> 64;
            }
            if (x & 0x200 > 0) {
                result = (result * 0x10000000000000163) >> 64;
            }
            if (x & 0x100 > 0) {
                result = (result * 0x100000000000000B1) >> 64;
            }
        }

        if (x & 0xFF > 0) {
            if (x & 0x80 > 0) {
                result = (result * 0x10000000000000059) >> 64;
            }
            if (x & 0x40 > 0) {
                result = (result * 0x1000000000000002C) >> 64;
            }
            if (x & 0x20 > 0) {
                result = (result * 0x10000000000000016) >> 64;
            }
            if (x & 0x10 > 0) {
                result = (result * 0x1000000000000000B) >> 64;
            }
            if (x & 0x8 > 0) {
                result = (result * 0x10000000000000006) >> 64;
            }
            if (x & 0x4 > 0) {
                result = (result * 0x10000000000000003) >> 64;
            }
            if (x & 0x2 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
            if (x & 0x1 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
        }

        // In the code snippet below, two operations are executed simultaneously:
        //
        // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
        // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
        // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
        //
        // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
        // integer part, $2^n$.
        result *= UNIT;
        result >>= (191 - (x >> 64));
    }
}

/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
///     x >>= 128;
///     result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
    // 2^128
    assembly ("memory-safe") {
        let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^64
    assembly ("memory-safe") {
        let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^32
    assembly ("memory-safe") {
        let factor := shl(5, gt(x, 0xFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^16
    assembly ("memory-safe") {
        let factor := shl(4, gt(x, 0xFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^8
    assembly ("memory-safe") {
        let factor := shl(3, gt(x, 0xFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^4
    assembly ("memory-safe") {
        let factor := shl(2, gt(x, 0xF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^2
    assembly ("memory-safe") {
        let factor := shl(1, gt(x, 0x3))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^1
    // No need to shift x any more.
    assembly ("memory-safe") {
        let factor := gt(x, 0x1)
        result := or(result, factor)
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
    // use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256
    // variables such that product = prod1 * 2^256 + prod0.
    uint256 prod0; // Least significant 256 bits of the product
    uint256 prod1; // Most significant 256 bits of the product
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    // Handle non-overflow cases, 256 by 256 division.
    if (prod1 == 0) {
        unchecked {
            return prod0 / denominator;
        }
    }

    // Make sure the result is less than 2^256. Also prevents denominator == 0.
    if (prod1 >= denominator) {
        revert PRBMath_MulDiv_Overflow(x, y, denominator);
    }

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

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

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

    unchecked {
        // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
        // because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
        // For more detail, see https://cs.stackexchange.com/q/138556/92363.
        uint256 lpotdod = denominator & (~denominator + 1);
        uint256 flippedLpotdod;

        assembly ("memory-safe") {
            // Factor powers of two out of denominator.
            denominator := div(denominator, lpotdod)

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

            // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
            // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
            // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
            flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
        }

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

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

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

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

/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
///     x * y = MAX\_UINT256 * UNIT \\
///     (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
    uint256 prod0;
    uint256 prod1;
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    if (prod1 == 0) {
        unchecked {
            return prod0 / UNIT;
        }
    }

    if (prod1 >= UNIT) {
        revert PRBMath_MulDiv18_Overflow(x, y);
    }

    uint256 remainder;
    assembly ("memory-safe") {
        remainder := mulmod(x, y, UNIT)
        result :=
            mul(
                or(
                    div(sub(prod0, remainder), UNIT_LPOTD),
                    mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
                ),
                UNIT_INVERSE
            )
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
    if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
        revert PRBMath_MulDivSigned_InputTooSmall();
    }

    // Get hold of the absolute values of x, y and the denominator.
    uint256 xAbs;
    uint256 yAbs;
    uint256 dAbs;
    unchecked {
        xAbs = x < 0 ? uint256(-x) : uint256(x);
        yAbs = y < 0 ? uint256(-y) : uint256(y);
        dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
    }

    // Compute the absolute value of x*y÷denominator. The result must fit in int256.
    uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
    if (resultAbs > uint256(type(int256).max)) {
        revert PRBMath_MulDivSigned_Overflow(x, y);
    }

    // Get the signs of x, y and the denominator.
    uint256 sx;
    uint256 sy;
    uint256 sd;
    assembly ("memory-safe") {
        // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
        sx := sgt(x, sub(0, 1))
        sy := sgt(y, sub(0, 1))
        sd := sgt(denominator, sub(0, 1))
    }

    // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
    // If there are, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
    }
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
    if (x == 0) {
        return 0;
    }

    // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
    //
    // We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
    //
    // $$
    // msb(x) <= x <= 2*msb(x)$
    // $$
    //
    // We write $msb(x)$ as $2^k$, and we get:
    //
    // $$
    // k = log_2(x)
    // $$
    //
    // Thus, we can write the initial inequality as:
    //
    // $$
    // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
    // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
    // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
    // $$
    //
    // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
    uint256 xAux = uint256(x);
    result = 1;
    if (xAux >= 2 ** 128) {
        xAux >>= 128;
        result <<= 64;
    }
    if (xAux >= 2 ** 64) {
        xAux >>= 64;
        result <<= 32;
    }
    if (xAux >= 2 ** 32) {
        xAux >>= 32;
        result <<= 16;
    }
    if (xAux >= 2 ** 16) {
        xAux >>= 16;
        result <<= 8;
    }
    if (xAux >= 2 ** 8) {
        xAux >>= 8;
        result <<= 4;
    }
    if (xAux >= 2 ** 4) {
        xAux >>= 4;
        result <<= 2;
    }
    if (xAux >= 2 ** 2) {
        result <<= 1;
    }

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

        // If x is not a perfect square, round the result toward zero.
        uint256 roundedResult = x / result;
        if (result >= roundedResult) {
            result = roundedResult;
        }
    }
}

File 20 of 76 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    error T();
    error R();

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert T();

            uint256 ratio = absTick & 0x1 != 0
                ? 0xfffcb933bd6fad37aa2d162d1a594001
                : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

            if (tick > 0) ratio = type(uint256).max / ratio;

            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // second inequality must be < because the price can never reach the price at the max tick
            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
            uint256 ratio = uint256(sqrtPriceX96) << 32;

            uint256 r = ratio;
            uint256 msb = 0;

            assembly {
                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(5, gt(r, 0xFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(4, gt(r, 0xFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(3, gt(r, 0xFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(2, gt(r, 0xF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(1, gt(r, 0x3))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := gt(r, 0x1)
                msb := or(msb, f)
            }

            if (msb >= 128) r = ratio >> (msb - 127);
            else r = ratio << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

File 21 of 76 : OracleLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;

import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
    /// @param pool Address of the pool that we want to observe
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(address pool, uint32 secondsAgo)
        internal
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, 'BP');

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = IUniswapV3Pool(pool)
            .observe(secondsAgos);

        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[1] -
            secondsPerLiquidityCumulativeX128s[0];

        arithmeticMeanTick = int24(tickCumulativesDelta / int56(uint56(secondsAgo)));
        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)) arithmeticMeanTick--;

        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
    /// @param pool Address of Uniswap V3 pool that we want to observe
    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
        require(observationCardinality > 0, 'NI');

        (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations(
            (observationIndex + 1) % observationCardinality
        );

        // The next index might not be initialized if the cardinality is in the process of increasing
        // In this case the oldest observation is always in index 0
        if (!initialized) {
            (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
        }

        unchecked {
            secondsAgo = uint32(block.timestamp) - observationTimestamp;
        }
    }

    /// @notice Given a pool, it returns the tick value as of the start of the current block
    /// @param pool Address of Uniswap V3 pool
    /// @return The tick that the pool was in at the start of the current block
    function getBlockStartingTickAndLiquidity(address pool) internal view returns (int24, uint128) {
        (, int24 tick, uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();

        // 2 observations are needed to reliably calculate the block starting tick
        require(observationCardinality > 1, 'NEO');

        // If the latest observation occurred in the past, then no tick-changing trades have happened in this block
        // therefore the tick in `slot0` is the same as at the beginning of the current block.
        // We don't need to check if this observation is initialized - it is guaranteed to be.
        (
            uint32 observationTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,

        ) = IUniswapV3Pool(pool).observations(observationIndex);
        if (observationTimestamp != uint32(block.timestamp)) {
            return (tick, IUniswapV3Pool(pool).liquidity());
        }

        uint256 prevIndex = (uint256(observationIndex) + observationCardinality - 1) % observationCardinality;
        (
            uint32 prevObservationTimestamp,
            int56 prevTickCumulative,
            uint160 prevSecondsPerLiquidityCumulativeX128,
            bool prevInitialized
        ) = IUniswapV3Pool(pool).observations(prevIndex);

        require(prevInitialized, 'ONI');

        uint32 delta = observationTimestamp - prevObservationTimestamp;
        tick = int24((tickCumulative - int56(uint56(prevTickCumulative))) / int56(uint56(delta)));
        uint128 liquidity = uint128(
            (uint192(delta) * type(uint160).max) /
                (uint192(secondsPerLiquidityCumulativeX128 - prevSecondsPerLiquidityCumulativeX128) << 32)
        );
        return (tick, liquidity);
    }

    /// @notice Information for calculating a weighted arithmetic mean tick
    struct WeightedTickData {
        int24 tick;
        uint128 weight;
    }

    /// @notice Given an array of ticks and weights, calculates the weighted arithmetic mean tick
    /// @param weightedTickData An array of ticks and weights
    /// @return weightedArithmeticMeanTick The weighted arithmetic mean tick
    /// @dev Each entry of `weightedTickData` should represents ticks from pools with the same underlying pool tokens. If they do not,
    /// extreme care must be taken to ensure that ticks are comparable (including decimal differences).
    /// @dev Note that the weighted arithmetic mean tick corresponds to the weighted geometric mean price.
    function getWeightedArithmeticMeanTick(WeightedTickData[] memory weightedTickData)
        internal
        pure
        returns (int24 weightedArithmeticMeanTick)
    {
        // Accumulates the sum of products between each tick and its weight
        int256 numerator;

        // Accumulates the sum of the weights
        uint256 denominator;

        // Products fit in 152 bits, so it would take an array of length ~2**104 to overflow this logic
        for (uint256 i; i < weightedTickData.length; i++) {
            numerator += weightedTickData[i].tick * int256(uint256(weightedTickData[i].weight));
            denominator += weightedTickData[i].weight;
        }

        weightedArithmeticMeanTick = int24(numerator / int256(denominator));
        // Always round to negative infinity
        if (numerator < 0 && (numerator % int256(denominator) != 0)) weightedArithmeticMeanTick--;
    }

    /// @notice Returns the "synthetic" tick which represents the price of the first entry in `tokens` in terms of the last
    /// @dev Useful for calculating relative prices along routes.
    /// @dev There must be one tick for each pairwise set of tokens.
    /// @param tokens The token contract addresses
    /// @param ticks The ticks, representing the price of each token pair in `tokens`
    /// @return syntheticTick The synthetic tick, representing the relative price of the outermost tokens in `tokens`
    function getChainedPrice(address[] memory tokens, int24[] memory ticks)
        internal
        pure
        returns (int256 syntheticTick)
    {
        require(tokens.length - 1 == ticks.length, 'DL');
        for (uint256 i = 1; i <= ticks.length; i++) {
            // check the tokens for address sort order, then accumulate the
            // ticks into the running synthetic tick, ensuring that intermediate tokens "cancel out"
            tokens[i - 1] < tokens[i] ? syntheticTick += ticks[i - 1] : syntheticTick -= ticks[i - 1];
        }
    }
}

File 22 of 76 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolErrors,
    IUniswapV3PoolEvents
{

}

File 23 of 76 : JBBuybackDelegateOperations.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title JBBuybackDelegateOperations
/// @notice JB specific operation indexes for the JBBuybackDelegate
library JBBuybackDelegateOperations {
    // [0..18] - JBOperations
    // 19 - JBOperations2 (ENS/Handle)
    // 20 - JBUriOperations (Set token URI)
    // [21..23] - JB721Operations

    uint256 public constant SET_POOL_PARAMS = 24;
    uint256 public constant CHANGE_POOL = 25;
}

File 24 of 76 : IJBBuybackDelegate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IJBPayDelegate3_1_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBPayDelegate3_1_1.sol";
import {IJBFundingCycleDataSource3_1_1} from
    "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBFundingCycleDataSource3_1_1.sol";
import {IJBDirectory} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBDirectory.sol";
import {IJBController3_1} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBController3_1.sol";
import {IJBProjects} from "@jbx-protocol/juice-contracts-v3/contracts/interfaces/IJBProjects.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";

import {IWETH9} from "./external/IWETH9.sol";

interface IJBBuybackDelegate is IJBPayDelegate3_1_1, IJBFundingCycleDataSource3_1_1, IUniswapV3SwapCallback {
    /////////////////////////////////////////////////////////////////////
    //                             Errors                              //
    /////////////////////////////////////////////////////////////////////

    error JuiceBuyback_MaximumSlippage();
    error JuiceBuyback_InsufficientPayAmount();
    error JuiceBuyback_NotEnoughTokensReceived();
    error JuiceBuyback_NewSecondsAgoTooLow();
    error JuiceBuyback_NoProjectToken();
    error JuiceBuyback_PoolAlreadySet();
    error JuiceBuyback_TransferFailed();
    error JuiceBuyback_InvalidTwapSlippageTolerance();
    error JuiceBuyback_InvalidTwapWindow();
    error JuiceBuyback_Unauthorized();

    /////////////////////////////////////////////////////////////////////
    //                             Events                              //
    /////////////////////////////////////////////////////////////////////

    event BuybackDelegate_Swap(uint256 indexed projectId, uint256 amountIn, IUniswapV3Pool pool, uint256 amountOut, address caller);
    event BuybackDelegate_Mint(uint256 indexed projectId, uint256 amountIn, uint256 tokenCount, address caller);
    event BuybackDelegate_TwapWindowChanged(uint256 indexed projectId, uint256 oldSecondsAgo, uint256 newSecondsAgo, address caller);
    event BuybackDelegate_TwapSlippageToleranceChanged(uint256 indexed projectId, uint256 oldTwapDelta, uint256 newTwapDelta, address caller);
    event BuybackDelegate_PoolAdded(uint256 indexed projectId, address indexed terminalToken, address newPool, address caller);

    /////////////////////////////////////////////////////////////////////
    //                             Getters                             //
    /////////////////////////////////////////////////////////////////////

    function SLIPPAGE_DENOMINATOR() external view returns (uint256);
    function MIN_TWAP_SLIPPAGE_TOLERANCE() external view returns (uint256);
    function MAX_TWAP_SLIPPAGE_TOLERANCE() external view returns (uint256);
    function MIN_TWAP_WINDOW() external view returns (uint256);
    function MAX_TWAP_WINDOW() external view returns (uint256);
    function UNISWAP_V3_FACTORY() external view returns (address);
    function DIRECTORY() external view returns (IJBDirectory);
    function CONTROLLER() external view returns (IJBController3_1);
    function PROJECTS() external view returns (IJBProjects);
    function WETH() external view returns (IWETH9);
    function DELEGATE_ID() external view returns (bytes4);
    function poolOf(uint256 projectId, address terminalToken) external view returns (IUniswapV3Pool pool);
    function twapWindowOf(uint256 projectId) external view returns (uint32 window);
    function twapSlippageToleranceOf(uint256 projectId) external view returns (uint256 slippageTolerance);
    function projectTokenOf(uint256 projectId) external view returns (address projectTokenOf);

    /////////////////////////////////////////////////////////////////////
    //                    State-changing functions                     //
    /////////////////////////////////////////////////////////////////////

    function setPoolFor(uint256 projectId, uint24 fee, uint32 twapWindow, uint256 twapSlippageTolerance, address terminalToken)
        external
        returns (IUniswapV3Pool newPool);

    function setTwapWindowOf(uint256 projectId, uint32 newWindow) external;

    function setTwapSlippageToleranceOf(uint256 projectId, uint256 newSlippageTolerance) external;
}

File 25 of 76 : IWETH9.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

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

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

File 26 of 76 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

File 27 of 76 : JBFee.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @custom:member amount The total amount the fee was taken from, as a fixed point number with the same number of decimals as the terminal in which this struct was created.
/// @custom:member fee The percent of the fee, out of MAX_FEE.
/// @custom:member feeDiscount The discount of the fee.
/// @custom:member beneficiary The address that will receive the tokens that are minted as a result of the fee payment.
struct JBFee {
  uint256 amount;
  uint32 fee;
  uint32 feeDiscount;
  address beneficiary;
}

File 28 of 76 : JBDidRedeemData3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBTokenAmount} from './JBTokenAmount.sol';

/// @custom:member holder The holder of the tokens being redeemed.
/// @custom:member projectId The ID of the project with which the redeemed tokens are associated.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the redemption is being made.
/// @custom:member projectTokenCount The number of project tokens being redeemed.
/// @custom:member reclaimedAmount The amount reclaimed from the treasury. Includes the token being reclaimed, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member beneficiary The address to which the reclaimed amount will be sent.
/// @custom:member memo The memo that is being emitted alongside the redemption.
/// @custom:member dataSourceMetadata Extra data to send to the delegate sent by the data source.
/// @custom:member redeemerMetadata Extra data to send to the delegate sent by the redeemer.
struct JBDidRedeemData3_1_1 {
  address holder;
  uint256 projectId;
  uint256 currentFundingCycleConfiguration;
  uint256 projectTokenCount;
  JBTokenAmount reclaimedAmount;
  JBTokenAmount forwardedAmount;
  address payable beneficiary;
  string memo;
  bytes dataSourceMetadata;
  bytes redeemerMetadata;
}

File 29 of 76 : IJBRedemptionDelegate3_1_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidRedeemData3_1_1} from './../structs/JBDidRedeemData3_1_1.sol';

/// @title Redemption delegate
/// @notice Delegate called after JBTerminal.redeemTokensOf(..) logic completion (if passed by the funding cycle datasource)
interface IJBRedemptionDelegate3_1_1 is IERC165 {
  /// @notice This function is called by JBPaymentTerminal.redeemTokensOf(..), after the execution of its logic
  /// @dev Critical business logic should be protected by an appropriate access control
  /// @param data the data passed by the terminal, as a JBDidRedeemData struct:
  function didRedeem(JBDidRedeemData3_1_1 calldata data) external payable;
}

File 30 of 76 : IJBPayoutRedemptionPaymentTerminal3_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBFee} from './../structs/JBFee.sol';
import {IJBAllowanceTerminal3_1} from './IJBAllowanceTerminal3_1.sol';
import {IJBDirectory} from './IJBDirectory.sol';
import {IJBFeeHoldingTerminal} from './IJBFeeHoldingTerminal.sol';
import {IJBPayDelegate} from './IJBPayDelegate.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';
import {IJBPayoutTerminal3_1} from './IJBPayoutTerminal3_1.sol';
import {IJBPrices} from './IJBPrices.sol';
import {IJBProjects} from './IJBProjects.sol';
import {IJBRedemptionDelegate} from './IJBRedemptionDelegate.sol';
import {IJBRedemptionTerminal} from './IJBRedemptionTerminal.sol';
import {IJBSplitsStore} from './IJBSplitsStore.sol';
import {JBDidPayData} from './../structs/JBDidPayData.sol';
import {JBDidRedeemData} from './../structs/JBDidRedeemData.sol';
import {JBSplit} from './../structs/JBSplit.sol';

interface IJBPayoutRedemptionPaymentTerminal3_1 is
  IJBPaymentTerminal,
  IJBPayoutTerminal3_1,
  IJBAllowanceTerminal3_1,
  IJBRedemptionTerminal,
  IJBFeeHoldingTerminal
{
  event AddToBalance(
    uint256 indexed projectId,
    uint256 amount,
    uint256 refundedFees,
    string memo,
    bytes metadata,
    address caller
  );

  event Migrate(
    uint256 indexed projectId,
    IJBPaymentTerminal indexed to,
    uint256 amount,
    address caller
  );

  event DistributePayouts(
    uint256 indexed fundingCycleConfiguration,
    uint256 indexed fundingCycleNumber,
    uint256 indexed projectId,
    address beneficiary,
    uint256 amount,
    uint256 distributedAmount,
    uint256 fee,
    uint256 beneficiaryDistributionAmount,
    bytes metadata,
    address caller
  );

  event UseAllowance(
    uint256 indexed fundingCycleConfiguration,
    uint256 indexed fundingCycleNumber,
    uint256 indexed projectId,
    address beneficiary,
    uint256 amount,
    uint256 distributedAmount,
    uint256 netDistributedamount,
    string memo,
    bytes metadata,
    address caller
  );

  event HoldFee(
    uint256 indexed projectId,
    uint256 indexed amount,
    uint256 indexed fee,
    uint256 feeDiscount,
    address beneficiary,
    address caller
  );

  event ProcessFee(
    uint256 indexed projectId,
    uint256 indexed amount,
    bool indexed wasHeld,
    address beneficiary,
    address caller
  );

  event RefundHeldFees(
    uint256 indexed projectId,
    uint256 indexed amount,
    uint256 indexed refundedFees,
    uint256 leftoverAmount,
    address caller
  );

  event Pay(
    uint256 indexed fundingCycleConfiguration,
    uint256 indexed fundingCycleNumber,
    uint256 indexed projectId,
    address payer,
    address beneficiary,
    uint256 amount,
    uint256 beneficiaryTokenCount,
    string memo,
    bytes metadata,
    address caller
  );

  event DelegateDidPay(
    IJBPayDelegate indexed delegate,
    JBDidPayData data,
    uint256 delegatedAmount,
    address caller
  );

  event RedeemTokens(
    uint256 indexed fundingCycleConfiguration,
    uint256 indexed fundingCycleNumber,
    uint256 indexed projectId,
    address holder,
    address beneficiary,
    uint256 tokenCount,
    uint256 reclaimedAmount,
    string memo,
    bytes metadata,
    address caller
  );

  event DelegateDidRedeem(
    IJBRedemptionDelegate indexed delegate,
    JBDidRedeemData data,
    uint256 delegatedAmount,
    address caller
  );

  event DistributeToPayoutSplit(
    uint256 indexed projectId,
    uint256 indexed domain,
    uint256 indexed group,
    JBSplit split,
    uint256 amount,
    uint256 netAmount,
    address caller
  );

  event SetFee(uint256 fee, address caller);

  event SetFeeGauge(address indexed feeGauge, address caller);

  event SetFeelessAddress(address indexed addrs, bool indexed flag, address caller);

  event PayoutReverted(
    uint256 indexed projectId,
    JBSplit split,
    uint256 amount,
    bytes reason,
    address caller
  );

  event FeeReverted(
    uint256 indexed projectId,
    uint256 indexed feeProjectId,
    uint256 amount,
    bytes reason,
    address caller
  );

  function projects() external view returns (IJBProjects);

  function splitsStore() external view returns (IJBSplitsStore);

  function directory() external view returns (IJBDirectory);

  function prices() external view returns (IJBPrices);

  function store() external view returns (address);

  function baseWeightCurrency() external view returns (uint256);

  function payoutSplitsGroup() external view returns (uint256);

  function heldFeesOf(uint256 projectId) external view returns (JBFee[] memory);

  function fee() external view returns (uint256);

  function feeGauge() external view returns (address);

  function isFeelessAddress(address account) external view returns (bool);

  function migrate(uint256 projectId, IJBPaymentTerminal to) external returns (uint256 balance);

  function processFees(uint256 projectId) external;

  function setFee(uint256 fee) external;

  function setFeeGauge(address feeGauge) external;

  function setFeelessAddress(address account, bool flag) external;
}

File 31 of 76 : JBTokenAmount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @custom:member token The token the payment was made in.
/// @custom:member value The amount of tokens that was paid, as a fixed point number.
/// @custom:member decimals The number of decimals included in the value fixed point number.
/// @custom:member currency The expected currency of the value.
struct JBTokenAmount {
  address token;
  uint256 value;
  uint256 decimals;
  uint256 currency;
}

File 32 of 76 : IJBOperatorStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBOperatorData} from './../structs/JBOperatorData.sol';

interface IJBOperatorStore {
  event SetOperator(
    address indexed operator,
    address indexed account,
    uint256 indexed domain,
    uint256[] permissionIndexes,
    uint256 packed
  );

  function permissionsOf(
    address operator,
    address account,
    uint256 domain
  ) external view returns (uint256);

  function hasPermission(
    address operator,
    address account,
    uint256 domain,
    uint256 permissionIndex
  ) external view returns (bool);

  function hasPermissions(
    address operator,
    address account,
    uint256 domain,
    uint256[] calldata permissionIndexes
  ) external view returns (bool);

  function setOperator(JBOperatorData calldata operatorData) external;

  function setOperators(JBOperatorData[] calldata operatorData) external;
}

File 33 of 76 : IJBFundingCycleStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBBallotState} from './../enums/JBBallotState.sol';
import {JBFundingCycle} from './../structs/JBFundingCycle.sol';
import {JBFundingCycleData} from './../structs/JBFundingCycleData.sol';

interface IJBFundingCycleStore {
  event Configure(
    uint256 indexed configuration,
    uint256 indexed projectId,
    JBFundingCycleData data,
    uint256 metadata,
    uint256 mustStartAtOrAfter,
    address caller
  );

  event Init(uint256 indexed configuration, uint256 indexed projectId, uint256 indexed basedOn);

  function latestConfigurationOf(uint256 projectId) external view returns (uint256);

  function get(
    uint256 projectId,
    uint256 configuration
  ) external view returns (JBFundingCycle memory);

  function latestConfiguredOf(
    uint256 projectId
  ) external view returns (JBFundingCycle memory fundingCycle, JBBallotState ballotState);

  function queuedOf(uint256 projectId) external view returns (JBFundingCycle memory fundingCycle);

  function currentOf(uint256 projectId) external view returns (JBFundingCycle memory fundingCycle);

  function currentBallotStateOf(uint256 projectId) external view returns (JBBallotState);

  function configureFor(
    uint256 projectId,
    JBFundingCycleData calldata data,
    uint256 metadata,
    uint256 mustStartAtOrAfter
  ) external returns (JBFundingCycle memory fundingCycle);
}

File 34 of 76 : IJBProjects.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {JBProjectMetadata} from './../structs/JBProjectMetadata.sol';
import {IJBTokenUriResolver} from './IJBTokenUriResolver.sol';

interface IJBProjects is IERC721 {
  event Create(
    uint256 indexed projectId,
    address indexed owner,
    JBProjectMetadata metadata,
    address caller
  );

  event SetMetadata(uint256 indexed projectId, JBProjectMetadata metadata, address caller);

  event SetTokenUriResolver(IJBTokenUriResolver indexed resolver, address caller);

  function count() external view returns (uint256);

  function metadataContentOf(
    uint256 projectId,
    uint256 domain
  ) external view returns (string memory);

  function tokenUriResolver() external view returns (IJBTokenUriResolver);

  function createFor(
    address owner,
    JBProjectMetadata calldata metadata
  ) external returns (uint256 projectId);

  function setMetadataOf(uint256 projectId, JBProjectMetadata calldata metadata) external;

  function setTokenUriResolver(IJBTokenUriResolver newResolver) external;
}

File 35 of 76 : JBBallotState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

enum JBBallotState {
  Active,
  Approved,
  Failed
}

File 36 of 76 : JBFundAccessConstraints.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBPaymentTerminal} from './../interfaces/IJBPaymentTerminal.sol';

/// @custom:member terminal The terminal within which the distribution limit and the overflow allowance applies.
/// @custom:member token The token for which the fund access constraints apply.
/// @custom:member distributionLimit The amount of the distribution limit, as a fixed point number with the same number of decimals as the terminal within which the limit applies.
/// @custom:member distributionLimitCurrency The currency of the distribution limit.
/// @custom:member overflowAllowance The amount of the allowance, as a fixed point number with the same number of decimals as the terminal within which the allowance applies.
/// @custom:member overflowAllowanceCurrency The currency of the overflow allowance.
struct JBFundAccessConstraints {
  IJBPaymentTerminal terminal;
  address token;
  uint256 distributionLimit;
  uint256 distributionLimitCurrency;
  uint256 overflowAllowance;
  uint256 overflowAllowanceCurrency;
}

File 37 of 76 : JBFundingCycle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBFundingCycleBallot} from './../interfaces/IJBFundingCycleBallot.sol';

/// @custom:member number The funding cycle number for the cycle's project. Each funding cycle has a number that is an increment of the cycle that directly preceded it. Each project's first funding cycle has a number of 1.
/// @custom:member configuration The timestamp when the parameters for this funding cycle were configured. This value will stay the same for subsequent funding cycles that roll over from an originally configured cycle.
/// @custom:member basedOn The `configuration` of the funding cycle that was active when this cycle was created.
/// @custom:member start The timestamp marking the moment from which the funding cycle is considered active. It is a unix timestamp measured in seconds.
/// @custom:member duration The number of seconds the funding cycle lasts for, after which a new funding cycle will start. A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties. If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle. If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
/// @custom:member weight A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on. For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
/// @custom:member discountRate A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`. If it's 0, each funding cycle will have equal weight. If the number is 90%, the next funding cycle will have a 10% smaller weight. This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
/// @custom:member ballot An address of a contract that says whether a proposed reconfiguration should be accepted or rejected. It can be used to create rules around how a project owner can change funding cycle parameters over time.
/// @custom:member metadata Extra data that can be associated with a funding cycle.
struct JBFundingCycle {
  uint256 number;
  uint256 configuration;
  uint256 basedOn;
  uint256 start;
  uint256 duration;
  uint256 weight;
  uint256 discountRate;
  IJBFundingCycleBallot ballot;
  uint256 metadata;
}

File 38 of 76 : JBFundingCycleData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBFundingCycleBallot} from './../interfaces/IJBFundingCycleBallot.sol';

/// @custom:member duration The number of seconds the funding cycle lasts for, after which a new funding cycle will start. A duration of 0 means that the funding cycle will stay active until the project owner explicitly issues a reconfiguration, at which point a new funding cycle will immediately start with the updated properties. If the duration is greater than 0, a project owner cannot make changes to a funding cycle's parameters while it is active – any proposed changes will apply to the subsequent cycle. If no changes are proposed, a funding cycle rolls over to another one with the same properties but new `start` timestamp and a discounted `weight`.
/// @custom:member weight A fixed point number with 18 decimals that contracts can use to base arbitrary calculations on. For example, payment terminals can use this to determine how many tokens should be minted when a payment is received.
/// @custom:member discountRate A percent by how much the `weight` of the subsequent funding cycle should be reduced, if the project owner hasn't configured the subsequent funding cycle with an explicit `weight`. If it's 0, each funding cycle will have equal weight. If the number is 90%, the next funding cycle will have a 10% smaller weight. This weight is out of `JBConstants.MAX_DISCOUNT_RATE`.
/// @custom:member ballot An address of a contract that says whether a proposed reconfiguration should be accepted or rejected. It can be used to create rules around how a project owner can change funding cycle parameters over time.
struct JBFundingCycleData {
  uint256 duration;
  uint256 weight;
  uint256 discountRate;
  IJBFundingCycleBallot ballot;
}

File 39 of 76 : JBFundingCycleMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBGlobalFundingCycleMetadata} from './JBGlobalFundingCycleMetadata.sol';

/// @custom:member global Data used globally in non-migratable ecosystem contracts.
/// @custom:member reservedRate The reserved rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_RESERVED_RATE`.
/// @custom:member redemptionRate The redemption rate of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
/// @custom:member ballotRedemptionRate The redemption rate to use during an active ballot of the funding cycle. This number is a percentage calculated out of `JBConstants.MAX_REDEMPTION_RATE`.
/// @custom:member pausePay A flag indicating if the pay functionality should be paused during the funding cycle.
/// @custom:member pauseDistributions A flag indicating if the distribute functionality should be paused during the funding cycle.
/// @custom:member pauseRedeem A flag indicating if the redeem functionality should be paused during the funding cycle.
/// @custom:member pauseBurn A flag indicating if the burn functionality should be paused during the funding cycle.
/// @custom:member allowMinting A flag indicating if minting tokens should be allowed during this funding cycle.
/// @custom:member allowTerminalMigration A flag indicating if migrating terminals should be allowed during this funding cycle.
/// @custom:member allowControllerMigration A flag indicating if migrating controllers should be allowed during this funding cycle.
/// @custom:member holdFees A flag indicating if fees should be held during this funding cycle.
/// @custom:member preferClaimedTokenOverride A flag indicating if claimed tokens should always be prefered to unclaimed tokens when minting.
/// @custom:member useTotalOverflowForRedemptions A flag indicating if redemptions should use the project's balance held in all terminals instead of the project's local terminal balance from which the redemption is being fulfilled.
/// @custom:member useDataSourceForPay A flag indicating if the data source should be used for pay transactions during this funding cycle.
/// @custom:member useDataSourceForRedeem A flag indicating if the data source should be used for redeem transactions during this funding cycle.
/// @custom:member dataSource The data source to use during this funding cycle.
/// @custom:member metadata Metadata of the metadata, up to uint8 in size.
struct JBFundingCycleMetadata {
  JBGlobalFundingCycleMetadata global;
  uint256 reservedRate;
  uint256 redemptionRate;
  uint256 ballotRedemptionRate;
  bool pausePay;
  bool pauseDistributions;
  bool pauseRedeem;
  bool pauseBurn;
  bool allowMinting;
  bool allowTerminalMigration;
  bool allowControllerMigration;
  bool holdFees;
  bool preferClaimedTokenOverride;
  bool useTotalOverflowForRedemptions;
  bool useDataSourceForPay;
  bool useDataSourceForRedeem;
  address dataSource;
  uint256 metadata;
}

File 40 of 76 : JBGroupedSplits.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBSplit} from './JBSplit.sol';

/// @custom:member group The group indentifier.
/// @custom:member splits The splits to associate with the group.
struct JBGroupedSplits {
  uint256 group;
  JBSplit[] splits;
}

File 41 of 76 : JBProjectMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @custom:member content The metadata content.
/// @custom:member domain The domain within which the metadata applies.
struct JBProjectMetadata {
  string content;
  uint256 domain;
}

File 42 of 76 : JBSplit.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBSplitAllocator} from './../interfaces/IJBSplitAllocator.sol';

/// @custom:member preferClaimed A flag that only has effect if a projectId is also specified, and the project has a token contract attached. If so, this flag indicates if the tokens that result from making a payment to the project should be delivered claimed into the beneficiary's wallet, or unclaimed to save gas.
/// @custom:member preferAddToBalance A flag indicating if a distribution to a project should prefer triggering it's addToBalance function instead of its pay function.
/// @custom:member percent The percent of the whole group that this split occupies. This number is out of `JBConstants.SPLITS_TOTAL_PERCENT`.
/// @custom:member projectId The ID of a project. If an allocator is not set but a projectId is set, funds will be sent to the protocol treasury belonging to the project who's ID is specified. Resulting tokens will be routed to the beneficiary with the claimed token preference respected.
/// @custom:member beneficiary An address. The role the of the beneficary depends on whether or not projectId is specified, and whether or not an allocator is specified. If allocator is set, the beneficiary will be forwarded to the allocator for it to use. If allocator is not set but projectId is set, the beneficiary is the address to which the project's tokens will be sent that result from a payment to it. If neither allocator or projectId are set, the beneficiary is where the funds from the split will be sent.
/// @custom:member lockedUntil Specifies if the split should be unchangeable until the specified time, with the exception of extending the locked period.
/// @custom:member allocator If an allocator is specified, funds will be sent to the allocator contract along with all properties of this split.
struct JBSplit {
  bool preferClaimed;
  bool preferAddToBalance;
  uint256 percent;
  uint256 projectId;
  address payable beneficiary;
  uint256 lockedUntil;
  IJBSplitAllocator allocator;
}

File 43 of 76 : IJBController3_0_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBController3_0_1 {
  function reservedTokenBalanceOf(uint256 projectId) external view returns (uint256);

  function totalOutstandingTokensOf(uint256 projectId) external view returns (uint256);
}

File 44 of 76 : IJBFundAccessConstraintsStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBFundAccessConstraints} from './../structs/JBFundAccessConstraints.sol';
import {IJBPaymentTerminal} from './IJBPaymentTerminal.sol';

interface IJBFundAccessConstraintsStore is IERC165 {
  event SetFundAccessConstraints(
    uint256 indexed fundingCycleConfiguration,
    uint256 indexed projectId,
    JBFundAccessConstraints constraints,
    address caller
  );

  function distributionLimitOf(
    uint256 projectId,
    uint256 configuration,
    IJBPaymentTerminal terminal,
    address token
  ) external view returns (uint256 distributionLimit, uint256 distributionLimitCurrency);

  function overflowAllowanceOf(
    uint256 projectId,
    uint256 configuration,
    IJBPaymentTerminal terminal,
    address token
  ) external view returns (uint256 overflowAllowance, uint256 overflowAllowanceCurrency);

  function setFor(
    uint256 projectId,
    uint256 configuration,
    JBFundAccessConstraints[] memory fundAccessConstaints
  ) external;
}

File 45 of 76 : IJBMigratable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBMigratable {
  function prepForMigrationOf(uint256 projectId, address from) external;
}

File 46 of 76 : IJBSplitsStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBGroupedSplits} from './../structs/JBGroupedSplits.sol';
import {JBSplit} from './../structs/JBSplit.sol';
import {IJBDirectory} from './IJBDirectory.sol';
import {IJBProjects} from './IJBProjects.sol';

interface IJBSplitsStore {
  event SetSplit(
    uint256 indexed projectId,
    uint256 indexed domain,
    uint256 indexed group,
    JBSplit split,
    address caller
  );

  function projects() external view returns (IJBProjects);

  function directory() external view returns (IJBDirectory);

  function splitsOf(
    uint256 projectId,
    uint256 domain,
    uint256 group
  ) external view returns (JBSplit[] memory);

  function set(uint256 projectId, uint256 domain, JBGroupedSplits[] memory groupedSplits) external;
}

File 47 of 76 : IJBTokenStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBFundingCycleStore} from './IJBFundingCycleStore.sol';
import {IJBProjects} from './IJBProjects.sol';
import {IJBToken} from './IJBToken.sol';

interface IJBTokenStore {
  event Issue(
    uint256 indexed projectId,
    IJBToken indexed token,
    string name,
    string symbol,
    address caller
  );

  event Mint(
    address indexed holder,
    uint256 indexed projectId,
    uint256 amount,
    bool tokensWereClaimed,
    bool preferClaimedTokens,
    address caller
  );

  event Burn(
    address indexed holder,
    uint256 indexed projectId,
    uint256 amount,
    uint256 initialUnclaimedBalance,
    uint256 initialClaimedBalance,
    bool preferClaimedTokens,
    address caller
  );

  event Claim(
    address indexed holder,
    uint256 indexed projectId,
    uint256 initialUnclaimedBalance,
    uint256 amount,
    address caller
  );

  event Set(uint256 indexed projectId, IJBToken indexed newToken, address caller);

  event Transfer(
    address indexed holder,
    uint256 indexed projectId,
    address indexed recipient,
    uint256 amount,
    address caller
  );

  function tokenOf(uint256 projectId) external view returns (IJBToken);

  function projects() external view returns (IJBProjects);

  function fundingCycleStore() external view returns (IJBFundingCycleStore);

  function unclaimedBalanceOf(address holder, uint256 projectId) external view returns (uint256);

  function unclaimedTotalSupplyOf(uint256 projectId) external view returns (uint256);

  function totalSupplyOf(uint256 projectId) external view returns (uint256);

  function balanceOf(address holder, uint256 projectId) external view returns (uint256 result);

  function issueFor(
    uint256 projectId,
    string calldata name,
    string calldata symbol
  ) external returns (IJBToken token);

  function setFor(uint256 projectId, IJBToken token) external;

  function burnFrom(
    address holder,
    uint256 projectId,
    uint256 amount,
    bool preferClaimedTokens
  ) external;

  function mintFor(
    address holder,
    uint256 projectId,
    uint256 amount,
    bool preferClaimedTokens
  ) external;

  function claimFor(address holder, uint256 projectId, uint256 amount) external;

  function transferFrom(
    address holder,
    uint256 projectId,
    address recipient,
    uint256 amount
  ) external;
}

File 48 of 76 : JBDelegateMetadataConstants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

// The various sizes used in bytes.
uint256 constant ID_SIZE = 4;
uint256 constant ID_OFFSET_SIZE = 1;
uint256 constant WORD_SIZE = 32;

// The size that a delegate takes in the lookup table (Identifier + Offset).
uint256 constant TOTAL_ID_SIZE = 5; // ID_SIZE + ID_OFFSET_SIZE;

// The amount of bytes to go forward to get to the offset of the next delegate (aka. the end of the offset of the current delegate).
uint256 constant NEXT_DELEGATE_OFFSET = 9; // TOTAL_ID_SIZE + ID_SIZE;

// 1 word (32B) is reserved for the protocol .
uint256 constant RESERVED_SIZE = 32; // 1 * WORD_SIZE;
uint256 constant MIN_METADATA_LENGTH = 37; // RESERVED_SIZE + ID_SIZE + ID_OFFSET_SIZE;

File 49 of 76 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

File 50 of 76 : FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

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

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}

File 51 of 76 : IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

File 52 of 76 : IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// @return observationIndex The index of the last oracle observation that was written,
    /// @return observationCardinality The current maximum number of observations stored in the pool,
    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// @return feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    /// @return The liquidity at the current price of the pool
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper
    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return liquidity The amount of liquidity in the position,
    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// @return initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

File 53 of 76 : IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

File 54 of 76 : IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

File 55 of 76 : IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

File 56 of 76 : IUniswapV3PoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
    error LOK();
    error TLU();
    error TLM();
    error TUM();
    error AI();
    error M0();
    error M1();
    error AS();
    error IIA();
    error L();
    error F0();
    error F1();
}

File 57 of 76 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 58 of 76 : IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 59 of 76 : IJBAllowanceTerminal3_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBAllowanceTerminal3_1 {
  function useAllowanceOf(
    uint256 projectId,
    uint256 amount,
    uint256 currency,
    address token,
    uint256 minReturnedTokens,
    address payable beneficiary,
    string calldata memo,
    bytes calldata metadata
  ) external returns (uint256 netDistributedAmount);
}

File 60 of 76 : IJBFeeHoldingTerminal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBFeeHoldingTerminal {
  function addToBalanceOf(
    uint256 projectId,
    uint256 amount,
    address token,
    bool shouldRefundHeldFees,
    string calldata memo,
    bytes calldata metadata
  ) external payable;
}

File 61 of 76 : IJBPayDelegate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidPayData} from './../structs/JBDidPayData.sol';

/// @title Pay delegate
/// @notice Delegate called after JBTerminal.pay(..) logic completion (if passed by the funding cycle datasource)
interface IJBPayDelegate is IERC165 {
  /// @notice This function is called by JBPaymentTerminal.pay(..), after the execution of its logic
  /// @dev Critical business logic should be protected by an appropriate access control
  /// @param data the data passed by the terminal, as a JBDidPayData struct:
  function didPay(JBDidPayData calldata data) external payable;
}

File 62 of 76 : IJBPayoutTerminal3_1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBPayoutTerminal3_1 {
  function distributePayoutsOf(
    uint256 projectId,
    uint256 amount,
    uint256 currency,
    address token,
    uint256 minReturnedTokens,
    bytes calldata metadata
  ) external returns (uint256 netLeftoverDistributionAmount);
}

File 63 of 76 : IJBPrices.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IJBPriceFeed} from './IJBPriceFeed.sol';

interface IJBPrices {
  event AddFeed(uint256 indexed currency, uint256 indexed base, IJBPriceFeed feed);

  function feedFor(uint256 currency, uint256 base) external view returns (IJBPriceFeed);

  function priceFor(
    uint256 currency,
    uint256 base,
    uint256 decimals
  ) external view returns (uint256);

  function addFeedFor(uint256 currency, uint256 base, IJBPriceFeed priceFeed) external;
}

File 64 of 76 : IJBRedemptionDelegate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBDidRedeemData} from './../structs/JBDidRedeemData.sol';

/// @title Redemption delegate
/// @notice Delegate called after JBTerminal.redeemTokensOf(..) logic completion (if passed by the funding cycle datasource)
interface IJBRedemptionDelegate is IERC165 {
  /// @notice This function is called by JBPaymentTerminal.redeemTokensOf(..), after the execution of its logic
  /// @dev Critical business logic should be protected by an appropriate access control
  /// @param data the data passed by the terminal, as a JBDidRedeemData struct:
  function didRedeem(JBDidRedeemData calldata data) external payable;
}

File 65 of 76 : IJBRedemptionTerminal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBRedemptionTerminal {
  function redeemTokensOf(
    address holder,
    uint256 projectId,
    uint256 tokenCount,
    address token,
    uint256 minReturnedTokens,
    address payable beneficiary,
    string calldata memo,
    bytes calldata metadata
  ) external returns (uint256 reclaimAmount);
}

File 66 of 76 : JBDidPayData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBTokenAmount} from './JBTokenAmount.sol';

/// @custom:member payer The address from which the payment originated.
/// @custom:member projectId The ID of the project for which the payment was made.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the payment is being made.
/// @custom:member amount The amount of the payment. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member projectTokenCount The number of project tokens minted for the beneficiary.
/// @custom:member beneficiary The address to which the tokens were minted.
/// @custom:member preferClaimedTokens A flag indicating whether the request prefered to mint project tokens into the beneficiaries wallet rather than leaving them unclaimed. This is only possible if the project has an attached token contract.
/// @custom:member memo The memo that is being emitted alongside the payment.
/// @custom:member metadata Extra data to send to the delegate.
struct JBDidPayData {
  address payer;
  uint256 projectId;
  uint256 currentFundingCycleConfiguration;
  JBTokenAmount amount;
  JBTokenAmount forwardedAmount;
  uint256 projectTokenCount;
  address beneficiary;
  bool preferClaimedTokens;
  string memo;
  bytes metadata;
}

File 67 of 76 : JBDidRedeemData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBTokenAmount} from './JBTokenAmount.sol';

/// @custom:member holder The holder of the tokens being redeemed.
/// @custom:member projectId The ID of the project with which the redeemed tokens are associated.
/// @custom:member currentFundingCycleConfiguration The configuration of the funding cycle during which the redemption is being made.
/// @custom:member projectTokenCount The number of project tokens being redeemed.
/// @custom:member reclaimedAmount The amount reclaimed from the treasury. Includes the token being reclaimed, the value, the number of decimals included, and the currency of the amount.
/// @custom:member forwardedAmount The amount of the payment that is being sent to the delegate. Includes the token being paid, the value, the number of decimals included, and the currency of the amount.
/// @custom:member beneficiary The address to which the reclaimed amount will be sent.
/// @custom:member memo The memo that is being emitted alongside the redemption.
/// @custom:member metadata Extra data to send to the delegate.
struct JBDidRedeemData {
  address holder;
  uint256 projectId;
  uint256 currentFundingCycleConfiguration;
  uint256 projectTokenCount;
  JBTokenAmount reclaimedAmount;
  JBTokenAmount forwardedAmount;
  address payable beneficiary;
  string memo;
  bytes metadata;
}

File 68 of 76 : JBOperatorData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @custom:member operator The address of the operator.
/// @custom:member domain The domain within which the operator is being given permissions. A domain of 0 is a wildcard domain, which gives an operator access to all domains.
/// @custom:member permissionIndexes The indexes of the permissions the operator is being given.
struct JBOperatorData {
  address operator;
  uint256 domain;
  uint256[] permissionIndexes;
}

File 69 of 76 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

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

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

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

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

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

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

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

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

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

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

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

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

File 70 of 76 : IJBTokenUriResolver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBTokenUriResolver {
  function getUri(uint256 projectId) external view returns (string memory tokenUri);
}

File 71 of 76 : IJBFundingCycleBallot.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBBallotState} from './../enums/JBBallotState.sol';

interface IJBFundingCycleBallot is IERC165 {
  function duration() external view returns (uint256);

  function stateOf(
    uint256 projectId,
    uint256 configuration,
    uint256 start
  ) external view returns (JBBallotState);
}

File 72 of 76 : JBGlobalFundingCycleMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @custom:member allowSetTerminals A flag indicating if setting terminals should be allowed during this funding cycle.
/// @custom:member allowSetController A flag indicating if setting a new controller should be allowed during this funding cycle.
/// @custom:member pauseTransfers A flag indicating if the project token transfer functionality should be paused during the funding cycle.
struct JBGlobalFundingCycleMetadata {
  bool allowSetTerminals;
  bool allowSetController;
  bool pauseTransfers;
}

File 73 of 76 : IJBSplitAllocator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {JBSplitAllocationData} from '../structs/JBSplitAllocationData.sol';

/// @title Split allocator
/// @notice Provide a way to process a single split with extra logic
/// @dev The contract address should be set as an allocator in the adequate split
interface IJBSplitAllocator is IERC165 {
  /// @notice This function is called by JBPaymentTerminal.distributePayoutOf(..), during the processing of the split including it
  /// @dev Critical business logic should be protected by an appropriate access control. The token and/or eth are optimistically transfered to the allocator for its logic.
  /// @param data the data passed by the terminal, as a JBSplitAllocationData struct:
  function allocate(JBSplitAllocationData calldata data) external payable;
}

File 74 of 76 : IJBToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBToken {
  function projectId() external view returns (uint256);

  function decimals() external view returns (uint8);

  function totalSupply(uint256 projectId) external view returns (uint256);

  function balanceOf(address account, uint256 projectId) external view returns (uint256);

  function mint(uint256 projectId, address account, uint256 amount) external;

  function burn(uint256 projectId, address account, uint256 amount) external;

  function approve(uint256, address spender, uint256 amount) external;

  function transfer(uint256 projectId, address to, uint256 amount) external;

  function transferFrom(uint256 projectId, address from, address to, uint256 amount) external;
}

File 75 of 76 : IJBPriceFeed.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IJBPriceFeed {
  function currentPrice(uint256 targetDecimals) external view returns (uint256);
}

File 76 of 76 : JBSplitAllocationData.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {JBSplit} from './JBSplit.sol';

/// @custom:member token The token being sent to the split allocator.
/// @custom:member amount The amount being sent to the split allocator, as a fixed point number.
/// @custom:member decimals The number of decimals in the amount.
/// @custom:member projectId The project to which the split belongs.
/// @custom:member group The group to which the split belongs.
/// @custom:member split The split that caused the allocation.
struct JBSplitAllocationData {
  address token;
  uint256 amount;
  uint256 decimals;
  uint256 projectId;
  uint256 group;
  JBSplit split;
}

Settings
{
  "remappings": [
    "ds-test/=node_modules/ds-test/src/",
    "forge-std/=node_modules/forge-std/src/",
    "@chainlink/=node_modules/@chainlink/",
    "@ensdomains/=node_modules/@ensdomains/",
    "@exhausted-pigeon/=node_modules/@exhausted-pigeon/",
    "@jbx-protocol/=node_modules/@jbx-protocol/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@paulrberg/=node_modules/@paulrberg/",
    "@prb/=node_modules/@prb/",
    "@uniswap/=node_modules/@uniswap/",
    "base64-sol/=node_modules/base64-sol/",
    "prb-math/=node_modules/prb-math/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IWETH9","name":"_weth","type":"address"},{"internalType":"address","name":"_factory","type":"address"},{"internalType":"contract IJBDirectory","name":"_directory","type":"address"},{"internalType":"contract IJBController3_1","name":"_controller","type":"address"},{"internalType":"bytes4","name":"_delegateId","type":"bytes4"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"JuiceBuyback_InsufficientPayAmount","type":"error"},{"inputs":[],"name":"JuiceBuyback_InvalidTwapSlippageTolerance","type":"error"},{"inputs":[],"name":"JuiceBuyback_InvalidTwapWindow","type":"error"},{"inputs":[],"name":"JuiceBuyback_MaximumSlippage","type":"error"},{"inputs":[],"name":"JuiceBuyback_NewSecondsAgoTooLow","type":"error"},{"inputs":[],"name":"JuiceBuyback_NoProjectToken","type":"error"},{"inputs":[],"name":"JuiceBuyback_NotEnoughTokensReceived","type":"error"},{"inputs":[],"name":"JuiceBuyback_PoolAlreadySet","type":"error"},{"inputs":[],"name":"JuiceBuyback_TransferFailed","type":"error"},{"inputs":[],"name":"JuiceBuyback_Unauthorized","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"T","type":"error"},{"inputs":[],"name":"UNAUTHORIZED","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokenCount","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":true,"internalType":"address","name":"terminalToken","type":"address"},{"indexed":false,"internalType":"address","name":"newPool","type":"address"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_PoolAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"contract IUniswapV3Pool","name":"pool","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldTwapDelta","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTwapDelta","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_TwapSlippageToleranceChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"projectId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldSecondsAgo","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newSecondsAgo","type":"uint256"},{"indexed":false,"internalType":"address","name":"caller","type":"address"}],"name":"BuybackDelegate_TwapWindowChanged","type":"event"},{"inputs":[],"name":"CONTROLLER","outputs":[{"internalType":"contract IJBController3_1","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DELEGATE_ID","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DIRECTORY","outputs":[{"internalType":"contract IJBDirectory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_TWAP_SLIPPAGE_TOLERANCE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_TWAP_WINDOW","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TWAP_SLIPPAGE_TOLERANCE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_TWAP_WINDOW","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PROJECTS","outputs":[{"internalType":"contract IJBProjects","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SLIPPAGE_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNISWAP_V3_FACTORY","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"contract IWETH9","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"payer","type":"address"},{"internalType":"uint256","name":"projectId","type":"uint256"},{"internalType":"uint256","name":"currentFundingCycleConfiguration","type":"uint256"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"amount","type":"tuple"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"forwardedAmount","type":"tuple"},{"internalType":"uint256","name":"projectTokenCount","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bool","name":"preferClaimedTokens","type":"bool"},{"internalType":"string","name":"memo","type":"string"},{"internalType":"bytes","name":"dataSourceMetadata","type":"bytes"},{"internalType":"bytes","name":"payerMetadata","type":"bytes"}],"internalType":"struct JBDidPayData3_1_1","name":"_data","type":"tuple"}],"name":"didPay","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"operatorStore","outputs":[{"internalType":"contract IJBOperatorStore","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IJBPaymentTerminal","name":"terminal","type":"address"},{"internalType":"address","name":"payer","type":"address"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"amount","type":"tuple"},{"internalType":"uint256","name":"projectId","type":"uint256"},{"internalType":"uint256","name":"currentFundingCycleConfiguration","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"weight","type":"uint256"},{"internalType":"uint256","name":"reservedRate","type":"uint256"},{"internalType":"string","name":"memo","type":"string"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBPayParamsData","name":"_data","type":"tuple"}],"name":"payParams","outputs":[{"internalType":"uint256","name":"weight","type":"uint256"},{"internalType":"string","name":"memo","type":"string"},{"components":[{"internalType":"contract IJBPayDelegate3_1_1","name":"delegate","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBPayDelegateAllocation3_1_1[]","name":"delegateAllocations","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"address","name":"_terminalToken","type":"address"}],"name":"poolOf","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"}],"name":"projectTokenOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IJBPaymentTerminal","name":"terminal","type":"address"},{"internalType":"address","name":"holder","type":"address"},{"internalType":"uint256","name":"projectId","type":"uint256"},{"internalType":"uint256","name":"currentFundingCycleConfiguration","type":"uint256"},{"internalType":"uint256","name":"tokenCount","type":"uint256"},{"internalType":"uint256","name":"totalSupply","type":"uint256"},{"internalType":"uint256","name":"overflow","type":"uint256"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"decimals","type":"uint256"},{"internalType":"uint256","name":"currency","type":"uint256"}],"internalType":"struct JBTokenAmount","name":"reclaimAmount","type":"tuple"},{"internalType":"bool","name":"useTotalOverflow","type":"bool"},{"internalType":"uint256","name":"redemptionRate","type":"uint256"},{"internalType":"string","name":"memo","type":"string"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBRedeemParamsData","name":"_data","type":"tuple"}],"name":"redeemParams","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"string","name":"","type":"string"},{"components":[{"internalType":"contract IJBRedemptionDelegate3_1_1","name":"delegate","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"metadata","type":"bytes"}],"internalType":"struct JBRedemptionDelegateAllocation3_1_1[]","name":"delegateAllocations","type":"tuple[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"uint24","name":"_fee","type":"uint24"},{"internalType":"uint32","name":"_twapWindow","type":"uint32"},{"internalType":"uint256","name":"_twapSlippageTolerance","type":"uint256"},{"internalType":"address","name":"_terminalToken","type":"address"}],"name":"setPoolFor","outputs":[{"internalType":"contract IUniswapV3Pool","name":"newPool","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"uint256","name":"_newSlippageTolerance","type":"uint256"}],"name":"setTwapSlippageToleranceOf","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"},{"internalType":"uint32","name":"_newWindow","type":"uint32"}],"name":"setTwapWindowOf","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"_interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"}],"name":"twapSlippageToleranceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_projectId","type":"uint256"}],"name":"twapWindowOf","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"_amount0Delta","type":"int256"},{"internalType":"int256","name":"_amount1Delta","type":"int256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"}]

6101606040523480156200001257600080fd5b50604051620035c7380380620035c7833981016040819052620000359162000166565b816001600160a01b031663ad007d636040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000074573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200009a9190620001f2565b6001600160a01b039081166080528581166101205283811660c05282811660e081905290851660a0526001600160e01b0319821661014052604080516322de550f60e21b81529051638b79543c916004808201926020929091908290030181865afa1580156200010e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001349190620001f2565b6001600160a01b03166101005250620002199350505050565b6001600160a01b03811681146200016357600080fd5b50565b600080600080600060a086880312156200017f57600080fd5b85516200018c816200014d565b60208701519095506200019f816200014d565b6040870151909450620001b2816200014d565b6060870151909350620001c5816200014d565b60808701519092506001600160e01b031981168114620001e457600080fd5b809150509295509295909350565b6000602082840312156200020557600080fd5b815162000212816200014d565b9392505050565b60805160a05160c05160e0516101005161012051610140516132e3620002e4600039600081816101b901526112d601526000818161047401528181610f41015281816113ac01528181611607015281816116960152611946015260008181610277015281816105fc015281816107570152610d2701526000818161050301528181610c3301528181610e150152611ad9015260008181610397015261088d0152600081816105370152610f74015260008181610440015281816117cc015261187301526132e36000f3fe60806040526004361061014b5760003560e01c806388bc2ef3116100b6578063af4718801161006f578063af47188014610496578063b88a92b4146104ab578063d46cf171146104c2578063ee0fc121146104f1578063f73e5aab14610525578063fa461e331461055957600080fd5b806388bc2ef3146103855780639c9d4361146103b9578063a51cfd18146103e9578063ac90511414610418578063ad007d631461042e578063ad5c46481461046257600080fd5b80633717fba7116101085780633717fba71461029957806355135de0146102db5780636b204943146102fb578063754baf961461030e5780637b621d3a14610324578063889eedb41461034457600080fd5b806301ffc9a714610150578063132893eb1461018557806314e650f9146101a75780631a65893b146101f457806327e5141114610217578063293c499914610265575b600080fd5b34801561015c57600080fd5b5061017061016b3660046126c0565b610579565b60405190151581526020015b60405180910390f35b34801561019157600080fd5b506101a56101a0366004612703565b6105e6565b005b3480156101b357600080fd5b506101db7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160e01b0319909116815260200161017c565b34801561020057600080fd5b50610209607881565b60405190815260200161017c565b34801561022357600080fd5b5061024d61023236600461272f565b6002602052600090815260409020546001600160a01b031681565b6040516001600160a01b03909116815260200161017c565b34801561027157600080fd5b5061024d7f000000000000000000000000000000000000000000000000000000000000000081565b3480156102a557600080fd5b506102c66102b436600461272f565b60009081526020819052604090205490565b60405163ffffffff909116815260200161017c565b3480156102e757600080fd5b506101a56102f6366004612748565b610741565b6101a561030936600461276a565b61086e565b34801561031a57600080fd5b5061020961232881565b34801561033057600080fd5b5061024d61033f3660046127be565b610d0e565b34801561035057600080fd5b5061024d61035f366004612823565b60016020908152600092835260408084209091529082529020546001600160a01b031681565b34801561039157600080fd5b5061024d7f000000000000000000000000000000000000000000000000000000000000000081565b3480156103c557600080fd5b506102096103d436600461272f565b60009081526020819052604090205460801c90565b3480156103f557600080fd5b50610409610404366004612853565b61125b565b60405161017c939291906128d5565b34801561042457600080fd5b5061020961271081565b34801561043a57600080fd5b5061024d7f000000000000000000000000000000000000000000000000000000000000000081565b34801561046e57600080fd5b5061024d7f000000000000000000000000000000000000000000000000000000000000000081565b3480156104a257600080fd5b50610209606481565b3480156104b757600080fd5b506102096202a30081565b3480156104ce57600080fd5b506104e26104dd366004612973565b6112be565b60405161017c939291906129af565b3480156104fd57600080fd5b5061024d7f000000000000000000000000000000000000000000000000000000000000000081565b34801561053157600080fd5b5061024d7f000000000000000000000000000000000000000000000000000000000000000081565b34801561056557600080fd5b506101a5610574366004612a3b565b6115d7565b60006001600160e01b031982166371700c6960e01b14806105aa57506001600160e01b03198216636b20494360e01b145b806105c557506001600160e01b0319821663766842c760e11b145b806105e057506301ffc9a760e01b6001600160e01b03198316145b92915050565b6040516331a9108f60e11b8152600481018390527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa15801561064b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061066f9190612abb565b82601861067d838383611785565b60788463ffffffff16108061069a57506202a3008463ffffffff16115b156106b857604051634b99a82760e01b815260040160405180910390fd5b60008581526020818152604091829020805463ffffffff88166fffffffffffffffffffffffffffffffff198216811790925583516001600160801b03821680825293810192909252339382019390935287907f0ad45a678e9246540d8e570b292142910b43d3431fd41ea7e077fd0a7d74a872906060015b60405180910390a250505050505050565b6040516331a9108f60e11b8152600481018390527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156107a6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ca9190612abb565b8260186107d8838383611785565b60648410806107e8575061232884115b1561080657604051631687249960e01b815260040160405180910390fd5b600085815260208181526040918290208054608088811b6001600160801b0383161790925583519181901c808352928201889052339382019390935287907fb4916f587869d0a367a4b9428fe68226803f2340d0a5edcc472b6258f7f4178390606001610730565b604051636e49181f60e01b8152602082013560048201523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636e49181f90604401602060405180830381865afa1580156108dc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109009190612ae6565b61091d576040516384f5681360e01b815260040160405180910390fd5b6000808080806109316101e0870187612b03565b81019061093e9190612b51565b9450945094509450945060006109548786611903565b905085801561096257508281105b156109805760405163da9d209360e01b815260040160405180910390fd5b600061eeee6109966101008a0160e08b01612ba2565b6001600160a01b031614610a24576109b5610100890160e08a01612ba2565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156109fb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a1f9190612bbf565b610a26565b475b905060008115610c0957610a498285610a4460a08d0135600a612cd2565b611ba0565b905061eeee610a5f6101008b0160e08c01612ba2565b6001600160a01b031614610af357610a7e6101008a0160e08b01612ba2565b60405163095ea7b360e01b8152336004820152602481018490526001600160a01b03919091169063095ea7b3906044016020604051808303816000875af1158015610acd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610af19190612ae6565b505b33630cf8e85861eeee610b0d6101008d0160e08e01612ba2565b6001600160a01b031614610b22576000610b24565b835b8b60200135858d60e0016000016020810190610b409190612ba2565b6040516001600160e01b031960e087901b168152600481019390935260248301919091526001600160a01b0316604482015260a06064820152600060a4820181905260c0608483015260c482015260e4016000604051808303818588803b158015610baa57600080fd5b505af1158015610bbe573d6000803e3d6000fd5b505060408051868152602080820187905233828401529151918e013594507f23b44985be81ddf30da326d2a65d4ee6cfe8b12699ff63d2e9b4c6c82a53058393508190036060019150a25b610c1d8685610a4460a08d0135600a612cd2565b610c279082612cde565b90506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016638ae9c07b60208b0135610c678487612cde565b610c796101a08e016101808f01612ba2565b610c876101c08f018f612b03565b8f6101a0016020810190610c9b9190612cf1565b60016040518863ffffffff1660e01b8152600401610cbf9796959493929190612d0e565b6020604051808303816000875af1158015610cde573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d029190612bbf565b50505050505050505050565b6040516331a9108f60e11b8152600481018690526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015610d76573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9a9190612abb565b866019610da8838383611785565b6064861080610db8575061232886115b15610dd657604051631687249960e01b815260040160405180910390fd5b60788763ffffffff161080610df357506202a3008763ffffffff16115b15610e1157604051634b99a82760e01b815260040160405180910390fd5b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663619306306040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e959190612abb565b6001600160a01b031663ea78803f8b6040518263ffffffff1660e01b8152600401610ec291815260200190565b602060405180830381865afa158015610edf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f039190612abb565b90506001600160a01b038116610f2c57604051632befbc9b60e01b815260040160405180910390fd5b61eeed196001600160a01b03871601610f63577f000000000000000000000000000000000000000000000000000000000000000095505b6001600160a01b03808716908216107f000000000000000000000000000000000000000000000000000000000000000081610f9e5787610fa0565b825b82610fab5783610fad565b885b604080516001600160a01b039384166020820152929091169082015262ffffff8c16606082015260800160408051601f19818403018152908290528051602091820120611052939290917fe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b5491016001600160f81b0319815260609390931b6bffffffffffffffffffffffff191660018401526015830191909152603582015260550190565b60408051601f19818403018152918152815160209283012060008e8152600184528281206001600160a01b038c81168352945291909120549097508188169116036110b057604051630917c39960e41b815260040160405180910390fd5b85600160008d81526020019081526020016000206000896001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055508863ffffffff16608089901b176000808d81526020019081526020016000208190555081600260008d815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055508a7f0ad45a678e9246540d8e570b292142910b43d3431fd41ea7e077fd0a7d74a87260008b336040516111bb9392919092835263ffffffff9190911660208301526001600160a01b0316604082015260600190565b60405180910390a26040805160008152602081018a9052338183015290518c917fb4916f587869d0a367a4b9428fe68226803f2340d0a5edcc472b6258f7f41783919081900360600190a2604080516001600160a01b0388811682523360208301528916918d917f4f12d52a21571ed6da4506af6a540828b73258521f50cd1af9704f36e284ddbb910160405180910390a3505050505095945050505050565b60006060806101008401356112746101a0860186612b03565b8382828080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525096995091975091955050505050505b9193909250565b600060608083810135610120850135848080856113087f00000000000000000000000000000000000000000000000000000000000000006113036101808d018d612b03565b611c7f565b9092509050811561132c57808060200190518101906113279190612d6e565b945092505b5081600003611339578491505b600061134f8386610a4460808e0135600a612cd2565b60c08b0135600090815260026020526040808220549293506001600160a01b039092169161eeee906113879060608f01908f01612ba2565b6001600160a01b0316146113aa576113a560608d0160408e01612ba2565b6113cc565b7f00000000000000000000000000000000000000000000000000000000000000005b9050856000036113e9576113e68c60c00135838784611e87565b95505b858310156115635787851115611412576040516306d0bd2360e21b815260040160405180910390fd5b6040805160018082528183019092526001600160a01b038381169085161091816020015b604080516060808201835260008083526020830152918101919091528152602001906001900390816114365750506040805160608101825230815260208101899052919b50810186838c8a14611495576114908a8e612da8565b611498565b60005b604080519315156020850152911515918301919091526060820152608081018a905260a081018b905260c0016040516020818303038152906040528152508a6000815181106114e9576114e9612dbb565b602090810291909101015260006115046101608f018f612b03565b8c82828080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091509091509b509b509b505050505050505050506112b7565b6101208c01356115776101608e018e612b03565b8b82828080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091509091509a509a509a5050505050505050509193909250565b6000806115e683850185612823565b909250905060006001600160a01b03821661eeee146116055781611627565b7f00000000000000000000000000000000000000000000000000000000000000005b60008481526001602090815260408083206001600160a01b03858116855292529091205491925016331461166e576040516384f5681360e01b815260040160405180910390fd5b600080881261167d578761167f565b865b905061eeed196001600160a01b03841601611709577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b1580156116ef57600080fd5b505af1158015611703573d6000803e3d6000fd5b50505050505b60405163a9059cbb60e01b8152336004820152602481018290526001600160a01b0383169063a9059cbb906044016020604051808303816000875af1158015611756573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061177a9190612ae6565b505050505050505050565b336001600160a01b03841614801590611839575060405163c161c93f60e01b81523360048201526001600160a01b03848116602483015260448201849052606482018390527f0000000000000000000000000000000000000000000000000000000000000000169063c161c93f90608401602060405180830381865afa158015611813573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118379190612ae6565b155b80156118e0575060405163c161c93f60e01b81523360048201526001600160a01b03848116602483015260006044830152606482018390527f0000000000000000000000000000000000000000000000000000000000000000169063c161c93f90608401602060405180830381865afa1580156118ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118de9190612ae6565b155b156118fe5760405163075fd2b160e01b815260040160405180910390fd5b505050565b60006101008301803590829061eeee906119209060e08801612ba2565b6001600160a01b0316146119445761193f610100860160e08701612ba2565b611966565b7f00000000000000000000000000000000000000000000000000000000000000005b60208087013560009081526001825260408082206001600160a01b0380861684529352902054919250168063128acb0830871586896119b4576119af6401000276a36001612dd1565b6119d3565b6119d3600173fffd8963efd1fc6a506488495d951d5263988d26612df8565b60208c01356119e96101008e0160e08f01612ba2565b604051602001611a0c9291909182526001600160a01b0316602082015260400190565b6040516020818303038152906040526040518663ffffffff1660e01b8152600401611a3b959493929190612e18565b60408051808303816000875af1925050508015611a75575060408051601f3d908101601f19168201909252611a7291810190612d6e565b60015b611a8557600093505050506105e0565b86611a905780611a92565b815b611a9b90612e5e565b604051631665bc0f60e01b815230600482015260208a013560248201526044810182905260a06064820152600060a4820152600160848201529096507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169250631665bc0f915060c401600060405180830381600087803b158015611b2757600080fd5b505af1158015611b3b573d6000803e3d6000fd5b5050604080518681526001600160a01b0385166020828101919091529181018890523360608201529089013592507f84368bfe147605fe15d2ca558fb0ab52664fb9e27d640457122c6796608e6fdf915060800160405180910390a250505092915050565b6000808060001985870985870292508281108382030391505080600003611bda57838281611bd057611bd0612e7a565b0492505050611c78565b838110611c1057604051630c740aef60e31b81526004810187905260248101869052604481018590526064015b60405180910390fd5b600084868809851960019081018716968790049682860381900495909211909303600082900391909104909201919091029190911760038402600290811880860282030280860282030280860282030280860282030280860282030280860290910302029150505b9392505050565b6000606060258311611ca35750506040805160208101909152600080825290611e7f565b60008484611cb360046020612cde565b818110611cc257611cc2612dbb565b919091013560f81c9150602090505b60008686611ce0600485612cde565b818110611cef57611cef612dbb565b9050013560f81c60f81b6001600160f81b03191614158015611d1a5750611d17602083612e90565b81105b15611e7c5760008686611d2e600485612cde565b818110611d3d57611d3d612dbb565b919091013560f81c9150506001600160e01b03198816878388611d61600483612cde565b92611d6e93929190612ea7565b611d7791612ed1565b6001600160e01b03191603611e73576000611d93602085612e90565b611d9e600985612cde565b101580611dd457508787611db3600986612cde565b818110611dc257611dc2612dbb565b909101356001600160f81b0319161590505b611e0c5760208888611de7600987612cde565b818110611df657611df6612dbb565b611e079392013560f81c9050612e90565b611e0e565b865b905060018888611e1f602086612e90565b611e2b92859290612ea7565b81818080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250959b50919950611e7f98505050505050505050565b50600501611cd1565b50505b935093915050565b60008481526001602090815260408083206001600160a01b0380861685529252808320548151633850c7bd60e01b815291519216918291633850c7bd9160048083019260e09291908290030181865afa925050508015611f04575060408051601f3d908101601f19168201909252611f0191810190612f13565b60015b611f12576000915050611f8b565b80611f2857600098505050505050505050611f8b565b50505050505050600086815260208190526040812054908190608082901c90611f518584611f93565b509050611f608189898c6121dd565b9550612710611f6f8388612e90565b611f799190612fb2565b611f839087612da8565b955050505050505b949350505050565b6000808263ffffffff16600003611fd15760405162461bcd60e51b8152602060048201526002602482015261042560f41b6044820152606401611c07565b604080516002808252606082018352600092602083019080368337019050509050838160008151811061200657612006612dbb565b602002602001019063ffffffff16908163ffffffff168152505060008160018151811061203557612035612dbb565b602002602001019063ffffffff16908163ffffffff1681525050600080866001600160a01b031663883bdbfd846040518263ffffffff1660e01b815260040161207e9190612fc6565b600060405180830381865afa15801561209b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526120c391908101906130d9565b915091506000826000815181106120dc576120dc612dbb565b6020026020010151836001815181106120f7576120f7612dbb565b602002602001015161210991906131a5565b905060008260008151811061212057612120612dbb565b60200260200101518360018151811061213b5761213b612dbb565b602002602001015161214d9190612df8565b905061215f63ffffffff8916836131d2565b965060008260060b128015612185575061217f63ffffffff891683613210565b60060b15155b15612198578661219481613232565b9750505b60006121b16001600160a01b0363ffffffff8b16613255565b90506121ce640100000000600160c01b03602084901b1682613287565b96505050505050509250929050565b6000806121e9866122eb565b90506001600160801b036001600160a01b0382161161226f5760006122176001600160a01b03831680612e90565b9050836001600160a01b0316856001600160a01b03161061224f5761224a600160c01b876001600160801b03168361260e565b612267565b61226781876001600160801b0316600160c01b61260e565b9250506122e2565b600061228e6001600160a01b038316806801000000000000000061260e565b9050836001600160a01b0316856001600160a01b0316106122c6576122c1600160801b876001600160801b03168361260e565b6122de565b6122de81876001600160801b0316600160801b61260e565b9250505b50949350505050565b60008060008360020b12612302578260020b61230a565b8260020b6000035b9050620d89e8811115612330576040516315e4079d60e11b815260040160405180910390fd5b60008160011660000361234757600160801b612359565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561238d576ffff97272373d413259a46990580e213a0260801c5b60048216156123ac576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156123cb576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156123ea576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612409576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612428576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612447576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612467576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612487576ff987a7253ac413176f2b074cf7815e540260801c5b6104008216156124a7576ff3392b0822b70005940c7a398e4b70f30260801c5b6108008216156124c7576fe7159475a2c29b7443b29c7fa6e889d90260801c5b6110008216156124e7576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612507576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612527576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612547576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612568576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615612588576e5d6af8dedb81196699c329225ee6040260801c5b620400008216156125a7576d2216e584f5fa1ea926041bedfe980260801c5b620800008216156125c4576b048a170391f7dc42444e8fa20260801c5b60008460020b13156125e55780600019816125e1576125e1612e7a565b0490505b6401000000008106156125f95760016125fc565b60005b60ff16602082901c0192505050919050565b6000808060001985870985870292508281108382030391505080600003612647576000841161263c57600080fd5b508290049050611c78565b80841161265357600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6000602082840312156126d257600080fd5b81356001600160e01b031981168114611c7857600080fd5b803563ffffffff811681146126fe57600080fd5b919050565b6000806040838503121561271657600080fd5b82359150612726602084016126ea565b90509250929050565b60006020828403121561274157600080fd5b5035919050565b6000806040838503121561275b57600080fd5b50508035926020909101359150565b60006020828403121561277c57600080fd5b813567ffffffffffffffff81111561279357600080fd5b82016102208185031215611c7857600080fd5b6001600160a01b03811681146127bb57600080fd5b50565b600080600080600060a086880312156127d657600080fd5b85359450602086013562ffffff811681146127f057600080fd5b93506127fe604087016126ea565b9250606086013591506080860135612815816127a6565b809150509295509295909350565b6000806040838503121561283657600080fd5b823591506020830135612848816127a6565b809150509250929050565b60006020828403121561286557600080fd5b813567ffffffffffffffff81111561287c57600080fd5b82016101e08185031215611c7857600080fd5b6000815180845260005b818110156128b557602081850181015186830182015201612899565b506000602082860101526020601f19601f83011685010191505092915050565b60006060858352602081818501526128ef8285018761288f565b6040858203818701528187518084528484019150848160051b850101858a0160005b8381101561296157868303601f19018552815180516001600160a01b0316845288810151898501528601518684018a905261294e8a85018261288f565b9589019593505090870190600101612911565b50909c9b505050505050505050505050565b60006020828403121561298557600080fd5b813567ffffffffffffffff81111561299c57600080fd5b82016101a08185031215611c7857600080fd5b60006060858352602081818501526129c98285018761288f565b6040858203818701528187518084528484019150848160051b850101858a0160005b8381101561296157868303601f19018552815180516001600160a01b0316845288810151898501528601518684018a9052612a288a85018261288f565b95890195935050908701906001016129eb565b60008060008060608587031215612a5157600080fd5b8435935060208501359250604085013567ffffffffffffffff80821115612a7757600080fd5b818701915087601f830112612a8b57600080fd5b813581811115612a9a57600080fd5b886020828501011115612aac57600080fd5b95989497505060200194505050565b600060208284031215612acd57600080fd5b8151611c78816127a6565b80151581146127bb57600080fd5b600060208284031215612af857600080fd5b8151611c7881612ad8565b6000808335601e19843603018112612b1a57600080fd5b83018035915067ffffffffffffffff821115612b3557600080fd5b602001915036819003821315612b4a57600080fd5b9250929050565b600080600080600060a08688031215612b6957600080fd5b8535612b7481612ad8565b94506020860135612b8481612ad8565b94979496505050506040830135926060810135926080909101359150565b600060208284031215612bb457600080fd5b8135611c78816127a6565b600060208284031215612bd157600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600181815b80851115612c29578160001904821115612c0f57612c0f612bd8565b80851615612c1c57918102915b93841c9390800290612bf3565b509250929050565b600082612c40575060016105e0565b81612c4d575060006105e0565b8160018114612c635760028114612c6d57612c89565b60019150506105e0565b60ff841115612c7e57612c7e612bd8565b50506001821b6105e0565b5060208310610133831016604e8410600b8410161715612cac575081810a6105e0565b612cb68383612bee565b8060001904821115612cca57612cca612bd8565b029392505050565b6000611c788383612c31565b808201808211156105e0576105e0612bd8565b600060208284031215612d0357600080fd5b8135611c7881612ad8565b878152602081018790526001600160a01b038616604082015260c0606082018190528101849052838560e0830137600060e0858301810191909152921515608082015290151560a0820152601f909201601f191690910101949350505050565b60008060408385031215612d8157600080fd5b505080516020909101519092909150565b634e487b7160e01b600052604160045260246000fd5b818103818111156105e0576105e0612bd8565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b03818116838216019080821115612df157612df1612bd8565b5092915050565b6001600160a01b03828116828216039080821115612df157612df1612bd8565b6001600160a01b0386811682528515156020830152604082018590528316606082015260a060808201819052600090612e539083018461288f565b979650505050505050565b6000600160ff1b8201612e7357612e73612bd8565b5060000390565b634e487b7160e01b600052601260045260246000fd5b80820281158282048414176105e0576105e0612bd8565b60008085851115612eb757600080fd5b83861115612ec457600080fd5b5050820193919092039150565b6001600160e01b03198135818116916004851015612ef95780818660040360031b1b83161692505b505092915050565b805161ffff811681146126fe57600080fd5b600080600080600080600060e0888a031215612f2e57600080fd5b8751612f39816127a6565b8097505060208801518060020b8114612f5157600080fd5b9550612f5f60408901612f01565b9450612f6d60608901612f01565b9350612f7b60808901612f01565b925060a088015160ff81168114612f9157600080fd5b60c0890151909250612fa281612ad8565b8091505092959891949750929550565b600082612fc157612fc1612e7a565b500490565b6020808252825182820181905260009190848201906040850190845b8181101561300457835163ffffffff1683529284019291840191600101612fe2565b50909695505050505050565b604051601f8201601f1916810167ffffffffffffffff8111828210171561303957613039612d92565b604052919050565b600067ffffffffffffffff82111561305b5761305b612d92565b5060051b60200190565b600082601f83011261307657600080fd5b8151602061308b61308683613041565b613010565b82815260059290921b840181019181810190868411156130aa57600080fd5b8286015b848110156130ce5780516130c1816127a6565b83529183019183016130ae565b509695505050505050565b600080604083850312156130ec57600080fd5b825167ffffffffffffffff8082111561310457600080fd5b818501915085601f83011261311857600080fd5b8151602061312861308683613041565b82815260059290921b8401810191818101908984111561314757600080fd5b948201945b838610156131755785518060060b81146131665760008081fd5b8252948201949082019061314c565b9188015191965090935050508082111561318e57600080fd5b5061319b85828601613065565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156105e0576105e0612bd8565b60008160060b8360060b806131e9576131e9612e7a565b667fffffffffffff1982146000198214161561320757613207612bd8565b90059392505050565b60008260060b8061322357613223612e7a565b808360060b0791505092915050565b60008160020b627fffff19810361324b5761324b612bd8565b6000190192915050565b6001600160c01b0382811682821681810283169291811582850482141761327e5761327e612bd8565b50505092915050565b60006001600160c01b03838116806132a1576132a1612e7a565b9216919091049291505056fea264697066735822122069dd9d2219c65572308db0914e887be9a2419a92d6707d2ebe99b5ec3da9803a64736f6c63430008150033000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98400000000000000000000000065572fb928b46f9adb7cfe5a4c41226f636161ea00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b4255594200000000000000000000000000000000000000000000000000000000

Deployed Bytecode

0x60806040526004361061014b5760003560e01c806388bc2ef3116100b6578063af4718801161006f578063af47188014610496578063b88a92b4146104ab578063d46cf171146104c2578063ee0fc121146104f1578063f73e5aab14610525578063fa461e331461055957600080fd5b806388bc2ef3146103855780639c9d4361146103b9578063a51cfd18146103e9578063ac90511414610418578063ad007d631461042e578063ad5c46481461046257600080fd5b80633717fba7116101085780633717fba71461029957806355135de0146102db5780636b204943146102fb578063754baf961461030e5780637b621d3a14610324578063889eedb41461034457600080fd5b806301ffc9a714610150578063132893eb1461018557806314e650f9146101a75780631a65893b146101f457806327e5141114610217578063293c499914610265575b600080fd5b34801561015c57600080fd5b5061017061016b3660046126c0565b610579565b60405190151581526020015b60405180910390f35b34801561019157600080fd5b506101a56101a0366004612703565b6105e6565b005b3480156101b357600080fd5b506101db7f425559420000000000000000000000000000000000000000000000000000000081565b6040516001600160e01b0319909116815260200161017c565b34801561020057600080fd5b50610209607881565b60405190815260200161017c565b34801561022357600080fd5b5061024d61023236600461272f565b6002602052600090815260409020546001600160a01b031681565b6040516001600160a01b03909116815260200161017c565b34801561027157600080fd5b5061024d7f000000000000000000000000d8b4359143eda5b2d763e127ed27c77addbc47d381565b3480156102a557600080fd5b506102c66102b436600461272f565b60009081526020819052604090205490565b60405163ffffffff909116815260200161017c565b3480156102e757600080fd5b506101a56102f6366004612748565b610741565b6101a561030936600461276a565b61086e565b34801561031a57600080fd5b5061020961232881565b34801561033057600080fd5b5061024d61033f3660046127be565b610d0e565b34801561035057600080fd5b5061024d61035f366004612823565b60016020908152600092835260408084209091529082529020546001600160a01b031681565b34801561039157600080fd5b5061024d7f00000000000000000000000065572fb928b46f9adb7cfe5a4c41226f636161ea81565b3480156103c557600080fd5b506102096103d436600461272f565b60009081526020819052604090205460801c90565b3480156103f557600080fd5b50610409610404366004612853565b61125b565b60405161017c939291906128d5565b34801561042457600080fd5b5061020961271081565b34801561043a57600080fd5b5061024d7f0000000000000000000000006f3c5afca0c9edf3926ef2ddf17c8ae6391afefb81565b34801561046e57600080fd5b5061024d7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b3480156104a257600080fd5b50610209606481565b3480156104b757600080fd5b506102096202a30081565b3480156104ce57600080fd5b506104e26104dd366004612973565b6112be565b60405161017c939291906129af565b3480156104fd57600080fd5b5061024d7f00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b81565b34801561053157600080fd5b5061024d7f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98481565b34801561056557600080fd5b506101a5610574366004612a3b565b6115d7565b60006001600160e01b031982166371700c6960e01b14806105aa57506001600160e01b03198216636b20494360e01b145b806105c557506001600160e01b0319821663766842c760e11b145b806105e057506301ffc9a760e01b6001600160e01b03198316145b92915050565b6040516331a9108f60e11b8152600481018390527f000000000000000000000000d8b4359143eda5b2d763e127ed27c77addbc47d36001600160a01b031690636352211e90602401602060405180830381865afa15801561064b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061066f9190612abb565b82601861067d838383611785565b60788463ffffffff16108061069a57506202a3008463ffffffff16115b156106b857604051634b99a82760e01b815260040160405180910390fd5b60008581526020818152604091829020805463ffffffff88166fffffffffffffffffffffffffffffffff198216811790925583516001600160801b03821680825293810192909252339382019390935287907f0ad45a678e9246540d8e570b292142910b43d3431fd41ea7e077fd0a7d74a872906060015b60405180910390a250505050505050565b6040516331a9108f60e11b8152600481018390527f000000000000000000000000d8b4359143eda5b2d763e127ed27c77addbc47d36001600160a01b031690636352211e90602401602060405180830381865afa1580156107a6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ca9190612abb565b8260186107d8838383611785565b60648410806107e8575061232884115b1561080657604051631687249960e01b815260040160405180910390fd5b600085815260208181526040918290208054608088811b6001600160801b0383161790925583519181901c808352928201889052339382019390935287907fb4916f587869d0a367a4b9428fe68226803f2340d0a5edcc472b6258f7f4178390606001610730565b604051636e49181f60e01b8152602082013560048201523360248201527f00000000000000000000000065572fb928b46f9adb7cfe5a4c41226f636161ea6001600160a01b031690636e49181f90604401602060405180830381865afa1580156108dc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109009190612ae6565b61091d576040516384f5681360e01b815260040160405180910390fd5b6000808080806109316101e0870187612b03565b81019061093e9190612b51565b9450945094509450945060006109548786611903565b905085801561096257508281105b156109805760405163da9d209360e01b815260040160405180910390fd5b600061eeee6109966101008a0160e08b01612ba2565b6001600160a01b031614610a24576109b5610100890160e08a01612ba2565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156109fb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a1f9190612bbf565b610a26565b475b905060008115610c0957610a498285610a4460a08d0135600a612cd2565b611ba0565b905061eeee610a5f6101008b0160e08c01612ba2565b6001600160a01b031614610af357610a7e6101008a0160e08b01612ba2565b60405163095ea7b360e01b8152336004820152602481018490526001600160a01b03919091169063095ea7b3906044016020604051808303816000875af1158015610acd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610af19190612ae6565b505b33630cf8e85861eeee610b0d6101008d0160e08e01612ba2565b6001600160a01b031614610b22576000610b24565b835b8b60200135858d60e0016000016020810190610b409190612ba2565b6040516001600160e01b031960e087901b168152600481019390935260248301919091526001600160a01b0316604482015260a06064820152600060a4820181905260c0608483015260c482015260e4016000604051808303818588803b158015610baa57600080fd5b505af1158015610bbe573d6000803e3d6000fd5b505060408051868152602080820187905233828401529151918e013594507f23b44985be81ddf30da326d2a65d4ee6cfe8b12699ff63d2e9b4c6c82a53058393508190036060019150a25b610c1d8685610a4460a08d0135600a612cd2565b610c279082612cde565b90506001600160a01b037f00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b16638ae9c07b60208b0135610c678487612cde565b610c796101a08e016101808f01612ba2565b610c876101c08f018f612b03565b8f6101a0016020810190610c9b9190612cf1565b60016040518863ffffffff1660e01b8152600401610cbf9796959493929190612d0e565b6020604051808303816000875af1158015610cde573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d029190612bbf565b50505050505050505050565b6040516331a9108f60e11b8152600481018690526000907f000000000000000000000000d8b4359143eda5b2d763e127ed27c77addbc47d36001600160a01b031690636352211e90602401602060405180830381865afa158015610d76573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9a9190612abb565b866019610da8838383611785565b6064861080610db8575061232886115b15610dd657604051631687249960e01b815260040160405180910390fd5b60788763ffffffff161080610df357506202a3008763ffffffff16115b15610e1157604051634b99a82760e01b815260040160405180910390fd5b60007f00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b6001600160a01b031663619306306040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e71573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e959190612abb565b6001600160a01b031663ea78803f8b6040518263ffffffff1660e01b8152600401610ec291815260200190565b602060405180830381865afa158015610edf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f039190612abb565b90506001600160a01b038116610f2c57604051632befbc9b60e01b815260040160405180910390fd5b61eeed196001600160a01b03871601610f63577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc295505b6001600160a01b03808716908216107f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98481610f9e5787610fa0565b825b82610fab5783610fad565b885b604080516001600160a01b039384166020820152929091169082015262ffffff8c16606082015260800160408051601f19818403018152908290528051602091820120611052939290917fe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b5491016001600160f81b0319815260609390931b6bffffffffffffffffffffffff191660018401526015830191909152603582015260550190565b60408051601f19818403018152918152815160209283012060008e8152600184528281206001600160a01b038c81168352945291909120549097508188169116036110b057604051630917c39960e41b815260040160405180910390fd5b85600160008d81526020019081526020016000206000896001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055508863ffffffff16608089901b176000808d81526020019081526020016000208190555081600260008d815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055508a7f0ad45a678e9246540d8e570b292142910b43d3431fd41ea7e077fd0a7d74a87260008b336040516111bb9392919092835263ffffffff9190911660208301526001600160a01b0316604082015260600190565b60405180910390a26040805160008152602081018a9052338183015290518c917fb4916f587869d0a367a4b9428fe68226803f2340d0a5edcc472b6258f7f41783919081900360600190a2604080516001600160a01b0388811682523360208301528916918d917f4f12d52a21571ed6da4506af6a540828b73258521f50cd1af9704f36e284ddbb910160405180910390a3505050505095945050505050565b60006060806101008401356112746101a0860186612b03565b8382828080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525096995091975091955050505050505b9193909250565b600060608083810135610120850135848080856113087f42555942000000000000000000000000000000000000000000000000000000006113036101808d018d612b03565b611c7f565b9092509050811561132c57808060200190518101906113279190612d6e565b945092505b5081600003611339578491505b600061134f8386610a4460808e0135600a612cd2565b60c08b0135600090815260026020526040808220549293506001600160a01b039092169161eeee906113879060608f01908f01612ba2565b6001600160a01b0316146113aa576113a560608d0160408e01612ba2565b6113cc565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b9050856000036113e9576113e68c60c00135838784611e87565b95505b858310156115635787851115611412576040516306d0bd2360e21b815260040160405180910390fd5b6040805160018082528183019092526001600160a01b038381169085161091816020015b604080516060808201835260008083526020830152918101919091528152602001906001900390816114365750506040805160608101825230815260208101899052919b50810186838c8a14611495576114908a8e612da8565b611498565b60005b604080519315156020850152911515918301919091526060820152608081018a905260a081018b905260c0016040516020818303038152906040528152508a6000815181106114e9576114e9612dbb565b602090810291909101015260006115046101608f018f612b03565b8c82828080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091509091509b509b509b505050505050505050506112b7565b6101208c01356115776101608e018e612b03565b8b82828080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091509091509a509a509a5050505050505050509193909250565b6000806115e683850185612823565b909250905060006001600160a01b03821661eeee146116055781611627565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b60008481526001602090815260408083206001600160a01b03858116855292529091205491925016331461166e576040516384f5681360e01b815260040160405180910390fd5b600080881261167d578761167f565b865b905061eeed196001600160a01b03841601611709577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b1580156116ef57600080fd5b505af1158015611703573d6000803e3d6000fd5b50505050505b60405163a9059cbb60e01b8152336004820152602481018290526001600160a01b0383169063a9059cbb906044016020604051808303816000875af1158015611756573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061177a9190612ae6565b505050505050505050565b336001600160a01b03841614801590611839575060405163c161c93f60e01b81523360048201526001600160a01b03848116602483015260448201849052606482018390527f0000000000000000000000006f3c5afca0c9edf3926ef2ddf17c8ae6391afefb169063c161c93f90608401602060405180830381865afa158015611813573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118379190612ae6565b155b80156118e0575060405163c161c93f60e01b81523360048201526001600160a01b03848116602483015260006044830152606482018390527f0000000000000000000000006f3c5afca0c9edf3926ef2ddf17c8ae6391afefb169063c161c93f90608401602060405180830381865afa1580156118ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118de9190612ae6565b155b156118fe5760405163075fd2b160e01b815260040160405180910390fd5b505050565b60006101008301803590829061eeee906119209060e08801612ba2565b6001600160a01b0316146119445761193f610100860160e08701612ba2565b611966565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b60208087013560009081526001825260408082206001600160a01b0380861684529352902054919250168063128acb0830871586896119b4576119af6401000276a36001612dd1565b6119d3565b6119d3600173fffd8963efd1fc6a506488495d951d5263988d26612df8565b60208c01356119e96101008e0160e08f01612ba2565b604051602001611a0c9291909182526001600160a01b0316602082015260400190565b6040516020818303038152906040526040518663ffffffff1660e01b8152600401611a3b959493929190612e18565b60408051808303816000875af1925050508015611a75575060408051601f3d908101601f19168201909252611a7291810190612d6e565b60015b611a8557600093505050506105e0565b86611a905780611a92565b815b611a9b90612e5e565b604051631665bc0f60e01b815230600482015260208a013560248201526044810182905260a06064820152600060a4820152600160848201529096507f00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b6001600160a01b03169250631665bc0f915060c401600060405180830381600087803b158015611b2757600080fd5b505af1158015611b3b573d6000803e3d6000fd5b5050604080518681526001600160a01b0385166020828101919091529181018890523360608201529089013592507f84368bfe147605fe15d2ca558fb0ab52664fb9e27d640457122c6796608e6fdf915060800160405180910390a250505092915050565b6000808060001985870985870292508281108382030391505080600003611bda57838281611bd057611bd0612e7a565b0492505050611c78565b838110611c1057604051630c740aef60e31b81526004810187905260248101869052604481018590526064015b60405180910390fd5b600084868809851960019081018716968790049682860381900495909211909303600082900391909104909201919091029190911760038402600290811880860282030280860282030280860282030280860282030280860282030280860290910302029150505b9392505050565b6000606060258311611ca35750506040805160208101909152600080825290611e7f565b60008484611cb360046020612cde565b818110611cc257611cc2612dbb565b919091013560f81c9150602090505b60008686611ce0600485612cde565b818110611cef57611cef612dbb565b9050013560f81c60f81b6001600160f81b03191614158015611d1a5750611d17602083612e90565b81105b15611e7c5760008686611d2e600485612cde565b818110611d3d57611d3d612dbb565b919091013560f81c9150506001600160e01b03198816878388611d61600483612cde565b92611d6e93929190612ea7565b611d7791612ed1565b6001600160e01b03191603611e73576000611d93602085612e90565b611d9e600985612cde565b101580611dd457508787611db3600986612cde565b818110611dc257611dc2612dbb565b909101356001600160f81b0319161590505b611e0c5760208888611de7600987612cde565b818110611df657611df6612dbb565b611e079392013560f81c9050612e90565b611e0e565b865b905060018888611e1f602086612e90565b611e2b92859290612ea7565b81818080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250959b50919950611e7f98505050505050505050565b50600501611cd1565b50505b935093915050565b60008481526001602090815260408083206001600160a01b0380861685529252808320548151633850c7bd60e01b815291519216918291633850c7bd9160048083019260e09291908290030181865afa925050508015611f04575060408051601f3d908101601f19168201909252611f0191810190612f13565b60015b611f12576000915050611f8b565b80611f2857600098505050505050505050611f8b565b50505050505050600086815260208190526040812054908190608082901c90611f518584611f93565b509050611f608189898c6121dd565b9550612710611f6f8388612e90565b611f799190612fb2565b611f839087612da8565b955050505050505b949350505050565b6000808263ffffffff16600003611fd15760405162461bcd60e51b8152602060048201526002602482015261042560f41b6044820152606401611c07565b604080516002808252606082018352600092602083019080368337019050509050838160008151811061200657612006612dbb565b602002602001019063ffffffff16908163ffffffff168152505060008160018151811061203557612035612dbb565b602002602001019063ffffffff16908163ffffffff1681525050600080866001600160a01b031663883bdbfd846040518263ffffffff1660e01b815260040161207e9190612fc6565b600060405180830381865afa15801561209b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526120c391908101906130d9565b915091506000826000815181106120dc576120dc612dbb565b6020026020010151836001815181106120f7576120f7612dbb565b602002602001015161210991906131a5565b905060008260008151811061212057612120612dbb565b60200260200101518360018151811061213b5761213b612dbb565b602002602001015161214d9190612df8565b905061215f63ffffffff8916836131d2565b965060008260060b128015612185575061217f63ffffffff891683613210565b60060b15155b15612198578661219481613232565b9750505b60006121b16001600160a01b0363ffffffff8b16613255565b90506121ce640100000000600160c01b03602084901b1682613287565b96505050505050509250929050565b6000806121e9866122eb565b90506001600160801b036001600160a01b0382161161226f5760006122176001600160a01b03831680612e90565b9050836001600160a01b0316856001600160a01b03161061224f5761224a600160c01b876001600160801b03168361260e565b612267565b61226781876001600160801b0316600160c01b61260e565b9250506122e2565b600061228e6001600160a01b038316806801000000000000000061260e565b9050836001600160a01b0316856001600160a01b0316106122c6576122c1600160801b876001600160801b03168361260e565b6122de565b6122de81876001600160801b0316600160801b61260e565b9250505b50949350505050565b60008060008360020b12612302578260020b61230a565b8260020b6000035b9050620d89e8811115612330576040516315e4079d60e11b815260040160405180910390fd5b60008160011660000361234757600160801b612359565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561238d576ffff97272373d413259a46990580e213a0260801c5b60048216156123ac576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156123cb576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156123ea576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612409576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612428576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612447576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612467576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612487576ff987a7253ac413176f2b074cf7815e540260801c5b6104008216156124a7576ff3392b0822b70005940c7a398e4b70f30260801c5b6108008216156124c7576fe7159475a2c29b7443b29c7fa6e889d90260801c5b6110008216156124e7576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612507576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612527576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612547576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612568576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615612588576e5d6af8dedb81196699c329225ee6040260801c5b620400008216156125a7576d2216e584f5fa1ea926041bedfe980260801c5b620800008216156125c4576b048a170391f7dc42444e8fa20260801c5b60008460020b13156125e55780600019816125e1576125e1612e7a565b0490505b6401000000008106156125f95760016125fc565b60005b60ff16602082901c0192505050919050565b6000808060001985870985870292508281108382030391505080600003612647576000841161263c57600080fd5b508290049050611c78565b80841161265357600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b6000602082840312156126d257600080fd5b81356001600160e01b031981168114611c7857600080fd5b803563ffffffff811681146126fe57600080fd5b919050565b6000806040838503121561271657600080fd5b82359150612726602084016126ea565b90509250929050565b60006020828403121561274157600080fd5b5035919050565b6000806040838503121561275b57600080fd5b50508035926020909101359150565b60006020828403121561277c57600080fd5b813567ffffffffffffffff81111561279357600080fd5b82016102208185031215611c7857600080fd5b6001600160a01b03811681146127bb57600080fd5b50565b600080600080600060a086880312156127d657600080fd5b85359450602086013562ffffff811681146127f057600080fd5b93506127fe604087016126ea565b9250606086013591506080860135612815816127a6565b809150509295509295909350565b6000806040838503121561283657600080fd5b823591506020830135612848816127a6565b809150509250929050565b60006020828403121561286557600080fd5b813567ffffffffffffffff81111561287c57600080fd5b82016101e08185031215611c7857600080fd5b6000815180845260005b818110156128b557602081850181015186830182015201612899565b506000602082860101526020601f19601f83011685010191505092915050565b60006060858352602081818501526128ef8285018761288f565b6040858203818701528187518084528484019150848160051b850101858a0160005b8381101561296157868303601f19018552815180516001600160a01b0316845288810151898501528601518684018a905261294e8a85018261288f565b9589019593505090870190600101612911565b50909c9b505050505050505050505050565b60006020828403121561298557600080fd5b813567ffffffffffffffff81111561299c57600080fd5b82016101a08185031215611c7857600080fd5b60006060858352602081818501526129c98285018761288f565b6040858203818701528187518084528484019150848160051b850101858a0160005b8381101561296157868303601f19018552815180516001600160a01b0316845288810151898501528601518684018a9052612a288a85018261288f565b95890195935050908701906001016129eb565b60008060008060608587031215612a5157600080fd5b8435935060208501359250604085013567ffffffffffffffff80821115612a7757600080fd5b818701915087601f830112612a8b57600080fd5b813581811115612a9a57600080fd5b886020828501011115612aac57600080fd5b95989497505060200194505050565b600060208284031215612acd57600080fd5b8151611c78816127a6565b80151581146127bb57600080fd5b600060208284031215612af857600080fd5b8151611c7881612ad8565b6000808335601e19843603018112612b1a57600080fd5b83018035915067ffffffffffffffff821115612b3557600080fd5b602001915036819003821315612b4a57600080fd5b9250929050565b600080600080600060a08688031215612b6957600080fd5b8535612b7481612ad8565b94506020860135612b8481612ad8565b94979496505050506040830135926060810135926080909101359150565b600060208284031215612bb457600080fd5b8135611c78816127a6565b600060208284031215612bd157600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600181815b80851115612c29578160001904821115612c0f57612c0f612bd8565b80851615612c1c57918102915b93841c9390800290612bf3565b509250929050565b600082612c40575060016105e0565b81612c4d575060006105e0565b8160018114612c635760028114612c6d57612c89565b60019150506105e0565b60ff841115612c7e57612c7e612bd8565b50506001821b6105e0565b5060208310610133831016604e8410600b8410161715612cac575081810a6105e0565b612cb68383612bee565b8060001904821115612cca57612cca612bd8565b029392505050565b6000611c788383612c31565b808201808211156105e0576105e0612bd8565b600060208284031215612d0357600080fd5b8135611c7881612ad8565b878152602081018790526001600160a01b038616604082015260c0606082018190528101849052838560e0830137600060e0858301810191909152921515608082015290151560a0820152601f909201601f191690910101949350505050565b60008060408385031215612d8157600080fd5b505080516020909101519092909150565b634e487b7160e01b600052604160045260246000fd5b818103818111156105e0576105e0612bd8565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b03818116838216019080821115612df157612df1612bd8565b5092915050565b6001600160a01b03828116828216039080821115612df157612df1612bd8565b6001600160a01b0386811682528515156020830152604082018590528316606082015260a060808201819052600090612e539083018461288f565b979650505050505050565b6000600160ff1b8201612e7357612e73612bd8565b5060000390565b634e487b7160e01b600052601260045260246000fd5b80820281158282048414176105e0576105e0612bd8565b60008085851115612eb757600080fd5b83861115612ec457600080fd5b5050820193919092039150565b6001600160e01b03198135818116916004851015612ef95780818660040360031b1b83161692505b505092915050565b805161ffff811681146126fe57600080fd5b600080600080600080600060e0888a031215612f2e57600080fd5b8751612f39816127a6565b8097505060208801518060020b8114612f5157600080fd5b9550612f5f60408901612f01565b9450612f6d60608901612f01565b9350612f7b60808901612f01565b925060a088015160ff81168114612f9157600080fd5b60c0890151909250612fa281612ad8565b8091505092959891949750929550565b600082612fc157612fc1612e7a565b500490565b6020808252825182820181905260009190848201906040850190845b8181101561300457835163ffffffff1683529284019291840191600101612fe2565b50909695505050505050565b604051601f8201601f1916810167ffffffffffffffff8111828210171561303957613039612d92565b604052919050565b600067ffffffffffffffff82111561305b5761305b612d92565b5060051b60200190565b600082601f83011261307657600080fd5b8151602061308b61308683613041565b613010565b82815260059290921b840181019181810190868411156130aa57600080fd5b8286015b848110156130ce5780516130c1816127a6565b83529183019183016130ae565b509695505050505050565b600080604083850312156130ec57600080fd5b825167ffffffffffffffff8082111561310457600080fd5b818501915085601f83011261311857600080fd5b8151602061312861308683613041565b82815260059290921b8401810191818101908984111561314757600080fd5b948201945b838610156131755785518060060b81146131665760008081fd5b8252948201949082019061314c565b9188015191965090935050508082111561318e57600080fd5b5061319b85828601613065565b9150509250929050565b600682810b9082900b03667fffffffffffff198112667fffffffffffff821317156105e0576105e0612bd8565b60008160060b8360060b806131e9576131e9612e7a565b667fffffffffffff1982146000198214161561320757613207612bd8565b90059392505050565b60008260060b8061322357613223612e7a565b808360060b0791505092915050565b60008160020b627fffff19810361324b5761324b612bd8565b6000190192915050565b6001600160c01b0382811682821681810283169291811582850482141761327e5761327e612bd8565b50505092915050565b60006001600160c01b03838116806132a1576132a1612e7a565b9216919091049291505056fea264697066735822122069dd9d2219c65572308db0914e887be9a2419a92d6707d2ebe99b5ec3da9803a64736f6c63430008150033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98400000000000000000000000065572fb928b46f9adb7cfe5a4c41226f636161ea00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b4255594200000000000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _weth (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [1] : _factory (address): 0x1F98431c8aD98523631AE4a59f267346ea31F984
Arg [2] : _directory (address): 0x65572FB928b46f9aDB7cfe5A4c41226F636161ea
Arg [3] : _controller (address): 0x97a5b9D9F0F7cD676B69f584F29048D0Ef4BB59b
Arg [4] : _delegateId (bytes4): 0x42555942

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [1] : 0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984
Arg [2] : 00000000000000000000000065572fb928b46f9adb7cfe5a4c41226f636161ea
Arg [3] : 00000000000000000000000097a5b9d9f0f7cd676b69f584f29048d0ef4bb59b
Arg [4] : 4255594200000000000000000000000000000000000000000000000000000000


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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