ETH Price: $2,938.27 (-0.66%)

Contract

0x5d5B129a3d2FC95589006Df0d8F513440489eEC5

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
LeverageLSTZapper

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 5 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

import "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";

import "./GasCompZapper.sol";
import "../Dependencies/Constants.sol";

contract LeverageLSTZapper is GasCompZapper, ILeverageZapper {
    using SafeERC20 for IERC20;

    constructor(IAddressesRegistry _addressesRegistry, IFlashLoanProvider _flashLoanProvider, IExchange _exchange)
        GasCompZapper(_addressesRegistry, _flashLoanProvider, _exchange)
    {
        // Approval of WETH and Coll to BorrowerOperations is done in parent GasCompZapper
        // Approve Bold to exchange module (Coll is approved in parent GasCompZapper)
        boldToken.approve(address(_exchange), type(uint256).max);
    }

    function openLeveragedTroveWithRawETH(OpenLeveragedTroveParams calldata _params) external payable {
        require(msg.value == ETH_GAS_COMPENSATION, "LZ: Wrong ETH");
        require(
            _params.batchManager == address(0) || _params.annualInterestRate == 0,
            "LZ: Cannot choose interest if joining a batch"
        );

        // Set initial balances to make sure there are not lefovers
        InitialBalances memory initialBalances;
        _setInitialTokensAndBalances(collToken, boldToken, initialBalances);

        // Convert ETH to WETH
        WETH.deposit{value: msg.value}();

        // Pull own coll
        collToken.safeTransferFrom(msg.sender, address(this), _params.collAmount);

        // Flash loan coll
        flashLoanProvider.makeFlashLoan(
            collToken, _params.flashLoanAmount, IFlashLoanProvider.Operation.OpenTrove, abi.encode(msg.sender, _params)
        );

        // return leftovers to user
        _returnLeftovers(initialBalances);
    }

    // Callback from the flash loan provider
    function receiveFlashLoanOnOpenLeveragedTrove(
        address _originalSender,
        OpenLeveragedTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external override {
        require(msg.sender == address(flashLoanProvider), "LZ: Caller not FlashLoan provider");

        uint256 totalCollAmount = _params.collAmount + _effectiveFlashLoanAmount;
        // We compute boldAmount off-chain for efficiency

        // Open trove
        uint256 troveId;
        uint256 index = _getTroveIndex(_originalSender, _params.ownerIndex);
        if (_params.batchManager == address(0)) {
            troveId = borrowerOperations.openTrove(
                _params.owner,
                index,
                totalCollAmount,
                _params.boldAmount,
                _params.upperHint,
                _params.lowerHint,
                _params.annualInterestRate,
                _params.maxUpfrontFee,
                // Add this contract as add/receive manager to be able to fully adjust trove,
                // while keeping the same management functionality
                address(this), // add manager
                address(this), // remove manager
                address(this) // receiver for remove manager
            );
        } else {
            IBorrowerOperations.OpenTroveAndJoinInterestBatchManagerParams memory
                openTroveAndJoinInterestBatchManagerParams = IBorrowerOperations
                    .OpenTroveAndJoinInterestBatchManagerParams({
                    owner: _params.owner,
                    ownerIndex: index,
                    collAmount: totalCollAmount,
                    boldAmount: _params.boldAmount,
                    upperHint: _params.upperHint,
                    lowerHint: _params.lowerHint,
                    interestBatchManager: _params.batchManager,
                    maxUpfrontFee: _params.maxUpfrontFee,
                    // Add this contract as add/receive manager to be able to fully adjust trove,
                    // while keeping the same management functionality
                    addManager: address(this), // add manager
                    removeManager: address(this), // remove manager
                    receiver: address(this) // receiver for remove manager
                });
            troveId =
                borrowerOperations.openTroveAndJoinInterestBatchManager(openTroveAndJoinInterestBatchManagerParams);
        }

        // Set add/remove managers
        _setAddManager(troveId, _params.addManager);
        _setRemoveManagerAndReceiver(troveId, _params.removeManager, _params.receiver);

        // Swap Bold to Coll
        exchange.swapFromBold(_params.boldAmount, _params.flashLoanAmount);

        // Send coll back to return flash loan
        collToken.safeTransfer(address(flashLoanProvider), _params.flashLoanAmount);
    }

    function leverUpTrove(LeverUpTroveParams calldata _params) external {
        address owner = troveNFT.ownerOf(_params.troveId);
        address receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_params.troveId, owner);
        _requireZapperIsReceiver(_params.troveId);

        // Set initial balances to make sure there are not lefovers
        InitialBalances memory initialBalances;
        _setInitialTokensBalancesAndReceiver(collToken, boldToken, initialBalances, receiver);

        // Flash loan coll
        flashLoanProvider.makeFlashLoan(
            collToken, _params.flashLoanAmount, IFlashLoanProvider.Operation.LeverUpTrove, abi.encode(_params)
        );

        // return leftovers to user
        _returnLeftovers(initialBalances);
    }

    // Callback from the flash loan provider
    function receiveFlashLoanOnLeverUpTrove(LeverUpTroveParams calldata _params, uint256 _effectiveFlashLoanAmount)
        external
        override
    {
        require(msg.sender == address(flashLoanProvider), "LZ: Caller not FlashLoan provider");

        // Adjust trove
        // With the received coll from flash loan, we increase both the trove coll and debt
        borrowerOperations.adjustTrove(
            _params.troveId,
            _effectiveFlashLoanAmount, // flash loan amount minus fee
            true, // _isCollIncrease
            _params.boldAmount,
            true, // _isDebtIncrease
            _params.maxUpfrontFee
        );

        // Swap Bold to Coll
        // No need to use a min: if the obtained amount is not enough, the flash loan return below won’t be enough
        // And the flash loan provider will revert after this function exits
        // The frontend should calculate in advance the `_params.boldAmount` needed for this to work
        exchange.swapFromBold(_params.boldAmount, _params.flashLoanAmount);

        // Send coll back to return flash loan
        collToken.safeTransfer(address(flashLoanProvider), _params.flashLoanAmount);
    }

    function leverDownTrove(LeverDownTroveParams calldata _params) external {
        address owner = troveNFT.ownerOf(_params.troveId);
        address receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_params.troveId, owner);
        _requireZapperIsReceiver(_params.troveId);

        // Set initial balances to make sure there are not lefovers
        InitialBalances memory initialBalances;
        _setInitialTokensBalancesAndReceiver(collToken, boldToken, initialBalances, receiver);

        // Flash loan coll
        flashLoanProvider.makeFlashLoan(
            collToken, _params.flashLoanAmount, IFlashLoanProvider.Operation.LeverDownTrove, abi.encode(_params)
        );

        // return leftovers to user
        _returnLeftovers(initialBalances);
    }

    // Callback from the flash loan provider
    function receiveFlashLoanOnLeverDownTrove(LeverDownTroveParams calldata _params, uint256 _effectiveFlashLoanAmount)
        external
        override
    {
        require(msg.sender == address(flashLoanProvider), "LZ: Caller not FlashLoan provider");

        // Swap Coll from flash loan to Bold, so we can repay and downsize trove
        // We swap the flash loan minus the flash loan fee
        // The frontend should calculate in advance the `_params.minBoldAmount` to achieve the desired leverage ratio
        // (with some slippage tolerance)
        uint256 receivedBoldAmount = exchange.swapToBold(_effectiveFlashLoanAmount, _params.minBoldAmount);

        // Adjust trove
        borrowerOperations.adjustTrove(
            _params.troveId,
            _params.flashLoanAmount,
            false, // _isCollIncrease
            receivedBoldAmount,
            false, // _isDebtIncrease
            0
        );

        // Send coll back to return flash loan
        collToken.safeTransfer(address(flashLoanProvider), _params.flashLoanAmount);
    }

    // As formulas are symmetrical, it can be used in both ways
    function leverageRatioToCollateralRatio(uint256 _inputRatio) external pure returns (uint256) {
        return _inputRatio * DECIMAL_PRECISION / (_inputRatio - DECIMAL_PRECISION);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

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

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

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

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

import "openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";

import "./BaseZapper.sol";
import "../Dependencies/Constants.sol";

contract GasCompZapper is BaseZapper {
    using SafeERC20 for IERC20;

    IERC20 public immutable collToken;

    constructor(IAddressesRegistry _addressesRegistry, IFlashLoanProvider _flashLoanProvider, IExchange _exchange)
        BaseZapper(_addressesRegistry, _flashLoanProvider, _exchange)
    {
        collToken = _addressesRegistry.collToken();
        require(address(WETH) != address(collToken), "GCZ: Wrong coll branch");

        // Approve WETH to BorrowerOperations
        WETH.approve(address(borrowerOperations), type(uint256).max);
        // Approve coll to BorrowerOperations
        collToken.approve(address(borrowerOperations), type(uint256).max);
        // Approve Coll to exchange module (for closeTroveFromCollateral)
        //collToken.approve(address(_exchange), type(uint256).max);
    }

    function openTroveWithRawETH(OpenTroveParams calldata _params) external payable returns (uint256) {
        require(msg.value == ETH_GAS_COMPENSATION, "GCZ: Wrong ETH");
        require(
            _params.batchManager == address(0) || _params.annualInterestRate == 0,
            "GCZ: Cannot choose interest if joining a batch"
        );

        // Convert ETH to WETH
        WETH.deposit{value: msg.value}();

        // Pull coll
        collToken.safeTransferFrom(msg.sender, address(this), _params.collAmount);

        uint256 troveId;
        // Include sender in index
        uint256 index = _getTroveIndex(_params.ownerIndex);
        if (_params.batchManager == address(0)) {
            troveId = borrowerOperations.openTrove(
                _params.owner,
                index,
                _params.collAmount,
                _params.boldAmount,
                _params.upperHint,
                _params.lowerHint,
                _params.annualInterestRate,
                _params.maxUpfrontFee,
                // Add this contract as add/receive manager to be able to fully adjust trove,
                // while keeping the same management functionality
                address(this), // add manager
                address(this), // remove manager
                address(this) // receiver for remove manager
            );
        } else {
            IBorrowerOperations.OpenTroveAndJoinInterestBatchManagerParams memory
                openTroveAndJoinInterestBatchManagerParams = IBorrowerOperations
                    .OpenTroveAndJoinInterestBatchManagerParams({
                    owner: _params.owner,
                    ownerIndex: index,
                    collAmount: _params.collAmount,
                    boldAmount: _params.boldAmount,
                    upperHint: _params.upperHint,
                    lowerHint: _params.lowerHint,
                    interestBatchManager: _params.batchManager,
                    maxUpfrontFee: _params.maxUpfrontFee,
                    // Add this contract as add/receive manager to be able to fully adjust trove,
                    // while keeping the same management functionality
                    addManager: address(this), // add manager
                    removeManager: address(this), // remove manager
                    receiver: address(this) // receiver for remove manager
                });
            troveId =
                borrowerOperations.openTroveAndJoinInterestBatchManager(openTroveAndJoinInterestBatchManagerParams);
        }

        boldToken.transfer(msg.sender, _params.boldAmount);

        // Set add/remove managers
        _setAddManager(troveId, _params.addManager);
        _setRemoveManagerAndReceiver(troveId, _params.removeManager, _params.receiver);

        return troveId;
    }

    function addColl(uint256 _troveId, uint256 _amount) external {
        address owner = troveNFT.ownerOf(_troveId);
        _requireSenderIsOwnerOrAddManager(_troveId, owner);

        IBorrowerOperations borrowerOperationsCached = borrowerOperations;

        // Pull coll
        collToken.safeTransferFrom(msg.sender, address(this), _amount);

        borrowerOperationsCached.addColl(_troveId, _amount);
    }

    function withdrawColl(uint256 _troveId, uint256 _amount) external {
        address owner = troveNFT.ownerOf(_troveId);
        address receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
        _requireZapperIsReceiver(_troveId);

        borrowerOperations.withdrawColl(_troveId, _amount);

        // Send coll left
        collToken.safeTransfer(receiver, _amount);
    }

    function withdrawBold(uint256 _troveId, uint256 _boldAmount, uint256 _maxUpfrontFee) external {
        address owner = troveNFT.ownerOf(_troveId);
        address receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
        _requireZapperIsReceiver(_troveId);

        borrowerOperations.withdrawBold(_troveId, _boldAmount, _maxUpfrontFee);

        // Send Bold
        boldToken.transfer(receiver, _boldAmount);
    }

    function repayBold(uint256 _troveId, uint256 _boldAmount) external {
        address owner = troveNFT.ownerOf(_troveId);
        _requireSenderIsOwnerOrAddManager(_troveId, owner);

        // Set initial balances to make sure there are not lefovers
        InitialBalances memory initialBalances;
        _setInitialTokensAndBalances(collToken, boldToken, initialBalances);

        // Pull Bold
        boldToken.transferFrom(msg.sender, address(this), _boldAmount);

        borrowerOperations.repayBold(_troveId, _boldAmount);

        // return leftovers to user
        _returnLeftovers(initialBalances);
    }

    function adjustTrove(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        uint256 _maxUpfrontFee
    ) external {
        InitialBalances memory initialBalances;
        address receiver =
            _adjustTrovePre(_troveId, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease, initialBalances);
        borrowerOperations.adjustTrove(
            _troveId, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease, _maxUpfrontFee
        );
        _adjustTrovePost(_collChange, _isCollIncrease, _boldChange, _isDebtIncrease, receiver, initialBalances);
    }

    function adjustZombieTrove(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external {
        InitialBalances memory initialBalances;
        address receiver =
            _adjustTrovePre(_troveId, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease, initialBalances);
        borrowerOperations.adjustZombieTrove(
            _troveId, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease, _upperHint, _lowerHint, _maxUpfrontFee
        );
        _adjustTrovePost(_collChange, _isCollIncrease, _boldChange, _isDebtIncrease, receiver, initialBalances);
    }

    function _adjustTrovePre(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        InitialBalances memory _initialBalances
    ) internal returns (address) {
        address receiver = _checkAdjustTroveManagers(_troveId, _collChange, _isCollIncrease, _isDebtIncrease);

        // Set initial balances to make sure there are not lefovers
        _setInitialTokensAndBalances(collToken, boldToken, _initialBalances);

        // Pull coll
        if (_isCollIncrease) {
            collToken.safeTransferFrom(msg.sender, address(this), _collChange);
        }

        // Pull Bold
        if (!_isDebtIncrease) {
            boldToken.transferFrom(msg.sender, address(this), _boldChange);
        }

        return receiver;
    }

    function _adjustTrovePost(
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        address _receiver,
        InitialBalances memory _initialBalances
    ) internal {
        // Send coll left
        if (!_isCollIncrease) {
            collToken.safeTransfer(_receiver, _collChange);
        }

        // Send Bold
        if (_isDebtIncrease) {
            boldToken.transfer(_receiver, _boldChange);
        }

        // return leftovers to user
        _returnLeftovers(_initialBalances);
    }

    function closeTroveToRawETH(uint256 _troveId) external {
        address owner = troveNFT.ownerOf(_troveId);
        address payable receiver = payable(_requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner));
        _requireZapperIsReceiver(_troveId);

        // pull Bold for repayment
        LatestTroveData memory trove = troveManager.getLatestTroveData(_troveId);
        boldToken.transferFrom(msg.sender, address(this), trove.entireDebt);

        borrowerOperations.closeTrove(_troveId);

        // Send coll left
        collToken.safeTransfer(receiver, trove.entireColl);

        // Send gas compensation
        WETH.withdraw(ETH_GAS_COMPENSATION);
        (bool success,) = receiver.call{value: ETH_GAS_COMPENSATION}("");
        require(success, "GCZ: Sending ETH failed");
    }

    function closeTroveFromCollateral(uint256 _troveId, uint256 _flashLoanAmount, uint256 _minExpectedCollateral)
        external
        override
    {
        address owner = troveNFT.ownerOf(_troveId);
        address payable receiver = payable(_requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner));
        _requireZapperIsReceiver(_troveId);

        CloseTroveParams memory params = CloseTroveParams({
            troveId: _troveId,
            flashLoanAmount: _flashLoanAmount,
            minExpectedCollateral: _minExpectedCollateral,
            receiver: receiver
        });

        // Set initial balances to make sure there are not lefovers
        InitialBalances memory initialBalances;
        initialBalances.tokens[0] = collToken;
        initialBalances.tokens[1] = boldToken;
        _setInitialBalancesAndReceiver(initialBalances, receiver);

        // Flash loan coll
        flashLoanProvider.makeFlashLoan(
            collToken, _flashLoanAmount, IFlashLoanProvider.Operation.CloseTrove, abi.encode(params)
        );

        // return leftovers to user
        _returnLeftovers(initialBalances);
    }

    function receiveFlashLoanOnCloseTroveFromCollateral(
        CloseTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external {
        require(msg.sender == address(flashLoanProvider), "GCZ: Caller not FlashLoan provider");

        LatestTroveData memory trove = troveManager.getLatestTroveData(_params.troveId);
        uint256 collLeft = trove.entireColl - _params.flashLoanAmount;
        require(collLeft >= _params.minExpectedCollateral, "GCZ: Not enough collateral received");

        // Swap Coll from flash loan to Bold, so we can repay and close trove
        // We swap the flash loan minus the flash loan fee
        exchange.swapToBold(_effectiveFlashLoanAmount, trove.entireDebt);

        // We asked for a min of entireDebt in swapToBold call above, so we don’t check again here:
        //uint256 receivedBoldAmount = exchange.swapToBold(_effectiveFlashLoanAmount, trove.entireDebt);
        //require(receivedBoldAmount >= trove.entireDebt, "GCZ: Not enough BOLD obtained to repay");

        borrowerOperations.closeTrove(_params.troveId);

        // Send coll back to return flash loan
        collToken.safeTransfer(address(flashLoanProvider), _params.flashLoanAmount);

        // Send coll left
        collToken.safeTransfer(_params.receiver, collLeft);

        // Send gas compensation
        WETH.withdraw(ETH_GAS_COMPENSATION);
        (bool success,) = _params.receiver.call{value: ETH_GAS_COMPENSATION}("");
        require(success, "GCZ: Sending ETH failed");
    }

    receive() external payable {}

    // Unimplemented flash loan receive functions for leverage
    function receiveFlashLoanOnOpenLeveragedTrove(
        address _originalSender,
        ILeverageZapper.OpenLeveragedTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external virtual override {}
    function receiveFlashLoanOnLeverUpTrove(
        ILeverageZapper.LeverUpTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external virtual override {}
    function receiveFlashLoanOnLeverDownTrove(
        ILeverageZapper.LeverDownTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external virtual override {}
}

File 4 of 70 : Constants.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.24;

address constant ZERO_ADDRESS = address(0);

uint256 constant MAX_UINT256 = type(uint256).max;

uint256 constant DECIMAL_PRECISION = 1e18;
uint256 constant _100pct = DECIMAL_PRECISION;
uint256 constant _1pct = DECIMAL_PRECISION / 100;

// Amount of ETH to be locked in gas pool on opening troves
uint256 constant ETH_GAS_COMPENSATION = 0.001 ether;

// Liquidation
uint256 constant MIN_LIQUIDATION_PENALTY_SP = 5e16; // 5%
uint256 constant MAX_LIQUIDATION_PENALTY_REDISTRIBUTION = 20e16; // 20%

// Collateral branch parameters (SETH = staked ETH, i.e. wstETH / rETH)
//CCR: Critical Collateral Ratio. minimum for each collateral branch
//MCR: Minimum Collateral Ratio. minimum for each trove
//SCR: Shutdown Collateral Ratio. minimum for each collateral branch

//WETH
uint256 constant CCR_WETH = 150 * _1pct; // Branch minimum for adjustments
uint256 constant MCR_WETH = 110 * _1pct; // Trove minimum for liquidation
uint256 constant SCR_WETH = 110 * _1pct; //shutdown threshold (should be same as MCR)

//LSTs of staked eth: wstETH and rETH
uint256 constant CCR_SETH = 160 * _1pct; // Branch minimum for adjustments
uint256 constant MCR_SETH = 110 * _1pct; // Trove minimum for liquidation
uint256 constant SCR_SETH = 110 * _1pct; //shutdown threshold (should be same as MCR)

//LRT: weETH, rsETH. Liquidation restaking tokens
uint256 constant CCR_LRT = 160 * _1pct; // Branch minimum for adjustments
uint256 constant MCR_LRT = 130 * _1pct; // Trove minimum for liquidation
uint256 constant SCR_LRT = 115 * _1pct; //shutdown threshold (should be same as MCR)

//ARB. Arbitrum
uint256 constant CCR_ARB = 165 * _1pct; // Branch minimum for adjustments
uint256 constant MCR_ARB = 140 * _1pct; // Trove minimum for liquidation
uint256 constant SCR_ARB = 115 * _1pct; //shutdown threshold (should be same as MCR)

// COMP, compound
uint256 constant CCR_COMP = 165 * _1pct; // Branch minimum for adjustments
uint256 constant MCR_COMP = 140 * _1pct; // Trove minimum for liquidation
uint256 constant SCR_COMP = 115 * _1pct; //shutdown threshold (should be same as MCR)

//tBTC from threshold
uint256 constant CCR_BTC = 150 * _1pct; // Branch minimum for adjustments
uint256 constant MCR_BTC = 115 * _1pct; // Trove minimum for liquidation
uint256 constant SCR_BTC = 110 * _1pct; //shutdown threshold (should be same as MCR)

// Batch CR buffer (same for all branches for now)
// On top of MCR to join a batch, or adjust inside a batch
uint256 constant BCR_ALL = 10 * _1pct;

uint256 constant LIQUIDATION_PENALTY_SP_WETH = 5 * _1pct;
uint256 constant LIQUIDATION_PENALTY_SP_SETH = 5 * _1pct;

//used when stability pool is empty. 
uint256 constant LIQUIDATION_PENALTY_REDISTRIBUTION_WETH = 10 * _1pct;
uint256 constant LIQUIDATION_PENALTY_REDISTRIBUTION_SETH = 20 * _1pct;

// Fraction of collateral awarded to liquidator
uint256 constant COLL_GAS_COMPENSATION_DIVISOR = 800; // dividing by 800 yields 0.125%
//todo: 
uint256 constant COLL_GAS_COMPENSATION_CAP = 10000000000000000 wei; // Max coll gas compensation capped at 2 ETH

// Minimum amount of net Bold debt a trove must have. 500 USND
uint256 constant MIN_DEBT = 500e18;

uint256 constant MIN_ANNUAL_INTEREST_RATE = _1pct / 2; // 0.5%
uint256 constant MAX_ANNUAL_INTEREST_RATE = 250 * _1pct;

// Batch management params
uint128 constant MAX_ANNUAL_BATCH_MANAGEMENT_FEE = uint128(_100pct / 10); // 10%
uint128 constant MIN_INTEREST_RATE_CHANGE_PERIOD = 1 hours; // only applies to batch managers / batched Troves

uint256 constant REDEMPTION_FEE_FLOOR = 55 * _1pct / 100; // 0.55% -> Floor $0.9945

// For the debt / shares ratio to increase by a factor 1e9
// at a average annual debt increase (compounded interest + fees) of 10%, it would take more than 217 years (log(1e9)/log(1.1))
// at a average annual debt increase (compounded interest + fees) of 50%, it would take more than 51 years (log(1e9)/log(1.5))
// The increase pace could be forced to be higher through an inflation attack,
// but precisely the fact that we have this max value now prevents the attack
uint256 constant MAX_BATCH_SHARES_RATIO = 1e9;

// Half-life of 6h. 6h = 360 min
// (1/2) = d^360 => d = (1/2)^(1/360)
uint256 constant REDEMPTION_MINUTE_DECAY_FACTOR = 998076443575628800;

// BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.
// Corresponds to (1 / ALPHA) in the white paper.
uint256 constant REDEMPTION_BETA = 1;

// To prevent redemptions unless Bold depegs below 0.95 and allow the system to take off
uint256 constant INITIAL_BASE_RATE = _100pct; // 100% initial redemption rate

// Discount to be used once the shutdown thas been triggered
uint256 constant URGENT_REDEMPTION_BONUS = 2e16; // 2%

uint256 constant ONE_MINUTE = 1 minutes;
uint256 constant ONE_YEAR = 365 days;
uint256 constant UPFRONT_INTEREST_PERIOD = 7 days;
uint256 constant INTEREST_RATE_ADJ_COOLDOWN = 7 days;

uint256 constant SP_YIELD_SPLIT = 75 * _1pct; // 75%

uint256 constant MIN_BOLD_IN_SP = 1e18;

// Dummy contract that lets legacy Hardhat tests query some of the constants
contract Constants {
    uint256 public constant _ETH_GAS_COMPENSATION = ETH_GAS_COMPENSATION;
    uint256 public constant _MIN_DEBT = MIN_DEBT;
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

import "../Interfaces/IWETH.sol";
import "../Interfaces/IAddressesRegistry.sol";
import "../Interfaces/IBorrowerOperations.sol";
import "../Dependencies/AddRemoveManagers.sol";
import "./LeftoversSweep.sol";
import "./Interfaces/IFlashLoanProvider.sol";
import "./Interfaces/IFlashLoanReceiver.sol";
import "./Interfaces/IExchange.sol";
import "./Interfaces/IZapper.sol";

abstract contract BaseZapper is AddRemoveManagers, LeftoversSweep, IFlashLoanReceiver, IZapper {
    IBorrowerOperations public immutable borrowerOperations; // LST branch (i.e., not WETH as collateral)
    ITroveManager public immutable troveManager;
    IWETH public immutable WETH;
    IBoldToken public immutable boldToken;

    IFlashLoanProvider public immutable flashLoanProvider;
    IExchange public immutable exchange;

    constructor(IAddressesRegistry _addressesRegistry, IFlashLoanProvider _flashLoanProvider, IExchange _exchange)
        AddRemoveManagers(_addressesRegistry)
    {
        borrowerOperations = _addressesRegistry.borrowerOperations();
        troveManager = _addressesRegistry.troveManager();
        boldToken = _addressesRegistry.boldToken();
        WETH = _addressesRegistry.WETH();

        flashLoanProvider = _flashLoanProvider;
        exchange = _exchange;
    }

    function _requireZapperIsReceiver(uint256 _troveId) internal view {
        (, address receiver) = borrowerOperations.removeManagerReceiverOf(_troveId);
        require(receiver == address(this), "BZ: Zapper is not receiver for this trove");
    }

    function _getTroveIndex(address _sender, uint256 _ownerIndex) internal pure returns (uint256) {
        return uint256(keccak256(abi.encode(_sender, _ownerIndex)));
    }

    function _getTroveIndex(uint256 _ownerIndex) internal view returns (uint256) {
        return _getTroveIndex(msg.sender, _ownerIndex);
    }

    function _checkAdjustTroveManagers(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        bool _isDebtIncrease
    ) internal view returns (address) {
        address owner = troveNFT.ownerOf(_troveId);
        address receiver = owner;

        if ((!_isCollIncrease && _collChange > 0) || _isDebtIncrease) {
            receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
            _requireZapperIsReceiver(_troveId);
        } else {
            // RemoveManager assumes AddManager, so if the former is set, there's no need to check the latter
            _requireSenderIsOwnerOrAddManager(_troveId, owner);
            // No need to check the type of trove change for two reasons:
            // - If the check above fails, it means sender is not owner, nor AddManager, nor RemoveManager.
            //   An independent 3rd party should not be allowed here.
            // - If it's not collIncrease or debtDecrease, _requireNonZeroAdjustment would revert
        }

        return receiver;
    }

    
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IWETH is IERC20Metadata {
    function deposit() external payable;
    function withdraw(uint256 wad) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IActivePool.sol";
import "./IBoldToken.sol";
import "./IBorrowerOperations.sol";
import "./ICollSurplusPool.sol";
import "./IDefaultPool.sol";
import "./IHintHelpers.sol";
import "./IMultiTroveGetter.sol";
import "./ISortedTroves.sol";
import "./IStabilityPool.sol";
import "./ITroveManager.sol";
import "./ITroveNFT.sol";
import {IMetadataNFT} from "../NFTMetadata/MetadataNFT.sol";
import "./ICollateralRegistry.sol";
import "./IInterestRouter.sol";
import "./IPriceFeed.sol";

interface IAddressesRegistry {
    struct AddressVars {
        IERC20Metadata collToken;
        IBorrowerOperations borrowerOperations;
        ITroveManager troveManager;
        ITroveNFT troveNFT;
        IMetadataNFT metadataNFT;
        IStabilityPool stabilityPool;
        IPriceFeed priceFeed;
        IActivePool activePool;
        IDefaultPool defaultPool;
        address gasPoolAddress;
        ICollSurplusPool collSurplusPool;
        ISortedTroves sortedTroves;
        IInterestRouter interestRouter;
        IHintHelpers hintHelpers;
        IMultiTroveGetter multiTroveGetter;
        ICollateralRegistry collateralRegistry;
        IBoldToken boldToken;
        IWETH WETH;
    }

    function CCR() external returns (uint256);
    function SCR() external returns (uint256);
    function MCR() external returns (uint256);
    function BCR() external returns (uint256);
    function debtLimit() external returns (uint256);
    function LIQUIDATION_PENALTY_SP() external returns (uint256);
    function LIQUIDATION_PENALTY_REDISTRIBUTION() external returns (uint256);

    function collToken() external view returns (IERC20Metadata);
    function borrowerOperations() external view returns (IBorrowerOperations);
    function troveManager() external view returns (ITroveManager);
    function troveNFT() external view returns (ITroveNFT);
    function metadataNFT() external view returns (IMetadataNFT);
    function stabilityPool() external view returns (IStabilityPool);
    function priceFeed() external view returns (IPriceFeed);
    function activePool() external view returns (IActivePool);
    function defaultPool() external view returns (IDefaultPool);
    function gasPoolAddress() external view returns (address);
    function collSurplusPool() external view returns (ICollSurplusPool);
    function sortedTroves() external view returns (ISortedTroves);
    function interestRouter() external view returns (IInterestRouter);
    function hintHelpers() external view returns (IHintHelpers);
    function multiTroveGetter() external view returns (IMultiTroveGetter);
    function collateralRegistry() external view returns (ICollateralRegistry);
    function boldToken() external view returns (IBoldToken);
    function WETH() external returns (IWETH);

    function setAddresses(AddressVars memory _vars) external;
    function daoUpdateInterestRouter(address _interestRouterAddress) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ILiquityBase.sol";
import "./IAddRemoveManagers.sol";
import "./IBoldToken.sol";
import "./IPriceFeed.sol";
import "./ISortedTroves.sol";
import "./ITroveManager.sol";
import "./IWETH.sol";

// Common interface for the Borrower Operations.
interface IBorrowerOperations is ILiquityBase, IAddRemoveManagers {
    function CCR() external view returns (uint256);
    function MCR() external view returns (uint256);
    function SCR() external view returns (uint256);
    

    function openTrove(
        address _owner,
        uint256 _ownerIndex,
        uint256 _ETHAmount,
        uint256 _boldAmount,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _annualInterestRate,
        uint256 _maxUpfrontFee,
        address _addManager,
        address _removeManager,
        address _receiver
    ) external returns (uint256);

    struct OpenTroveAndJoinInterestBatchManagerParams {
        address owner;
        uint256 ownerIndex;
        uint256 collAmount;
        uint256 boldAmount;
        uint256 upperHint;
        uint256 lowerHint;
        address interestBatchManager;
        uint256 maxUpfrontFee;
        address addManager;
        address removeManager;
        address receiver;
    }

    function openTroveAndJoinInterestBatchManager(OpenTroveAndJoinInterestBatchManagerParams calldata _params)
        external
        returns (uint256);

    function addColl(uint256 _troveId, uint256 _ETHAmount) external;

    function withdrawColl(uint256 _troveId, uint256 _amount) external;

    function withdrawBold(uint256 _troveId, uint256 _amount, uint256 _maxUpfrontFee) external;

    function repayBold(uint256 _troveId, uint256 _amount) external;

    function closeTrove(uint256 _troveId) external;

    function adjustTrove(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _debtChange,
        bool isDebtIncrease,
        uint256 _maxUpfrontFee
    ) external;

    function adjustZombieTrove(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external;

    function adjustTroveInterestRate(
        uint256 _troveId,
        uint256 _newAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external;

    function applyPendingDebt(uint256 _troveId, uint256 _lowerHint, uint256 _upperHint) external;

    function onLiquidateTrove(uint256 _troveId) external;

    function claimCollateral() external;

    function hasBeenShutDown() external view returns (bool);
    function shutdown() external;
    function shutdownFromOracleFailure() external;

    function checkBatchManagerExists(address _batchMananger) external view returns (bool);

    // -- individual delegation --
    struct InterestIndividualDelegate {
        address account;
        uint128 minInterestRate;
        uint128 maxInterestRate;
        uint256 minInterestRateChangePeriod;
    }

    function getInterestIndividualDelegateOf(uint256 _troveId)
        external
        view
        returns (InterestIndividualDelegate memory);
    function setInterestIndividualDelegate(
        uint256 _troveId,
        address _delegate,
        uint128 _minInterestRate,
        uint128 _maxInterestRate,
        // only needed if trove was previously in a batch:
        uint256 _newAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee,
        uint256 _minInterestRateChangePeriod
    ) external;
    function removeInterestIndividualDelegate(uint256 _troveId) external;

    // -- batches --
    struct InterestBatchManager {
        uint128 minInterestRate;
        uint128 maxInterestRate;
        uint256 minInterestRateChangePeriod;
    }

    function registerBatchManager(
        uint128 minInterestRate,
        uint128 maxInterestRate,
        uint128 currentInterestRate,
        uint128 fee,
        uint128 minInterestRateChangePeriod
    ) external;
    function lowerBatchManagementFee(uint256 _newAnnualFee) external;
    function setBatchManagerAnnualInterestRate(
        uint128 _newAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external;
    function interestBatchManagerOf(uint256 _troveId) external view returns (address);
    function getInterestBatchManager(address _account) external view returns (InterestBatchManager memory);
    function setInterestBatchManager(
        uint256 _troveId,
        address _newBatchManager,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external;

    function kickFromBatch(uint256 _troveId, uint256 _upperHint, uint256 _lowerHint) external;
    
    function removeFromBatch(
        uint256 _troveId,
        uint256 _newAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external;
    function switchBatchManager(
        uint256 _troveId,
        uint256 _removeUpperHint,
        uint256 _removeLowerHint,
        address _newBatchManager,
        uint256 _addUpperHint,
        uint256 _addLowerHint,
        uint256 _maxUpfrontFee
    ) external;
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.24;

import "../Interfaces/IAddRemoveManagers.sol";
import "../Interfaces/IAddressesRegistry.sol";
import "../Interfaces/ITroveNFT.sol";

contract AddRemoveManagers is IAddRemoveManagers {
    ITroveNFT internal immutable troveNFT;

    struct RemoveManagerReceiver {
        address manager;
        address receiver;
    }

    /*
     * Mapping from TroveId to granted address for operations that "give" money to the trove (add collateral, pay debt).
     * Useful for instance for cold/hot wallet setups.
     * If its value is zero address, any address is allowed to do those operations on behalf of trove owner.
     * Otherwise, only the address in this mapping (and the trove owner) will be allowed.
     * To restrict this permission to no one, trove owner should be set in this mapping.
     */
    mapping(uint256 => address) public addManagerOf;

    /*
     * Mapping from TroveId to granted addresses for operations that "withdraw" money from the trove (withdraw collateral, borrow),
     * and for each of those addresses another address for the receiver of those withdrawn funds.
     * Useful for instance for cold/hot wallet setups or for automations.
     * Only the address in this mapping, if any, and the trove owner, will be allowed.
     * Therefore, by default this permission is restricted to no one.
     * If the receiver is zero, the owner is assumed as the receiver.
     * The Remove Manager also gets Add Manager permission.
     */
    mapping(uint256 => RemoveManagerReceiver) public removeManagerReceiverOf;

    error EmptyManager();
    error NotBorrower();
    error NotOwnerNorAddManager();
    error NotOwnerNorRemoveManager();

    event TroveNFTAddressChanged(address _newTroveNFTAddress);
    event AddManagerUpdated(uint256 indexed _troveId, address _newAddManager);
    event RemoveManagerAndReceiverUpdated(uint256 indexed _troveId, address _newRemoveManager, address _newReceiver);

    constructor(IAddressesRegistry _addressesRegistry) {
        troveNFT = _addressesRegistry.troveNFT();
        emit TroveNFTAddressChanged(address(troveNFT));
    }

    function setAddManager(uint256 _troveId, address _manager) external {
        _requireCallerIsBorrower(_troveId);
        _setAddManager(_troveId, _manager);
    }

    function _setAddManager(uint256 _troveId, address _manager) internal {
        addManagerOf[_troveId] = _manager;
        emit AddManagerUpdated(_troveId, _manager);
    }

    function setRemoveManager(uint256 _troveId, address _manager) external {
        setRemoveManagerWithReceiver(_troveId, _manager, troveNFT.ownerOf(_troveId));
    }

    function setRemoveManagerWithReceiver(uint256 _troveId, address _manager, address _receiver) public {
        _requireCallerIsBorrower(_troveId);
        _setRemoveManagerAndReceiver(_troveId, _manager, _receiver);
    }

    function _setRemoveManagerAndReceiver(uint256 _troveId, address _manager, address _receiver) internal {
        _requireNonZeroManagerUnlessWiping(_manager, _receiver);
        removeManagerReceiverOf[_troveId].manager = _manager;
        removeManagerReceiverOf[_troveId].receiver = _receiver;
        emit RemoveManagerAndReceiverUpdated(_troveId, _manager, _receiver);
    }

    function _wipeAddRemoveManagers(uint256 _troveId) internal {
        delete addManagerOf[_troveId];
        delete removeManagerReceiverOf[_troveId];
        emit AddManagerUpdated(_troveId, address(0));
        emit RemoveManagerAndReceiverUpdated(_troveId, address(0), address(0));
    }

    function _requireNonZeroManagerUnlessWiping(address _manager, address _receiver) internal pure {
        if (_manager == address(0) && _receiver != address(0)) {
            revert EmptyManager();
        }
    }

    function _requireCallerIsBorrower(uint256 _troveId) internal view {
        if (msg.sender != troveNFT.ownerOf(_troveId)) {
            revert NotBorrower();
        }
    }

    function _requireSenderIsOwnerOrAddManager(uint256 _troveId, address _owner) internal view {
        address addManager = addManagerOf[_troveId];
        if (msg.sender != _owner && addManager != address(0) && msg.sender != addManager) {
             // RemoveManager assumes AddManager permission too
            address removeManager = removeManagerReceiverOf[_troveId].manager;
            if (msg.sender != removeManager) {
                revert NotOwnerNorAddManager();
            }
        }
    }

    function _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(uint256 _troveId, address _owner)
        internal
        view
        returns (address)
    {
        address manager = removeManagerReceiverOf[_troveId].manager;
        address receiver = removeManagerReceiverOf[_troveId].receiver;
        if (msg.sender != _owner && msg.sender != manager) {
            revert NotOwnerNorRemoveManager();
        }
        if (receiver == address(0) || msg.sender != manager) {
            return _owner;
        }
        return receiver;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

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

import "../Interfaces/IBoldToken.sol";

contract LeftoversSweep {
    using SafeERC20 for IERC20;

    struct InitialBalances {
        IERC20[4] tokens; // paving the way for completely dynamic routes
        uint256[4] balances;
        address receiver;
    }

    function _setInitialTokensAndBalances(
        IERC20 _collToken,
        IBoldToken _boldToken,
        InitialBalances memory _initialBalances
    ) internal view {
        _setInitialTokensBalancesAndReceiver(_collToken, _boldToken, _initialBalances, msg.sender);
    }

    function _setInitialTokensBalancesAndReceiver(
        IERC20 _collToken,
        IBoldToken _boldToken,
        InitialBalances memory _initialBalances,
        address _receiver
    ) internal view {
        _initialBalances.tokens[0] = _collToken;
        _initialBalances.tokens[1] = _boldToken;
        _setInitialBalancesAndReceiver(_initialBalances, _receiver);
    }

    function _setInitialBalances(InitialBalances memory _initialBalances) internal view {
        _setInitialBalancesAndReceiver(_initialBalances, msg.sender);
    }

    function _setInitialBalancesAndReceiver(InitialBalances memory _initialBalances, address _receiver) internal view {
        for (uint256 i = 0; i < _initialBalances.tokens.length; i++) {
            if (address(_initialBalances.tokens[i]) == address(0)) break;

            _initialBalances.balances[i] = _initialBalances.tokens[i].balanceOf(address(this));
        }
        _initialBalances.receiver = _receiver;
    }

    function _returnLeftovers(InitialBalances memory _initialBalances) internal {
        for (uint256 i = 0; i < _initialBalances.tokens.length; i++) {
            if (address(_initialBalances.tokens[i]) == address(0)) break;

            uint256 currentBalance = _initialBalances.tokens[i].balanceOf(address(this));
            if (currentBalance > _initialBalances.balances[i]) {
                _initialBalances.tokens[i].safeTransfer(
                    _initialBalances.receiver, currentBalance - _initialBalances.balances[i]
                );
            }
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "./ILeverageZapper.sol";
import "./IFlashLoanReceiver.sol";

interface IFlashLoanProvider {
    enum Operation {
        OpenTrove,
        CloseTrove,
        LeverUpTrove,
        LeverDownTrove
    }

    function receiver() external view returns (IFlashLoanReceiver);

    function makeFlashLoan(IERC20 _token, uint256 _amount, Operation _operation, bytes calldata userData) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IZapper.sol";
import "./ILeverageZapper.sol";

interface IFlashLoanReceiver {
    function receiveFlashLoanOnOpenLeveragedTrove(
        address _originalSender,
        ILeverageZapper.OpenLeveragedTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external;
    function receiveFlashLoanOnLeverUpTrove(
        ILeverageZapper.LeverUpTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external;
    function receiveFlashLoanOnLeverDownTrove(
        ILeverageZapper.LeverDownTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external;
    function receiveFlashLoanOnCloseTroveFromCollateral(
        IZapper.CloseTroveParams calldata _params,
        uint256 _effectiveFlashLoanAmount
    ) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IExchange {
    function swapFromBold(uint256 _boldAmount, uint256 _minCollAmount) external;

    function swapToBold(uint256 _collAmount, uint256 _minBoldAmount) external returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IFlashLoanProvider.sol";
import "./IExchange.sol";

interface IZapper {
    struct OpenTroveParams {
        address owner;
        uint256 ownerIndex;
        uint256 collAmount;
        uint256 boldAmount;
        uint256 upperHint;
        uint256 lowerHint;
        uint256 annualInterestRate;
        address batchManager;
        uint256 maxUpfrontFee;
        address addManager;
        address removeManager;
        address receiver;
    }

    struct CloseTroveParams {
        uint256 troveId;
        uint256 flashLoanAmount;
        uint256 minExpectedCollateral;
        address receiver;
    }

    function flashLoanProvider() external view returns (IFlashLoanProvider);

    function exchange() external view returns (IExchange);

    function openTroveWithRawETH(OpenTroveParams calldata _params) external payable returns (uint256);

    function closeTroveFromCollateral(uint256 _troveId, uint256 _flashLoanAmount, uint256 _minExpectedCollateral)
        external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IInterestRouter.sol";
import "./IBoldRewardsReceiver.sol";
import "../Types/TroveChange.sol";

interface IActivePool {
    function defaultPoolAddress() external view returns (address);
    function borrowerOperationsAddress() external view returns (address);
    function troveManagerAddress() external view returns (address);
    // We avoid IStabilityPool here in order to prevent creating a dependency cycle that would break flattening
    function stabilityPool() external view returns (IBoldRewardsReceiver);

    function getCollBalance() external view returns (uint256);
    function getBoldDebt() external view returns (uint256);
    function lastAggUpdateTime() external view returns (uint256);
    function aggRecordedDebt() external view returns (uint256);
    function aggWeightedDebtSum() external view returns (uint256);
    function aggBatchManagementFees() external view returns (uint256);
    function aggWeightedBatchManagementFeeSum() external view returns (uint256);
    function calcPendingAggInterest() external view returns (uint256);
    function calcPendingSPYield() external view returns (uint256);
    function calcPendingAggBatchManagementFee() external view returns (uint256);
    function getNewApproxAvgInterestRateFromTroveChange(TroveChange calldata _troveChange)
        external
        view
        returns (uint256);

    function mintAggInterest() external;
    function mintAggInterestAndAccountForTroveChange(TroveChange calldata _troveChange, address _batchManager)
        external;
    function mintBatchManagementFeeAndAccountForChange(TroveChange calldata _troveChange, address _batchAddress)
        external;

    function setShutdownFlag() external;
    function hasBeenShutDown() external view returns (bool);
    function shutdownTime() external view returns (uint256);

    function sendColl(address _account, uint256 _amount) external;
    function sendCollToDefaultPool(uint256 _amount) external;
    function receiveColl(uint256 _amount) external;
    function accountForReceivedColl(uint256 _amount) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol";
import "openzeppelin-contracts/contracts/interfaces/IERC5267.sol";

import { ISuperToken } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol";


interface IBoldTokenCustom is IERC20Permit, IERC5267 {
    function collateralRegistryAddress() external view returns (address);
    

    function setBranchAddresses(
        address _troveManagerAddress,
        address _stabilityPoolAddress,
        address _borrowerOperationsAddress,
        address _activePoolAddress
    ) external;

    function setCollateralRegistry(address _collateralRegistryAddress) external;

    function mint(address _account, uint256 _amount) external;

    function burn(address _account, uint256 _amount) external;

    function sendToPool(address _sender, address poolAddress, uint256 _amount) external;

    function returnFromPool(address poolAddress, address user, uint256 _amount) external;
}

interface IBoldToken is IBoldTokenCustom, ISuperToken {}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface ICollSurplusPool {
    function getCollBalance() external view returns (uint256);

    function getCollateral(address _account) external view returns (uint256);

    function accountSurplus(address _account, uint256 _amount) external;

    function claimColl(address _account) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IDefaultPool {
    function troveManagerAddress() external view returns (address);
    function activePoolAddress() external view returns (address);
    // --- Functions ---
    function getCollBalance() external view returns (uint256);
    function getBoldDebt() external view returns (uint256);
    function sendCollToActivePool(uint256 _amount) external;
    function receiveColl(uint256 _amount) external;

    function increaseBoldDebt(uint256 _amount) external;
    function decreaseBoldDebt(uint256 _amount) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IHintHelpers {
    function getApproxHint(uint256 _collIndex, uint256 _interestRate, uint256 _numTrials, uint256 _inputRandomSeed)
        external
        view
        returns (uint256 hintId, uint256 diff, uint256 latestRandomSeed);

    function predictOpenTroveUpfrontFee(uint256 _collIndex, uint256 _borrowedAmount, uint256 _interestRate)
        external
        view
        returns (uint256);

    function predictAdjustInterestRateUpfrontFee(uint256 _collIndex, uint256 _troveId, uint256 _newInterestRate)
        external
        view
        returns (uint256);

    function forcePredictAdjustInterestRateUpfrontFee(uint256 _collIndex, uint256 _troveId, uint256 _newInterestRate)
        external
        view
        returns (uint256);

    function predictAdjustTroveUpfrontFee(uint256 _collIndex, uint256 _troveId, uint256 _debtIncrease)
        external
        view
        returns (uint256);

    function predictAdjustBatchInterestRateUpfrontFee(
        uint256 _collIndex,
        address _batchAddress,
        uint256 _newInterestRate
    ) external view returns (uint256);

    function predictJoinBatchInterestRateUpfrontFee(uint256 _collIndex, uint256 _troveId, address _batchAddress)
        external
        view
        returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IMultiTroveGetter {
    struct CombinedTroveData {
        uint256 id;
        uint256 entireDebt;
        uint256 entireColl;
        uint256 redistBoldDebtGain;
        uint256 redistCollGain;
        uint256 accruedInterest;
        uint256 recordedDebt;
        uint256 annualInterestRate;
        uint256 accruedBatchManagementFee;
        uint256 lastInterestRateAdjTime;
        uint256 stake;
        uint256 lastDebtUpdateTime;
        address interestBatchManager;
        uint256 batchDebtShares;
        uint256 snapshotETH;
        uint256 snapshotBoldDebt;
    }

    struct DebtPerInterestRate {
        address interestBatchManager;
        uint256 interestRate;
        uint256 debt;
    }

    function getMultipleSortedTroves(uint256 _collIndex, int256 _startIdx, uint256 _count)
        external
        view
        returns (CombinedTroveData[] memory _troves);

    function getDebtPerInterestRateAscending(uint256 _collIndex, uint256 _startId, uint256 _maxIterations)
        external
        view
        returns (DebtPerInterestRate[] memory, uint256 currId);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ITroveManager.sol";
import {BatchId, BATCH_ID_ZERO} from "../Types/BatchId.sol";

interface ISortedTroves {
    // -- Mutating functions (permissioned) --
    function insert(uint256 _id, uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId) external;
    function insertIntoBatch(
        uint256 _troveId,
        BatchId _batchId,
        uint256 _annualInterestRate,
        uint256 _prevId,
        uint256 _nextId
    ) external;

    function remove(uint256 _id) external;
    function removeFromBatch(uint256 _id) external;

    function reInsert(uint256 _id, uint256 _newAnnualInterestRate, uint256 _prevId, uint256 _nextId) external;
    function reInsertBatch(BatchId _id, uint256 _newAnnualInterestRate, uint256 _prevId, uint256 _nextId) external;

    // -- View functions --

    function contains(uint256 _id) external view returns (bool);
    function isBatchedNode(uint256 _id) external view returns (bool);
    function isEmptyBatch(BatchId _id) external view returns (bool);

    function isEmpty() external view returns (bool);
    function getSize() external view returns (uint256);

    function getFirst() external view returns (uint256);
    function getLast() external view returns (uint256);
    function getNext(uint256 _id) external view returns (uint256);
    function getPrev(uint256 _id) external view returns (uint256);

    function validInsertPosition(uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId)
        external
        view
        returns (bool);
    function findInsertPosition(uint256 _annualInterestRate, uint256 _prevId, uint256 _nextId)
        external
        view
        returns (uint256, uint256);

    // Public state variable getters
    function borrowerOperationsAddress() external view returns (address);
    function troveManager() external view returns (ITroveManager);
    function size() external view returns (uint256);
    function nodes(uint256 _id) external view returns (uint256 nextId, uint256 prevId, BatchId batchId, bool exists);
    function batches(BatchId _id) external view returns (uint256 head, uint256 tail);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IActivePool.sol";
import "./ILiquityBase.sol";
import "./IBoldToken.sol";
import "./ITroveManager.sol";
import "./IBoldRewardsReceiver.sol";

/*
 * The Stability Pool holds Bold tokens deposited by Stability Pool depositors.
 *
 * When a trove is liquidated, then depending on system conditions, some of its Bold debt gets offset with
 * Bold in the Stability Pool:  that is, the offset debt evaporates, and an equal amount of Bold tokens in the Stability Pool is burned.
 *
 * Thus, a liquidation causes each depositor to receive a Bold loss, in proportion to their deposit as a share of total deposits.
 * They also receive an Coll gain, as the collateral of the liquidated trove is distributed among Stability depositors,
 * in the same proportion.
 *
 * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
 * of the total Bold in the Stability Pool, depletes 40% of each deposit.
 *
 * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
 * multiplying it by some factor in range ]0,1[
 *
 * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / Coll gain derivations:
 * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
 *
*/
interface IStabilityPool is ILiquityBase, IBoldRewardsReceiver {
    function boldToken() external view returns (IBoldToken);
    function troveManager() external view returns (ITroveManager);

    /*  provideToSP():
    * - Calculates depositor's Coll gain
    * - Calculates the compounded deposit
    * - Increases deposit, and takes new snapshots of accumulators P and S
    * - Sends depositor's accumulated Coll gains to depositor
    */
    function provideToSP(uint256 _amount, bool _doClaim) external;

    /*  withdrawFromSP():
    * - Calculates depositor's Coll gain
    * - Calculates the compounded deposit
    * - Sends the requested BOLD withdrawal to depositor
    * - (If _amount > userDeposit, the user withdraws all of their compounded deposit)
    * - Decreases deposit by withdrawn amount and takes new snapshots of accumulators P and S
    */
    function withdrawFromSP(uint256 _amount, bool doClaim) external;

    function claimAllCollGains() external;

    /*
     * Initial checks:
     * - Caller is TroveManager
     * ---
     * Cancels out the specified debt against the Bold contained in the Stability Pool (as far as possible)
     * and transfers the Trove's collateral from ActivePool to StabilityPool.
     * Only called by liquidation functions in the TroveManager.
     */
    function offset(uint256 _debt, uint256 _coll) external;

    function deposits(address _depositor) external view returns (uint256 initialValue);
    function stashedColl(address _depositor) external view returns (uint256);

    /*
     * Returns the total amount of Coll held by the pool, accounted in an internal variable instead of `balance`,
     * to exclude edge cases like Coll received from a self-destruct.
     */
    function getCollBalance() external view returns (uint256);

    /*
     * Returns Bold held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
     */
    function getTotalBoldDeposits() external view returns (uint256);

    function getYieldGainsOwed() external view returns (uint256);
    function getYieldGainsPending() external view returns (uint256);

    /*
     * Calculates the Coll gain earned by the deposit since its last snapshots were taken.
     */
    function getDepositorCollGain(address _depositor) external view returns (uint256);

    /*
     * Calculates the BOLD yield gain earned by the deposit since its last snapshots were taken.
     */
    function getDepositorYieldGain(address _depositor) external view returns (uint256);

    /*
     * Calculates what `getDepositorYieldGain` will be if interest is minted now.
     */
    function getDepositorYieldGainWithPending(address _depositor) external view returns (uint256);

    /*
     * Return the user's compounded deposit.
     */
    function getCompoundedBoldDeposit(address _depositor) external view returns (uint256);

    function scaleToS(uint256 _scale) external view returns (uint256);

    function scaleToB(uint256 _scale) external view returns (uint256);


    function P() external view returns (uint256);
    function currentScale() external view returns (uint256);
    function P_PRECISION() external view returns (uint256);
}

File 27 of 70 : ITroveManager.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ILiquityBase.sol";
import "./ITroveNFT.sol";
import "./IBorrowerOperations.sol";
import "./IStabilityPool.sol";
import "./IBoldToken.sol";
import "./ISortedTroves.sol";
import "../Types/LatestTroveData.sol";
import "../Types/LatestBatchData.sol";

// Common interface for the Trove Manager.
interface ITroveManager is ILiquityBase {

    
    enum Status {
        nonExistent,
        active,
        closedByOwner,
        closedByLiquidation,
        zombie
    }

    function shutdownTime() external view returns (uint256);

    function troveNFT() external view returns (ITroveNFT);
    function stabilityPool() external view returns (IStabilityPool);
    //function boldToken() external view returns (IBoldToken);
    function sortedTroves() external view returns (ISortedTroves);
    function borrowerOperations() external view returns (IBorrowerOperations);

    function Troves(uint256 _id)
        external
        view
        returns (
            uint256 debt,
            uint256 coll,
            uint256 stake,
            Status status,
            uint64 arrayIndex,
            uint64 lastDebtUpdateTime,
            uint64 lastInterestRateAdjTime,
            uint256 annualInterestRate,
            address interestBatchManager,
            uint256 batchDebtShares
        );

    function rewardSnapshots(uint256 _id) external view returns (uint256 coll, uint256 boldDebt);

    function getTroveIdsCount() external view returns (uint256);

    function getTroveFromTroveIdsArray(uint256 _index) external view returns (uint256);

    function getCurrentICR(uint256 _troveId, uint256 _price) external view returns (uint256);

    function lastZombieTroveId() external view returns (uint256);

    function batchLiquidateTroves(uint256[] calldata _troveArray) external;

    function redeemCollateral(
        address _sender,
        uint256 _boldAmount,
        uint256 _price,
        uint256 _redemptionRate,
        uint256 _maxIterations
    ) external returns (uint256 _redemeedAmount);

    function shutdown() external;
    function urgentRedemption(uint256 _boldAmount, uint256[] calldata _troveIds, uint256 _minCollateral) external;

    function getUnbackedPortionPriceAndRedeemability() external returns (uint256, uint256, bool);

    function getLatestTroveData(uint256 _troveId) external view returns (LatestTroveData memory);
    function getTroveAnnualInterestRate(uint256 _troveId) external view returns (uint256);

    function getTroveStatus(uint256 _troveId) external view returns (Status);

    function getLatestBatchData(address _batchAddress) external view returns (LatestBatchData memory);

    // -- permissioned functions called by BorrowerOperations

    function onOpenTrove(address _owner, uint256 _troveId, TroveChange memory _troveChange, uint256 _annualInterestRate)
        external;
    function onOpenTroveAndJoinBatch(
        address _owner,
        uint256 _troveId,
        TroveChange memory _troveChange,
        address _batchAddress,
        uint256 _batchColl,
        uint256 _batchDebt
    ) external;

    // Called from `adjustZombieTrove()`
    function setTroveStatusToActive(uint256 _troveId) external;

    function onAdjustTroveInterestRate(
        uint256 _troveId,
        uint256 _newColl,
        uint256 _newDebt,
        uint256 _newAnnualInterestRate,
        TroveChange calldata _troveChange
    ) external;

    function onAdjustTrove(uint256 _troveId, uint256 _newColl, uint256 _newDebt, TroveChange calldata _troveChange)
        external;

    function onAdjustTroveInsideBatch(
        uint256 _troveId,
        uint256 _newTroveColl,
        uint256 _newTroveDebt,
        TroveChange memory _troveChange,
        address _batchAddress,
        uint256 _newBatchColl,
        uint256 _newBatchDebt
    ) external;

    function onApplyTroveInterest(
        uint256 _troveId,
        uint256 _newTroveColl,
        uint256 _newTroveDebt,
        address _batchAddress,
        uint256 _newBatchColl,
        uint256 _newBatchDebt,
        TroveChange calldata _troveChange
    ) external;

    function onCloseTrove(
        uint256 _troveId,
        TroveChange memory _troveChange, // decrease vars: entire, with interest, batch fee and redistribution
        address _batchAddress,
        uint256 _newBatchColl,
        uint256 _newBatchDebt // entire, with interest and batch fee
    ) external;

    // -- batches --
    function onRegisterBatchManager(address _batchAddress, uint256 _annualInterestRate, uint256 _annualFee) external;
    function onLowerBatchManagerAnnualFee(
        address _batchAddress,
        uint256 _newColl,
        uint256 _newDebt,
        uint256 _newAnnualManagementFee
    ) external;
    function onSetBatchManagerAnnualInterestRate(
        address _batchAddress,
        uint256 _newColl,
        uint256 _newDebt,
        uint256 _newAnnualInterestRate,
        uint256 _upfrontFee // needed by BatchUpdated event
    ) external;

    struct OnSetInterestBatchManagerParams {
        uint256 troveId;
        uint256 troveColl; // entire, with redistribution
        uint256 troveDebt; // entire, with interest, batch fee and redistribution
        TroveChange troveChange;
        address newBatchAddress;
        uint256 newBatchColl; // updated collateral for new batch manager
        uint256 newBatchDebt; // updated debt for new batch manager
    }

    function onSetInterestBatchManager(OnSetInterestBatchManagerParams calldata _params) external;
    function onRemoveFromBatch(
        uint256 _troveId,
        uint256 _newTroveColl, // entire, with redistribution
        uint256 _newTroveDebt, // entire, with interest, batch fee and redistribution
        TroveChange memory _troveChange,
        address _batchAddress,
        uint256 _newBatchColl,
        uint256 _newBatchDebt, // entire, with interest and batch fee
        uint256 _newAnnualInterestRate
    ) external;

    function setDebtLimit(uint256 _newDebtLimit) external;
    function getDebtLimit() external view returns (uint256);
    function getInitalDebtLimit() external view returns (uint256);
    // -- end of permissioned functions --
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol";

import "./ITroveManager.sol";

interface ITroveNFT is IERC721Metadata {
    function mint(address _owner, uint256 _troveId) external;
    function burn(uint256 _troveId) external;
    function updateGovernor(address _governor) external;
    function governorUpdateURI(address _externalNFTUriAddress) external;
}

interface IExternalNFTUri {
    function tokenURI(uint256 _tokenId) external view returns (string memory);
}

//SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "lib/Solady/src/utils/SSTORE2.sol";
import "./utils/JSON.sol";

import "./utils/baseSVG.sol";
import "./utils/bauhaus.sol";

import "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import {ITroveManager} from "src/Interfaces/ITroveManager.sol";

interface IMetadataNFT {
    struct TroveData {
        uint256 _tokenId;
        address _owner;
        address _collToken;
        address _boldToken;
        uint256 _collAmount;
        uint256 _debtAmount;
        uint256 _interestRate;
        ITroveManager.Status _status;
    }

    function uri(TroveData memory _troveData) external view returns (string memory);
}

contract MetadataNFT is IMetadataNFT {
    FixedAssetReader public immutable assetReader;

    constructor(FixedAssetReader _assetReader) {
        assetReader = _assetReader;
    }

    function uri(TroveData memory _troveData) public view returns (string memory) {
        string memory attr = attributes(_troveData);
        return json.formattedMetadata(
            string.concat("Nerite - ", IERC20Metadata(_troveData._collToken).name()),
            string.concat(
                "Nerite is a collateralized debt platform. Users can lock up ",
                IERC20Metadata(_troveData._collToken).symbol(),
                " to issue stablecoin tokens (USND) to their own Ethereum address. The individual collateralized debt positions are called Troves, and are represented as NFTs. Caution! Transfering this NFT also transfers the underlying trove position."
            ),
            renderSVGImage(_troveData),
            attr
        );
    }

    function renderSVGImage(TroveData memory _troveData) internal view returns (string memory) {
        return svg._svg(
            baseSVG._svgProps(),
            string.concat(
                baseSVG._baseElements(assetReader),
                bauhaus._bauhaus(IERC20Metadata(_troveData._collToken).symbol(), _troveData._tokenId),
                dynamicTextComponents(_troveData)
            )
        );
    }

    function attributes(TroveData memory _troveData) public pure returns (string memory) {
        //include: collateral token address, collateral amount, debt token address, debt amount, interest rate, status
        return string.concat(
            '[{"trait_type": "Collateral Token", "value": "',
            LibString.toHexString(_troveData._collToken),
            '"}, {"trait_type": "Collateral Amount", "value": "',
            LibString.toString(_troveData._collAmount),
            '"}, {"trait_type": "Debt Token", "value": "',
            LibString.toHexString(_troveData._boldToken),
            '"}, {"trait_type": "Debt Amount", "value": "',
            LibString.toString(_troveData._debtAmount),
            '"}, {"trait_type": "Interest Rate", "value": "',
            LibString.toString(_troveData._interestRate),
            '"}, {"trait_type": "Status", "value": "',
            _status2Str(_troveData._status),
            '"} ]'
        );
    }

    function dynamicTextComponents(TroveData memory _troveData) public view returns (string memory) {
        string memory id = LibString.toHexString(_troveData._tokenId);
        id = string.concat(LibString.slice(id, 0, 6), "...", LibString.slice(id, 38, 42));

        return string.concat(
            baseSVG._formattedIdEl(id),
            baseSVG._formattedAddressEl(_troveData._owner),
            baseSVG._collLogo(IERC20Metadata(_troveData._collToken).symbol(), assetReader),
            baseSVG._statusEl(_status2Str(_troveData._status)),
            baseSVG._dynamicTextEls(_troveData._debtAmount, _troveData._collAmount, _troveData._interestRate)
        );
    }

    function _status2Str(ITroveManager.Status status) internal pure returns (string memory) {
        if (status == ITroveManager.Status.active) return "Active";
        if (status == ITroveManager.Status.closedByOwner) return "Closed";
        if (status == ITroveManager.Status.closedByLiquidation) return "Liquidated";
        if (status == ITroveManager.Status.zombie) return "Below Min Debt";
        return "";
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IBoldToken.sol";
import "./ITroveManager.sol";

interface ICollateralRegistry {
    function baseRate() external view returns (uint256);
    function lastFeeOperationTime() external view returns (uint256);

    function redeemCollateral(uint256 _boldamount, uint256 _maxIterations, uint256 _maxFeePercentage) external;
    // getters
    function totalCollaterals() external view returns (uint256);
    function getToken(uint256 _index) external view returns (IERC20Metadata);
    function getTroveManager(uint256 _index) external view returns (ITroveManager);
    function boldToken() external view returns (IBoldToken);

    function getRedemptionRate() external view returns (uint256);
    function getRedemptionRateWithDecay() external view returns (uint256);
    function getRedemptionRateForRedeemedAmount(uint256 _redeemAmount) external view returns (uint256);

    function getRedemptionFeeWithDecay(uint256 _ETHDrawn) external view returns (uint256);
    function getEffectiveRedemptionFeeInBold(uint256 _redeemAmount) external view returns (uint256);

    function updateDebtLimit(uint256 _indexTroveManager, uint256 _newDebtLimit) external;
    function updateGovernor(address _newGovernor) external;
    function getDebtLimit(uint256 _indexTroveManager) external view returns (uint256); 
    
}

File 31 of 70 : IInterestRouter.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IInterestRouter {
// Currently the Interest Router doesn’t need any specific function
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPriceFeed {
    function fetchPrice() external returns (uint256, bool);
    function fetchRedemptionPrice() external returns (uint256, bool);
    function lastGoodPrice() external view returns (uint256);
    function setAddresses(address _borrowerOperationsAddress) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IActivePool.sol";
import "./IDefaultPool.sol";
import "./IPriceFeed.sol";

interface ILiquityBase {
    function activePool() external view returns (IActivePool);
    function getEntireBranchDebt() external view returns (uint256);
    function getEntireBranchColl() external view returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IAddRemoveManagers {
    function setAddManager(uint256 _troveId, address _manager) external;
    function setRemoveManager(uint256 _troveId, address _manager) external;
    function setRemoveManagerWithReceiver(uint256 _troveId, address _manager, address _receiver) external;
    function addManagerOf(uint256 _troveId) external view returns (address);
    function removeManagerReceiverOf(uint256 _troveId) external view returns (address, address);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IZapper.sol";

interface ILeverageZapper is IZapper {
    struct OpenLeveragedTroveParams {
        address owner;
        uint256 ownerIndex;
        uint256 collAmount;
        uint256 flashLoanAmount;
        uint256 boldAmount;
        uint256 upperHint;
        uint256 lowerHint;
        uint256 annualInterestRate;
        address batchManager;
        uint256 maxUpfrontFee;
        address addManager;
        address removeManager;
        address receiver;
    }

    struct LeverUpTroveParams {
        uint256 troveId;
        uint256 flashLoanAmount;
        uint256 boldAmount;
        uint256 maxUpfrontFee;
    }

    struct LeverDownTroveParams {
        uint256 troveId;
        uint256 flashLoanAmount;
        uint256 minBoldAmount;
    }

    function openLeveragedTroveWithRawETH(OpenLeveragedTroveParams calldata _params) external payable;

    function leverUpTrove(LeverUpTroveParams calldata _params) external;

    function leverDownTrove(LeverDownTroveParams calldata _params) external;

    function leverageRatioToCollateralRatio(uint256 _inputRatio) external pure returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IBoldRewardsReceiver {
    function triggerBoldRewards(uint256 _boldYield) external;
}

File 37 of 70 : TroveChange.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

struct TroveChange {
    uint256 appliedRedistBoldDebtGain;
    uint256 appliedRedistCollGain;
    uint256 collIncrease;
    uint256 collDecrease;
    uint256 debtIncrease;
    uint256 debtDecrease;
    uint256 newWeightedRecordedDebt;
    uint256 oldWeightedRecordedDebt;
    uint256 upfrontFee;
    uint256 batchAccruedManagementFee;
    uint256 newWeightedRecordedBatchManagementFee;
    uint256 oldWeightedRecordedBatchManagementFee;
}

File 38 of 70 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.0;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

File 39 of 70 : ISuperfluid.sol
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

// ISuperfluid.sol can also be used as an umbrella-import for everything Superfluid, hence we should have these unused
// import.
//
// solhint-disable no-unused-import

/// Global definitions
import {
    SuperAppDefinitions,
    ContextDefinitions,
    FlowOperatorDefinitions,
    BatchOperation,
    SuperfluidGovernanceConfigs
} from "./Definitions.sol";
/// Super token related interfaces:
/// Note: CustomSuperTokenBase is not included for people building CustomSuperToken.
import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import { ISuperfluidToken } from "./ISuperfluidToken.sol";
import { ISuperToken } from "./ISuperToken.sol";
import { ISuperTokenFactory } from "./ISuperTokenFactory.sol";
import { ISETH } from "../tokens/ISETH.sol";
/// Superfluid/ERC20x NFTs
import { IPoolAdminNFT } from "../agreements/gdav1/IPoolAdminNFT.sol";
import { IPoolMemberNFT } from "../agreements/gdav1/IPoolMemberNFT.sol";
/// Superfluid agreement interfaces:
import { ISuperAgreement } from "./ISuperAgreement.sol";
import { IConstantFlowAgreementV1 } from "../agreements/IConstantFlowAgreementV1.sol";
import { IInstantDistributionAgreementV1 } from "../agreements/IInstantDistributionAgreementV1.sol";
import { 
    IGeneralDistributionAgreementV1, 
    PoolConfig, 
    PoolERC20Metadata 
} from "../agreements/gdav1/IGeneralDistributionAgreementV1.sol";
import { ISuperfluidPool } from "../agreements/gdav1/ISuperfluidPool.sol";
/// Superfluid App interfaces:
import { ISuperApp } from "./ISuperApp.sol";
/// Superfluid governance
import { ISuperfluidGovernance } from "./ISuperfluidGovernance.sol";


/**
 * @title Host interface
 * @author Superfluid
 * @notice This is the central contract of the system where super agreement, super app
 * and super token features are connected.
 *
 * The Superfluid host contract is also the entry point for the protocol users,
 * where batch call and meta transaction are provided for UX improvements.
 *
 */
interface ISuperfluid {

    /**************************************************************************
     * Errors
     *************************************************************************/
    // Superfluid Custom Errors
    error HOST_AGREEMENT_CALLBACK_IS_NOT_ACTION();              // 0xef4295f6
    error HOST_CANNOT_DOWNGRADE_TO_NON_UPGRADEABLE();           // 0x474e7641
    error HOST_CALL_AGREEMENT_WITH_CTX_FROM_WRONG_ADDRESS();    // 0x0cd0ebc2
    error HOST_CALL_APP_ACTION_WITH_CTX_FROM_WRONG_ADDRESS();   // 0x473f7bd4
    error HOST_INVALID_CONFIG_WORD();                           // 0xf4c802a4
    error HOST_MAX_256_AGREEMENTS();                            // 0x7c281a78
    error HOST_NON_UPGRADEABLE();                               // 0x14f72c9f
    error HOST_NON_ZERO_LENGTH_PLACEHOLDER_CTX();               // 0x67e9985b
    error HOST_ONLY_GOVERNANCE();                               // 0xc5d22a4e
    error HOST_UNKNOWN_BATCH_CALL_OPERATION_TYPE();             // 0xb4770115
    error HOST_AGREEMENT_ALREADY_REGISTERED();                  // 0xdc9ddba8
    error HOST_AGREEMENT_IS_NOT_REGISTERED();                   // 0x1c9e9bea
    error HOST_MUST_BE_CONTRACT();                              // 0xd4f6b30c
    error HOST_ONLY_LISTED_AGREEMENT();                         // 0x619c5359
    error HOST_NEED_MORE_GAS();                                 // 0xd4f5d496

    // App Related Custom Errors
    // uses SuperAppDefinitions' App Jail Reasons as _code
    error APP_RULE(uint256 _code);                              // 0xa85ba64f

    error HOST_NOT_A_SUPER_APP();                               // 0x163cbe43
    error HOST_NO_APP_REGISTRATION_PERMISSION();                // 0xb56455f0
    error HOST_RECEIVER_IS_NOT_SUPER_APP();                     // 0x96aa315e
    error HOST_SENDER_IS_NOT_SUPER_APP();                       // 0xbacfdc40
    error HOST_SOURCE_APP_NEEDS_HIGHER_APP_LEVEL();             // 0x44725270
    error HOST_SUPER_APP_IS_JAILED();                           // 0x02384b64
    error HOST_SUPER_APP_ALREADY_REGISTERED();                  // 0x01b0a935

    /**************************************************************************
     * Time
     *
     * > The Oracle: You have the sight now, Neo. You are looking at the world without time.
     * > Neo: Then why can't I see what happens to her?
     * > The Oracle: We can never see past the choices we don't understand.
     * >       - The Oracle and Neo conversing about the future of Trinity and the effects of Neo's choices
     *************************************************************************/

    function getNow() external view returns (uint256);

    /**************************************************************************
     * Governance
     *************************************************************************/

    /**
     * @dev Get the current governance address of the Superfluid host
     */
    function getGovernance() external view returns(ISuperfluidGovernance governance);

    /**
     * @dev Replace the current governance with a new one
     */
    function replaceGovernance(ISuperfluidGovernance newGov) external;
    /**
     * @dev Governance replaced event
     * @param oldGov Address of the old governance contract
     * @param newGov Address of the new governance contract
     */
    event GovernanceReplaced(ISuperfluidGovernance oldGov, ISuperfluidGovernance newGov);

    /**************************************************************************
     * Agreement Whitelisting
     *************************************************************************/

    /**
     * @dev Register a new agreement class to the system
     * @param agreementClassLogic Initial agreement class code
     *
     * @custom:modifiers
     * - onlyGovernance
     */
    function registerAgreementClass(ISuperAgreement agreementClassLogic) external;
    /**
     * @notice Agreement class registered event
     * @dev agreementType is the keccak256 hash of: "org.superfluid-finance.agreements.<AGREEMENT_NAME>.<VERSION>"
     * @param agreementType The agreement type registered
     * @param code Address of the new agreement
     */
    event AgreementClassRegistered(bytes32 agreementType, address code);

    /**
    * @dev Update code of an agreement class
    * @param agreementClassLogic New code for the agreement class
    *
    * @custom:modifiers
    *  - onlyGovernance
    */
    function updateAgreementClass(ISuperAgreement agreementClassLogic) external;
    /**
     * @notice Agreement class updated event
     * @dev agreementType is the keccak256 hash of: "org.superfluid-finance.agreements.<AGREEMENT_NAME>.<VERSION>"
     * @param agreementType The agreement type updated
     * @param code Address of the new agreement
     */
    event AgreementClassUpdated(bytes32 agreementType, address code);

    /**
    * @notice Check if the agreement type is whitelisted
    * @dev agreementType is the keccak256 hash of: "org.superfluid-finance.agreements.<AGREEMENT_NAME>.<VERSION>"
    */
    function isAgreementTypeListed(bytes32 agreementType) external view returns(bool yes);

    /**
    * @dev Check if the agreement class is whitelisted
    */
    function isAgreementClassListed(ISuperAgreement agreementClass) external view returns(bool yes);

    /**
    * @notice Get agreement class
    * @dev agreementType is the keccak256 hash of: "org.superfluid-finance.agreements.<AGREEMENT_NAME>.<VERSION>"
    */
    function getAgreementClass(bytes32 agreementType) external view returns(ISuperAgreement agreementClass);

    /**
    * @dev Map list of the agreement classes using a bitmap
    * @param bitmap Agreement class bitmap
    */
    function mapAgreementClasses(uint256 bitmap)
        external view
        returns (ISuperAgreement[] memory agreementClasses);

    /**
    * @notice Create a new bitmask by adding a agreement class to it
    * @dev agreementType is the keccak256 hash of: "org.superfluid-finance.agreements.<AGREEMENT_NAME>.<VERSION>"
    * @param bitmap Agreement class bitmap
    */
    function addToAgreementClassesBitmap(uint256 bitmap, bytes32 agreementType)
        external view
        returns (uint256 newBitmap);

    /**
    * @notice Create a new bitmask by removing a agreement class from it
    * @dev agreementType is the keccak256 hash of: "org.superfluid-finance.agreements.<AGREEMENT_NAME>.<VERSION>"
    * @param bitmap Agreement class bitmap
    */
    function removeFromAgreementClassesBitmap(uint256 bitmap, bytes32 agreementType)
        external view
        returns (uint256 newBitmap);

    /**************************************************************************
    * Super Token Factory
    **************************************************************************/

    /**
     * @dev Get the super token factory
     * @return factory The factory
     */
    function getSuperTokenFactory() external view returns (ISuperTokenFactory factory);

    /**
     * @dev Get the super token factory logic (applicable to upgradable deployment)
     * @return logic The factory logic
     */
    function getSuperTokenFactoryLogic() external view returns (address logic);

    /**
     * @dev Update super token factory
     * @param newFactory New factory logic
     */
    function updateSuperTokenFactory(ISuperTokenFactory newFactory) external;
    /**
     * @dev SuperToken factory updated event
     * @param newFactory Address of the new factory
     */
    event SuperTokenFactoryUpdated(ISuperTokenFactory newFactory);

    /**
     * @notice Update the super token logic to the latest (canonical) implementation
     * if `newLogicOverride` is zero, or to `newLogicOverride` otherwise.
     * or to the provided implementation `.
     * @dev Refer to ISuperTokenFactory.Upgradability for expected behaviours
     */
    function updateSuperTokenLogic(ISuperToken token, address newLogicOverride) external;
    /**
     * @notice Update the super token logic to the provided one
     * @dev newLogic must implement UUPSProxiable with matching proxiableUUID
     */
    event SuperTokenLogicUpdated(ISuperToken indexed token, address code);

    /**
     * @notice Change the SuperToken admin address
     * @dev The admin is the only account allowed to update the token logic
     * For backward compatibility, the "host" is the default "admin" if unset (address(0)).
     */
    function changeSuperTokenAdmin(ISuperToken token, address newAdmin) external;

    /**
     * @notice Change the implementation address the pool beacon points to
     * @dev Updating the logic the beacon points to will update the logic of all the Pool BeaconProxy instances
     */
    function updatePoolBeaconLogic(address newBeaconLogic) external;

    /**
     * @dev Pool Beacon logic updated event
     * @param beaconProxy addrss of the beacon proxy
     * @param newBeaconLogic address of the new beacon logic
     */
    event PoolBeaconLogicUpdated(address indexed beaconProxy, address newBeaconLogic);

    /**************************************************************************
     * App Registry
     *************************************************************************/

    /**
     * @dev Message sender (must be a contract) registers itself as a super app.
     * @param configWord The super app manifest configuration, flags are defined in
     * `SuperAppDefinitions`
     * @notice On some mainnet deployments, pre-authorization by governance may be needed for this to succeed.
     * See https://github.com/superfluid-finance/protocol-monorepo/wiki/Super-App-White-listing-Guide
     */
    function registerApp(uint256 configWord) external;

    /**
     * @dev Registers an app (must be a contract) as a super app.
     * @param app The super app address
     * @param configWord The super app manifest configuration, flags are defined in
     * `SuperAppDefinitions`
     * @notice On some mainnet deployments, pre-authorization by governance may be needed for this to succeed.
     * See https://github.com/superfluid-finance/protocol-monorepo/wiki/Super-App-White-listing-Guide
     */
    function registerApp(ISuperApp app, uint256 configWord) external;

    /**
     * @dev App registered event
     * @param app Address of jailed app
     */
    event AppRegistered(ISuperApp indexed app);

    /**
     * @dev DO NOT USE for new deployments
     * @custom:deprecated you should use `registerApp(uint256 configWord) instead.
     */
    function registerAppWithKey(uint256 configWord, string calldata registrationKey) external;

    /**
     * @dev DO NOT USE for new deployments
     * @custom:deprecated you should use `registerApp(ISuperApp app, uint256 configWord) instead.
     */
    function registerAppByFactory(ISuperApp app, uint256 configWord) external;

    /**
     * @dev Query if the app is registered
     * @param app Super app address
     */
    function isApp(ISuperApp app) external view returns(bool);

    /**
     * @dev Query app callbacklevel
     * @param app Super app address
     */
    function getAppCallbackLevel(ISuperApp app) external view returns(uint8 appCallbackLevel);

    /**
     * @dev Get the manifest of the super app
     * @param app Super app address
     */
    function getAppManifest(
        ISuperApp app
    )
        external view
        returns (
            bool isSuperApp,
            bool isJailed,
            uint256 noopMask
        );

    /**
     * @dev Query if the app has been jailed
     * @param app Super app address
     */
    function isAppJailed(ISuperApp app) external view returns (bool isJail);

    /**
     * @dev Whitelist the target app for app composition for the source app (msg.sender)
     * @param targetApp The target super app address
     */
    function allowCompositeApp(ISuperApp targetApp) external;

    /**
     * @dev Query if source app is allowed to call the target app as downstream app
     * @param app Super app address
     * @param targetApp The target super app address
     */
    function isCompositeAppAllowed(
        ISuperApp app,
        ISuperApp targetApp
    )
        external view
        returns (bool isAppAllowed);

    /**************************************************************************
     * Agreement Framework
     *
     * Agreements use these function to trigger super app callbacks, updates
     * app credit and charge gas fees.
     *
     * These functions can only be called by registered agreements.
     *************************************************************************/

    /**
     * @dev (For agreements) StaticCall the app before callback
     * @param  app               The super app.
     * @param  callData          The call data sending to the super app.
     * @param  isTermination     Is it a termination callback?
     * @param  ctx               Current ctx, it will be validated.
     * @return cbdata            Data returned from the callback.
     */
    function callAppBeforeCallback(
        ISuperApp app,
        bytes calldata callData,
        bool isTermination,
        bytes calldata ctx
    )
        external
        // onlyAgreement
        // assertValidCtx(ctx)
        returns(bytes memory cbdata);

    /**
     * @dev (For agreements) Call the app after callback
     * @param  app               The super app.
     * @param  callData          The call data sending to the super app.
     * @param  isTermination     Is it a termination callback?
     * @param  ctx               Current ctx, it will be validated.
     * @return newCtx            The current context of the transaction.
     */
    function callAppAfterCallback(
        ISuperApp app,
        bytes calldata callData,
        bool isTermination,
        bytes calldata ctx
    )
        external
        // onlyAgreement
        // assertValidCtx(ctx)
        returns(bytes memory newCtx);

    /**
     * @dev (For agreements) Create a new callback stack
     * @param  ctx                     The current ctx, it will be validated.
     * @param  app                     The super app.
     * @param  appCreditGranted        App credit granted so far.
     * @param  appCreditUsed           App credit used so far.
     * @return newCtx                  The current context of the transaction.
     */
    function appCallbackPush(
        bytes calldata ctx,
        ISuperApp app,
        uint256 appCreditGranted,
        int256 appCreditUsed,
        ISuperfluidToken appCreditToken
    )
        external
        // onlyAgreement
        // assertValidCtx(ctx)
        returns (bytes memory newCtx);

    /**
     * @dev (For agreements) Pop from the current app callback stack
     * @param  ctx                     The ctx that was pushed before the callback stack.
     * @param  appCreditUsedDelta      App credit used by the app.
     * @return newCtx                  The current context of the transaction.
     *
     * @custom:security
     * - Here we cannot do assertValidCtx(ctx), since we do not really save the stack in memory.
     * - Hence there is still implicit trust that the agreement handles the callback push/pop pair correctly.
     */
    function appCallbackPop(
        bytes calldata ctx,
        int256 appCreditUsedDelta
    )
        external
        // onlyAgreement
        returns (bytes memory newCtx);

    /**
     * @dev (For agreements) Use app credit.
     * @param  ctx                      The current ctx, it will be validated.
     * @param  appCreditUsedMore        See app credit for more details.
     * @return newCtx                   The current context of the transaction.
     */
    function ctxUseCredit(
        bytes calldata ctx,
        int256 appCreditUsedMore
    )
        external
        // onlyAgreement
        // assertValidCtx(ctx)
        returns (bytes memory newCtx);

    /**
     * @dev (For agreements) Jail the app.
     * @param  app                     The super app.
     * @param  reason                  Jail reason code.
     * @return newCtx                  The current context of the transaction.
     */
    function jailApp(
        bytes calldata ctx,
        ISuperApp app,
        uint256 reason
    )
        external
        // onlyAgreement
        // assertValidCtx(ctx)
        returns (bytes memory newCtx);

    /**
     * @dev Jail event for the app
     * @param app Address of jailed app
     * @param reason Reason the app is jailed (see Definitions.sol for the full list)
     */
    event Jail(ISuperApp indexed app, uint256 reason);

    /**************************************************************************
     * Contextless Call Proxies
     *
     * NOTE: For EOAs or non-app contracts, they are the entry points for interacting
     * with agreements or apps.
     *
     * NOTE: The contextual call data should be generated using
     * abi.encodeWithSelector. The context parameter should be set to "0x",
     * an empty bytes array as a placeholder to be replaced by the host
     * contract.
     *************************************************************************/

     /**
      * @dev Call agreement function
      * @param agreementClass The agreement address you are calling
      * @param callData The contextual call data with placeholder ctx
      * @param userData Extra user data being sent to the super app callbacks
      */
     function callAgreement(
         ISuperAgreement agreementClass,
         bytes calldata callData,
         bytes calldata userData
     )
        external
        //cleanCtx
        //isAgreement(agreementClass)
        returns(bytes memory returnedData);

    /**
     * @notice Call app action
     * @dev Main use case is calling app action in a batch call via the host
     * @param callData The contextual call data
     *
     * @custom:note See "Contextless Call Proxies" above for more about contextual call data.
     */
    function callAppAction(
        ISuperApp app,
        bytes calldata callData
    )
        external
        //cleanCtx
        //isAppActive(app)
        //isValidAppAction(callData)
        returns(bytes memory returnedData);

    /**************************************************************************
     * Contextual Call Proxies and Context Utilities
     *
     * For apps, they must use context they receive to interact with
     * agreements or apps.
     *
     * The context changes must be saved and returned by the apps in their
     * callbacks always, any modification to the context will be detected and
     * the violating app will be jailed.
     *************************************************************************/

    /**
     * @dev Context Struct
     *
     * @custom:note on backward compatibility:
     * - Non-dynamic fields are padded to 32bytes and packed
     * - Dynamic fields are referenced through a 32bytes offset to their "parents" field (or root)
     * - The order of the fields hence should not be rearranged in order to be backward compatible:
     *    - non-dynamic fields will be parsed at the same memory location,
     *    - and dynamic fields will simply have a greater offset than it was.
     * - We cannot change the structure of the Context struct because of ABI compatibility requirements
     */
    struct Context {
        //
        // Call context
        //
        // app callback level
        uint8 appCallbackLevel;
        // type of call
        uint8 callType;
        // the system timestamp
        uint256 timestamp;
        // The intended message sender for the call
        address msgSender;

        //
        // Callback context
        //
        // For callbacks it is used to know which agreement function selector is called
        bytes4 agreementSelector;
        // User provided data for app callbacks
        bytes userData;

        //
        // App context
        //
        // app credit granted
        uint256 appCreditGranted;
        // app credit wanted by the app callback
        uint256 appCreditWantedDeprecated;
        // app credit used, allowing negative values over a callback session
        // the appCreditUsed value over a callback sessions is calculated with:
        // existing flow data owed deposit + sum of the callback agreements
        // deposit deltas
        // the final value used to modify the state is determined by the
        // _adjustNewAppCreditUsed function (in AgreementLibrary.sol) which takes
        // the appCreditUsed value reached in the callback session and the app
        // credit granted
        int256 appCreditUsed;
        // app address
        address appAddress;
        // app credit in super token
        ISuperfluidToken appCreditToken;
    }

    function callAgreementWithContext(
        ISuperAgreement agreementClass,
        bytes calldata callData,
        bytes calldata userData,
        bytes calldata ctx
    )
        external
        // requireValidCtx(ctx)
        // onlyAgreement(agreementClass)
        returns (bytes memory newCtx, bytes memory returnedData);

    function callAppActionWithContext(
        ISuperApp app,
        bytes calldata callData,
        bytes calldata ctx
    )
        external
        // requireValidCtx(ctx)
        // isAppActive(app)
        returns (bytes memory newCtx);

    function decodeCtx(bytes memory ctx)
        external pure
        returns (Context memory context);

    function isCtxValid(bytes calldata ctx) external view returns (bool);

    /**************************************************************************
    * Batch call
    **************************************************************************/
    /**
     * @dev Batch operation data
     */
    struct Operation {
        // Operation type. Defined in BatchOperation (Definitions.sol)
        uint32 operationType;
        // Operation target
        address target;
        // Data specific to the operation
        bytes data;
    }

    /**
     * @dev Batch call function
     * @param operations Array of batch operations
     *
     * NOTE: `batchCall` is `payable, because there's limited support for sending
     * native tokens to batch operation targets.
     * If value is > 0, the whole amount is sent to the first operation matching any of:
     * - OPERATION_TYPE_SUPERFLUID_CALL_APP_ACTION
     * - OPERATION_TYPE_SIMPLE_FORWARD_CALL
     * - OPERATION_TYPE_ERC2771_FORWARD_CALL
     * If the first such operation does not allow receiving native tokens,
     * the transaction will revert.
     * It's currently not possible to send native tokens to multiple operations, or to
     * any but the first operation of one of the above mentioned types.
     * If no such operation is included, the native tokens will be sent back to the sender.
     */
    function batchCall(Operation[] calldata operations) external payable;

    /**
     * @dev Batch call function with EIP-2771 encoded msgSender
     * @param operations Array of batch operations
     *
     * NOTE: This can be called only by contracts recognized as _trusted forwarder_
     * by the host contract (see `Superfluid.isTrustedForwarder`).
     * If native tokens are passed along, the same rules as for `batchCall` apply,
     * with an optional refund going to the encoded msgSender.
     */
    function forwardBatchCall(Operation[] calldata operations) external payable;

    /**
     * @dev returns the address of the forwarder contract used to route batch operations of type
     * OPERATION_TYPE_ERC2771_FORWARD_CALL.
     * Needs to be set as _trusted forwarder_ by the call targets of such operations.
     */
    // solhint-disable func-name-mixedcase
    function getERC2771Forwarder() external view returns(address);

    /**************************************************************************
     * Function modifiers for access control and parameter validations
     *
     * While they cannot be explicitly stated in function definitions, they are
     * listed in function definition comments instead for clarity.
     *
     * TODO: turning these off because solidity-coverage doesn't like it
     *************************************************************************/

     /* /// @dev The current superfluid context is clean.
     modifier cleanCtx() virtual;

     /// @dev Require the ctx being valid.
     modifier requireValidCtx(bytes memory ctx) virtual;

     /// @dev Assert the ctx being valid.
     modifier assertValidCtx(bytes memory ctx) virtual;

     /// @dev The agreement is a listed agreement.
     modifier isAgreement(ISuperAgreement agreementClass) virtual;

     // onlyGovernance

     /// @dev The msg.sender must be a listed agreement.
     modifier onlyAgreement() virtual;

     /// @dev The app is registered and not jailed.
     modifier isAppActive(ISuperApp app) virtual; */
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

type BatchId is address;

using {equals as ==, notEquals as !=, isZero, isNotZero} for BatchId global;

function equals(BatchId a, BatchId b) pure returns (bool) {
    return BatchId.unwrap(a) == BatchId.unwrap(b);
}

function notEquals(BatchId a, BatchId b) pure returns (bool) {
    return !(a == b);
}

function isZero(BatchId x) pure returns (bool) {
    return x == BATCH_ID_ZERO;
}

function isNotZero(BatchId x) pure returns (bool) {
    return !x.isZero();
}

BatchId constant BATCH_ID_ZERO = BatchId.wrap(address(0));

File 41 of 70 : LatestTroveData.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

struct LatestTroveData {
    uint256 entireDebt;
    uint256 entireColl;
    uint256 redistBoldDebtGain;
    uint256 redistCollGain;
    uint256 accruedInterest;
    uint256 recordedDebt;
    uint256 annualInterestRate;
    uint256 weightedRecordedDebt;
    uint256 accruedBatchManagementFee;
    uint256 lastInterestRateAdjTime;
}

File 42 of 70 : LatestBatchData.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

struct LatestBatchData {
    uint256 totalDebtShares;
    uint256 entireDebtWithoutRedistribution;
    uint256 entireCollWithoutRedistribution;
    uint256 accruedInterest;
    uint256 recordedDebt;
    uint256 annualInterestRate;
    uint256 weightedRecordedDebt;
    uint256 annualManagementFee;
    uint256 accruedManagementFee;
    uint256 weightedRecordedBatchManagementFee;
    uint256 lastDebtUpdateTime;
    uint256 lastInterestRateAdjTime;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol)
/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3)
library SSTORE2 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The proxy initialization code.
    uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;

    /// @dev Hash of the `_CREATE3_PROXY_INITCODE`.
    /// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
    bytes32 internal constant CREATE3_PROXY_INITCODE_HASH =
        0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unable to deploy the storage contract.
    error DeploymentFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         WRITE LOGIC                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Writes `data` into the bytecode of a storage contract and returns its address.
    function write(bytes memory data) internal returns (address pointer) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
            /**
             * ---------------------------------------------------+
             * Opcode | Mnemonic       | Stack     | Memory       |
             * ---------------------------------------------------|
             * 61 l   | PUSH2 l        | l         |              |
             * 80     | DUP1           | l l       |              |
             * 60 0xa | PUSH1 0xa      | 0xa l l   |              |
             * 3D     | RETURNDATASIZE | 0 0xa l l |              |
             * 39     | CODECOPY       | l         | [0..l): code |
             * 3D     | RETURNDATASIZE | 0 l       | [0..l): code |
             * F3     | RETURN         |           | [0..l): code |
             * 00     | STOP           |           |              |
             * ---------------------------------------------------+
             * @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
             * Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
             */
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            // Deploy a new contract with the generated creation code.
            pointer := create(0, add(data, 0x15), add(n, 0xb))
            if iszero(pointer) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Writes `data` into the bytecode of a storage contract with `salt`
    /// and returns its normal CREATE2 deterministic address.
    function writeCounterfactual(bytes memory data, bytes32 salt)
        internal
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            // Deploy a new contract with the generated creation code.
            pointer := create2(0, add(data, 0x15), add(n, 0xb), salt)
            if iszero(pointer) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Writes `data` into the bytecode of a storage contract and returns its address.
    /// This uses the so-called "CREATE3" workflow,
    /// which means that `pointer` is agnostic to `data, and only depends on `salt`.
    function writeDeterministic(bytes memory data, bytes32 salt)
        internal
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
            let proxy := create2(0, 0x10, 0x10, salt)
            if iszero(proxy) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, proxy) // Store the proxy's address.
            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
            mstore(0x00, 0xd694)
            mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
            pointer := keccak256(0x1e, 0x17)

            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            if iszero(
                mul( // The arguments of `mul` are evaluated last to first.
                    extcodesize(pointer),
                    call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00)
                )
            ) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    ADDRESS CALCULATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the initialization code hash of the storage contract for `data`.
    /// Used for mining vanity addresses with create2crunch.
    function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe))
            mstore(data, add(0x61000180600a3d393df300, shl(0x40, n)))
            hash := keccak256(add(data, 0x15), add(n, 0xb))
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))`
    function predictCounterfactualAddress(bytes memory data, bytes32 salt)
        internal
        view
        returns (address pointer)
    {
        pointer = predictCounterfactualAddress(data, salt, address(this));
    }

    /// @dev Returns the CREATE2 address of the storage contract for `data`
    /// deployed with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        bytes32 hash = initCodeHash(data);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, hash)
            mstore(0x01, shl(96, deployer))
            mstore(0x15, salt)
            predicted := keccak256(0x00, 0x55)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x35, 0)
        }
    }

    /// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`.
    function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) {
        pointer = predictDeterministicAddress(salt, address(this));
    }

    /// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`.
    function predictDeterministicAddress(bytes32 salt, address deployer)
        internal
        pure
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x00, deployer) // Store `deployer`.
            mstore8(0x0b, 0xff) // Store the prefix.
            mstore(0x20, salt) // Store the salt.
            mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash.

            mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
            mstore(0x40, m) // Restore the free memory pointer.
            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
            mstore(0x00, 0xd694)
            mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
            pointer := keccak256(0x1e, 0x17)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         READ LOGIC                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
    function read(address pointer) internal view returns (bytes memory data) {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            let n := and(sub(extcodesize(pointer), 0x01), 0xffffffffff)
            extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
            mstore(data, n) // Store the length.
            mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`.
    function read(address pointer, uint256 start) internal view returns (bytes memory data) {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            let n := and(sub(extcodesize(pointer), 0x01), 0xffffffffff)
            extcodecopy(pointer, add(data, 0x1f), start, add(n, 0x21))
            mstore(data, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the data on `pointer` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `pointer` MUST be deployed via the SSTORE2 write functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `pointer` does not have any code.
    function read(address pointer, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01))
            if iszero(and(0xff, mload(add(data, d)))) {
                let n := sub(extcodesize(pointer), 0x01)
                returndatacopy(returndatasize(), returndatasize(), shr(64, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(data, d) // Store the length.
            mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(data, 0x40), d)) // Allocate memory.
        }
    }
}

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

// JSON utilities for base64 encoded ERC721 JSON metadata scheme
library json {
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// @dev JSON requires that double quotes be escaped or JSONs will not build correctly
    /// string.concat also requires an escape, use \\" or the constant DOUBLE_QUOTES to represent " in JSON
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////

    string constant DOUBLE_QUOTES = '\\"';

    function formattedMetadata(
        string memory name,
        string memory description,
        string memory svgImg,
        string memory attributes
    ) internal pure returns (string memory) {
        return string.concat(
            "data:application/json;base64,",
            encode(
                bytes(
                    string.concat(
                        "{",
                        _prop("name", name),
                        _prop("description", description),
                        _xmlImage(svgImg),
                        ',"attributes":',
                        attributes,
                        "}"
                    )
                )
            )
        );
    }

    function _xmlImage(string memory _svgImg) internal pure returns (string memory) {
        return _prop("image", string.concat("data:image/svg+xml;base64,", encode(bytes(_svgImg))), true);
    }

    function _prop(string memory _key, string memory _val) internal pure returns (string memory) {
        return string.concat('"', _key, '": ', '"', _val, '", ');
    }

    function _prop(string memory _key, string memory _val, bool last) internal pure returns (string memory) {
        if (last) {
            return string.concat('"', _key, '": ', '"', _val, '"');
        } else {
            return string.concat('"', _key, '": ', '"', _val, '", ');
        }
    }

    function _object(string memory _key, string memory _val) internal pure returns (string memory) {
        return string.concat('"', _key, '": ', "{", _val, "}");
    }

    /**
     * taken from Openzeppelin
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

            // Prepare result pointer, jump over length
            let resultPtr := add(result, 32)

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {} {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 { mstore8(sub(resultPtr, 1), 0x3d) }
        }

        return result;
    }
}

//SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {svg} from "./SVG.sol";
import {utils, LibString, numUtils} from "./Utils.sol";
import "./FixedAssets.sol";
import "./USNDLogoSVG.sol";

library baseSVG {
    string constant GEIST = 'style="font-family: Geist" ';
    string constant DARK_BLUE = "#121B44";
    string constant STOIC_WHITE = "#DEE4FB";

    USNDLogoSVG constant usndLogo = USNDLogoSVG(0x09673074d6C50c81f9b097E335ff6655bC96ca98);

    function _svgProps() internal pure returns (string memory) {
        return string.concat(
            svg.prop("width", "300"),
            svg.prop("height", "484"),
            svg.prop("viewBox", "0 0 300 484"),
            svg.prop("style", "background:none")
        );
    }

    function _baseElements(FixedAssetReader _assetReader) internal view returns (string memory) {
        return string.concat(
            svg.rect(
                string.concat(
                    svg.prop("fill", DARK_BLUE),
                    svg.prop("rx", "8"),
                    svg.prop("width", "300"),
                    svg.prop("height", "484")
                )
            ),
            _styles(_assetReader),
            _leverageLogo(),
            _boldLogo(_assetReader),
            _staticTextEls()
        );
    }

    function _styles(FixedAssetReader _assetReader) private view returns (string memory) {
        return svg.el(
            "style",
            utils.NULL,
            string.concat(
                '@font-face { font-family: "Geist"; src: url("data:font/woff2;utf-8;base64,',
                _assetReader.readAsset(bytes4(keccak256("geist"))),
                '"); }'
            )
        );
    }

    function _leverageLogo() internal pure returns (string memory) {
        return string.concat(
            svg.path(
                "M20.2 31.2C19.1 32.4 17.6 33 16 33L16 21C17.6 21 19.1 21.6 20.2 22.7C21.4 23.9 22 25.4 22 27C22 28.6 21.4 30.1 20.2 31.2Z",
                svg.prop("fill", STOIC_WHITE)
            ),
            svg.path(
                "M22 27C22 25.4 22.6 23.9 23.8 22.7C25 21.6 26.4 21 28 21V33C26.4 33 25 32.4 24 31.2C22.6 30.1 22 28.6 22 27Z",
                svg.prop("fill", STOIC_WHITE)
            )
        );
    }

    string public constant USND_LOGO = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTIwIiBoZWlnaHQ9IjUyMCIgdmlld0JveD0iMCAwIDUyMCA1MjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+DQo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDBfMjA0MF8xMjkxKSIgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZF8yMDQwXzEyOTEpIj4NCjxwYXRoIGQ9Ik0yNjAgNTEyQzQwMS4zODUgNTEyIDUxNiAzOTcuMzg1IDUxNiAyNTZDNTE2IDExNC42MTUgNDAxLjM4NSAwIDI2MCAwQzExOC42MTUgMCA0IDExNC42MTUgNCAyNTZDNCAzOTcuMzg1IDExOC42MTUgNTEyIDI2MCA1MTJaIiBmaWxsPSIjMUQzMTE3Ii8+DQo8cGF0aCBkPSJNMzIwLjUzNCA3MC45NTc2QzMyMi43MTcgNjEuODI2MiAzMTcuMDg1IDUyLjY1MzYgMzA3Ljk1NCA1MC40N0MyOTguODIyIDQ4LjI4NjQgMjg5LjY1IDUzLjkxODcgMjg3LjQ2NiA2My4wNTAxTDI3OS41NzMgOTYuMDU4M0MyMjIuNjE3IDk3Ljg2NzMgMTc3IDE0NC42MDkgMTc3IDIwMi4wMDRDMTc3IDI0MS43NjkgMjA5LjIzNSAyNzMuMDA0IDI0OSAyNzMuMDA0QzI1Mi41NDMgMjczLjAwNCAyNTYuMDQgMjcyLjc1MyAyNTkuNTMxIDI3Mi41MDNDMjYzLjAxMiAyNzIuMjUzIDI2Ni40ODcgMjcyLjAwNCAyNzAgMjcyLjAwNEMyOTAuOTg3IDI3Mi4wMDQgMzA4IDI4OC4wMTcgMzA4IDMwOS4wMDRDMzA4IDM0OC43NjggMjc1Ljc2NSAzODEuMDA0IDIzNiAzODEuMDA0QzIxNS4wMTMgMzgxLjAwNCAxOTggMzYzLjk5MSAxOTggMzQzLjAwNEMxOTggMzQxLjc2NSAxOTguMTMzIDM0MC41NTcgMTk4LjM4NCAzMzkuMzk0QzIwMC40NTkgMzUxLjEwOCAyMTAuNjkxIDM2MC4wMDQgMjIzIDM2MC4wMDRDMjM5LjU2OSAzNjAuMDA0IDI1MyAzNDYuNTczIDI1MyAzMzAuMDA0QzI1MyAzMDkuMDE3IDIzNS45ODcgMjkyLjAwNCAyMTUgMjkyLjAwNEMxODYuODMzIDI5Mi4wMDQgMTY0IDMxNC44MzcgMTY0IDM0My4wMDRDMTY0IDM3Mi4wNjggMTgxLjIyMSAzOTcuMTA5IDIwNi4wMTUgNDA4LjQ4MkwxOTguNDY2IDQ0MC4wNUMxOTYuMjgzIDQ0OS4xODIgMjAxLjkxNSA0NTguMzU0IDIxMS4wNDYgNDYwLjUzOEMyMjAuMTc4IDQ2Mi43MjEgMjI5LjM1IDQ1Ny4wODkgMjMxLjUzNCA0NDcuOTU4TDIzOS40MjcgNDE0Ljk1QzI5Ni4zODMgNDEzLjE0MSAzNDIgMzY2LjM5OSAzNDIgMzA5LjAwNEMzNDIgMjY5LjIzOSAzMDkuNzY0IDIzOC4wMDQgMjcwIDIzOC4wMDRDMjY2LjQ0NyAyMzguMDA0IDI2Mi45NDIgMjM4LjI1NSAyNTkuNDQ3IDIzOC41MDZDMjU1Ljk2OSAyMzguNzU1IDI1Mi40OTkgMjM5LjAwNCAyNDkgMjM5LjAwNEMyMjguMDEzIDIzOS4wMDQgMjExIDIyMi45OTEgMjExIDIwMi4wMDRDMjExIDE2Mi4yNCAyNDMuMjM1IDEzMC4wMDQgMjgzIDEzMC4wMDRDMzAzLjk4NyAxMzAuMDA0IDMyMSAxNDcuMDE3IDMyMSAxNjguMDA0QzMyMSAxNjkuMjQzIDMyMC44NjcgMTcwLjQ1MSAzMjAuNjE2IDE3MS42MTRDMzE4LjU0MSAxNTkuOSAzMDguMzA5IDE1MS4wMDQgMjk2IDE1MS4wMDRDMjc5LjQzMSAxNTEuMDA0IDI2NiAxNjQuNDM1IDI2NiAxODEuMDA0QzI2NiAyMDEuOTkxIDI4My4wMTMgMjE5LjAwNCAzMDQgMjE5LjAwNEMzMzIuMTY3IDIxOS4wMDQgMzU1IDE5Ni4xNzEgMzU1IDE2OC4wMDRDMzU1IDEzOC45NCAzMzcuNzc5IDExMy44OTggMzEyLjk4NSAxMDIuNTI2TDMyMC41MzQgNzAuOTU3NloiIGZpbGw9IiNENUY2Q0EiLz4NCjwvZz4NCjxkZWZzPg0KPGZpbHRlciBpZD0iZmlsdGVyMF9kXzIwNDBfMTI5MSIgeD0iMCIgeT0iMCIgd2lkdGg9IjUyMCIgaGVpZ2h0PSI1MjAiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4NCjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+DQo8ZmVDb2xvck1hdHJpeCBpbj0iU291cmNlQWxwaGEiIHR5cGU9Im1hdHJpeCIgdmFsdWVzPSIwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAxMjcgMCIgcmVzdWx0PSJoYXJkQWxwaGEiLz4NCjxmZU9mZnNldCBkeT0iNCIvPg0KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iMiIvPg0KPGZlQ29tcG9zaXRlIGluMj0iaGFyZEFscGhhIiBvcGVyYXRvcj0ib3V0Ii8+DQo8ZmVDb2xvck1hdHJpeCB0eXBlPSJtYXRyaXgiIHZhbHVlcz0iMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMC4yNSAwIi8+DQo8ZmVCbGVuZCBtb2RlPSJub3JtYWwiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9ImVmZmVjdDFfZHJvcFNoYWRvd18yMDQwXzEyOTEiLz4NCjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iZWZmZWN0MV9kcm9wU2hhZG93XzIwNDBfMTI5MSIgcmVzdWx0PSJzaGFwZSIvPg0KPC9maWx0ZXI+DQo8Y2xpcFBhdGggaWQ9ImNsaXAwXzIwNDBfMTI5MSI+DQo8cmVjdCB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgZmlsbD0id2hpdGUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDQpIi8+DQo8L2NsaXBQYXRoPg0KPC9kZWZzPg0KPC9zdmc+";

    function _boldLogo(FixedAssetReader _assetReader) internal view returns (string memory) {
        return svg.el(
            "image",
            string.concat(
                svg.prop("x", "264"),
                svg.prop("y", "373.5"),
                svg.prop("width", "20"),
                svg.prop("height", "20"),
                svg.prop(
                    "href",
                    usndLogo.getLogo()
                )
            )
        );
    }

    function _staticTextEls() internal pure returns (string memory) {
        return string.concat(
            svg.text(
                string.concat(
                    GEIST,
                    svg.prop("x", "16"),
                    svg.prop("y", "358"),
                    svg.prop("font-size", "14"),
                    svg.prop("fill", "white")
                ),
                "Collateral"
            ),
            svg.text(
                string.concat(
                    GEIST,
                    svg.prop("x", "16"),
                    svg.prop("y", "389"),
                    svg.prop("font-size", "14"),
                    svg.prop("fill", "white")
                ),
                "Debt"
            ),
            svg.text(
                string.concat(
                    GEIST,
                    svg.prop("x", "16"),
                    svg.prop("y", "420"),
                    svg.prop("font-size", "14"),
                    svg.prop("fill", "white")
                ),
                "Interest Rate"
            ),
            svg.text(
                string.concat(
                    GEIST,
                    svg.prop("x", "265"),
                    svg.prop("y", "422"),
                    svg.prop("font-size", "20"),
                    svg.prop("fill", "white")
                ),
                "%"
            ),
            svg.text(
                string.concat(
                    GEIST,
                    svg.prop("x", "16"),
                    svg.prop("y", "462"),
                    svg.prop("font-size", "14"),
                    svg.prop("fill", "white")
                ),
                "Owner"
            )
        );
    }

    function _formattedDynamicEl(string memory _value, uint256 _x, uint256 _y) internal pure returns (string memory) {
        return svg.text(
            string.concat(
                GEIST,
                svg.prop("text-anchor", "end"),
                svg.prop("x", LibString.toString(_x)),
                svg.prop("y", LibString.toString(_y)),
                svg.prop("font-size", "20"),
                svg.prop("fill", "white")
            ),
            _value
        );
    }

    function _formattedIdEl(string memory _id) internal pure returns (string memory) {
        return svg.text(
            string.concat(
                GEIST,
                svg.prop("text-anchor", "end"),
                svg.prop("x", "284"),
                svg.prop("y", "33"),
                svg.prop("font-size", "14"),
                svg.prop("fill", "white")
            ),
            _id
        );
    }

    function _formattedAddressEl(address _address) internal pure returns (string memory) {
        return svg.text(
            string.concat(
                GEIST,
                svg.prop("text-anchor", "end"),
                svg.prop("x", "284"),
                svg.prop("y", "462"),
                svg.prop("font-size", "14"),
                svg.prop("fill", "white")
            ),
            string.concat(
                LibString.slice(LibString.toHexStringChecksummed(_address), 0, 6),
                "...",
                LibString.slice(LibString.toHexStringChecksummed(_address), 38, 42)
            )
        );
    }

    function _collLogo(string memory _collName, FixedAssetReader _assetReader) internal view returns (string memory) {
        return svg.el(
            "image",
            string.concat(
                svg.prop("x", "264"),
                svg.prop("y", "342.5"),
                svg.prop("width", "20"),
                svg.prop("height", "20"),
                svg.prop(
                    "href",
                    string.concat(
                        "data:image/svg+xml;base64,", _assetReader.readAsset(bytes4(keccak256(bytes(_collName))))
                    )
                )
            )
        );
    }

    function _statusEl(string memory _status) internal pure returns (string memory) {
        return svg.text(
            string.concat(
                GEIST, svg.prop("x", "40"), svg.prop("y", "33"), svg.prop("font-size", "14"), svg.prop("fill", "white")
            ),
            _status
        );
    }

    function _dynamicTextEls(uint256 _debt, uint256 _coll, uint256 _annualInterestRate)
        internal
        pure
        returns (string memory)
    {
        return string.concat(
            _formattedDynamicEl(numUtils.toLocaleString(_coll, 18, 4), 256, 360),
            _formattedDynamicEl(numUtils.toLocaleString(_debt, 18, 2), 256, 391),
            _formattedDynamicEl(numUtils.toLocaleString(_annualInterestRate, 16, 2), 256, 422)
        );
    }
    
}

//SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "./SVG.sol";

library bauhaus {
    string constant GOLDEN = "#F5D93A";
    string constant CORAL = "#FB7C59";
    string constant GREEN = "#63D77D";
    string constant CYAN = "#95CBF3";
    string constant BLUE = "#405AE5";
    string constant DARK_BLUE = "#121B44";
    string constant BROWN = "#D99664";

    enum colorCode {
        GOLDEN,
        CORAL,
        GREEN,
        CYAN,
        BLUE,
        DARK_BLUE,
        BROWN
    }

    function _bauhaus(string memory _collName, uint256 _troveId) internal pure returns (string memory) {
        bytes32 collSig = keccak256(bytes(_collName));
        uint256 variant = _troveId % 4;

        if (collSig == keccak256("WETH")) {
            return _img1(variant);
        } else if (collSig == keccak256("wstETH")) {
            return _img2(variant);
        } else {
            // assume rETH
            return _img3(variant);
        }
    }

    function _colorCode2Hex(colorCode _color) private pure returns (string memory) {
        if (_color == colorCode.GOLDEN) {
            return GOLDEN;
        } else if (_color == colorCode.CORAL) {
            return CORAL;
        } else if (_color == colorCode.GREEN) {
            return GREEN;
        } else if (_color == colorCode.CYAN) {
            return CYAN;
        } else if (_color == colorCode.BLUE) {
            return BLUE;
        } else if (_color == colorCode.DARK_BLUE) {
            return DARK_BLUE;
        } else {
            return BROWN;
        }
    }

    struct COLORS {
        colorCode rect1;
        colorCode rect2;
        colorCode rect3;
        colorCode rect4;
        colorCode rect5;
        colorCode poly;
        colorCode circle1;
        colorCode circle2;
        colorCode circle3;
    }

    function _colors1(uint256 _variant) internal pure returns (COLORS memory) {
        if (_variant == 0) {
            return COLORS(
                colorCode.BLUE, // rect1
                colorCode.GOLDEN, // rect2
                colorCode.GOLDEN, // rect3
                colorCode.BROWN, // rect4
                colorCode.CORAL, // rect5
                colorCode.CYAN, // poly
                colorCode.GREEN, // circle1
                colorCode.DARK_BLUE, // circle2
                colorCode.GOLDEN // circle3
            );
        } else if (_variant == 1) {
            return COLORS(
                colorCode.GREEN, // rect1
                colorCode.BLUE, // rect2
                colorCode.GOLDEN, // rect3
                colorCode.BROWN, // rect4
                colorCode.GOLDEN, // rect5
                colorCode.CORAL, // poly
                colorCode.BLUE, // circle1
                colorCode.DARK_BLUE, // circle2
                colorCode.BLUE // circle3
            );
        } else if (_variant == 2) {
            return COLORS(
                colorCode.BLUE, // rect1
                colorCode.GOLDEN, // rect2
                colorCode.CYAN, // rect3
                colorCode.GOLDEN, // rect4
                colorCode.BROWN, // rect5
                colorCode.GREEN, // poly
                colorCode.CORAL, // circle1
                colorCode.DARK_BLUE, // circle2
                colorCode.BROWN // circle3
            );
        } else {
            return COLORS(
                colorCode.CYAN, // rect1
                colorCode.BLUE, // rect2
                colorCode.BLUE, // rect3
                colorCode.BROWN, // rect4
                colorCode.BLUE, // rect5
                colorCode.GREEN, // poly
                colorCode.GOLDEN, // circle1
                colorCode.DARK_BLUE, // circle2
                colorCode.BLUE // circle3
            );
        }
    }

    function _img1(uint256 _variant) internal pure returns (string memory) {
        COLORS memory colors = _colors1(_variant);
        return string.concat(_rects1(colors), _polygons1(colors), _circles1(colors));
    }

    function _rects1(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            //background
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "55"),
                    svg.prop("width", "268"),
                    svg.prop("height", "268"),
                    svg.prop("fill", DARK_BLUE)
                )
            ),
            // large right rect | rect1
            svg.rect(
                string.concat(
                    svg.prop("x", "128"),
                    svg.prop("y", "55"),
                    svg.prop("width", "156"),
                    svg.prop("height", "268"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect1))
                )
            ),
            // small upper right rect | rect2
            svg.rect(
                string.concat(
                    svg.prop("x", "228"),
                    svg.prop("y", "55"),
                    svg.prop("width", "56"),
                    svg.prop("height", "56"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect2))
                )
            ),
            // large central left rect | rect3
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "111"),
                    svg.prop("width", "134"),
                    svg.prop("height", "156"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect3))
                )
            ),
            // small lower left rect | rect4
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "267"),
                    svg.prop("width", "112"),
                    svg.prop("height", "56"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect4))
                )
            ),
            // small lower right rect | rect5
            svg.rect(
                string.concat(
                    svg.prop("x", "228"),
                    svg.prop("y", "267"),
                    svg.prop("width", "56"),
                    svg.prop("height", "56"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect5))
                )
            )
        );
    }

    function _polygons1(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            // left triangle | poly1
            svg.polygon(
                string.concat(svg.prop("points", "16,55 72,55 16,111"), svg.prop("fill", _colorCode2Hex(_colors.poly)))
            ),
            // right triangle | poly2
            svg.polygon(
                string.concat(svg.prop("points", "72,55 128,55 72,111"), svg.prop("fill", _colorCode2Hex(_colors.poly)))
            )
        );
    }

    function _circles1(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            //large central circle | circle1
            svg.circle(
                string.concat(
                    svg.prop("cx", "150"),
                    svg.prop("cy", "189"),
                    svg.prop("r", "78"),
                    svg.prop("fill", _colorCode2Hex(_colors.circle1))
                )
            ),
            //small right circle | circle2
            svg.circle(
                string.concat(
                    svg.prop("cx", "228"),
                    svg.prop("cy", "295"),
                    svg.prop("r", "28"),
                    svg.prop("fill", _colorCode2Hex(_colors.circle2))
                )
            ),
            //small right half circle | circle3
            svg.path(
                "M228 267C220.574 267 213.452 269.95 208.201 275.201C202.95 280.452 200 287.574 200 295C200 302.426 202.95 309.548 208.201 314.799C213.452 320.05 220.574 323 228 323L228 267Z",
                svg.prop("fill", _colorCode2Hex(_colors.circle3))
            )
        );
    }

    function _colors2(uint256 _variant) internal pure returns (COLORS memory) {
        if (_variant == 0) {
            return COLORS(
                colorCode.BROWN, // rect1
                colorCode.GOLDEN, // rect2
                colorCode.BLUE, // rect3
                colorCode.GREEN, // rect4
                colorCode.CORAL, // rect5
                colorCode.GOLDEN, // unused
                colorCode.GOLDEN, // circle1
                colorCode.CYAN, // circle2
                colorCode.GREEN // circle3
            );
        } else if (_variant == 1) {
            return COLORS(
                colorCode.GREEN, // rect1
                colorCode.BROWN, // rect2
                colorCode.GOLDEN, // rect3
                colorCode.BLUE, // rect4
                colorCode.CYAN, // rect5
                colorCode.GOLDEN, // unused
                colorCode.GREEN, // circle1
                colorCode.CORAL, // circle2
                colorCode.BLUE // circle3
            );
        } else if (_variant == 2) {
            return COLORS(
                colorCode.BLUE, // rect1
                colorCode.GOLDEN, // rect2
                colorCode.GREEN, // rect3
                colorCode.BLUE, // rect4
                colorCode.CORAL, // rect5
                colorCode.GOLDEN, // unused
                colorCode.CYAN, // circle1
                colorCode.BROWN, // circle2
                colorCode.BROWN // circle3
            );
        } else {
            return COLORS(
                colorCode.GOLDEN, // rect1
                colorCode.GREEN, // rect2
                colorCode.BLUE, // rect3
                colorCode.GOLDEN, // rect4
                colorCode.BROWN, // rect5
                colorCode.GOLDEN, // unused
                colorCode.BROWN, // circle1
                colorCode.CYAN, // circle2
                colorCode.CORAL // circle3
            );
        }
    }

    function _img2(uint256 _variant) internal pure returns (string memory) {
        COLORS memory colors = _colors2(_variant);
        return string.concat(_rects2(colors), _circles2(colors));
    }

    function _rects2(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            //background
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "55"),
                    svg.prop("width", "268"),
                    svg.prop("height", "268"),
                    svg.prop("fill", DARK_BLUE)
                )
            ),
            // large upper right rect | rect1
            svg.rect(
                string.concat(
                    svg.prop("x", "128"),
                    svg.prop("y", "55"),
                    svg.prop("width", "156"),
                    svg.prop("height", "156"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect1))
                )
            ),
            // large central left rect | rect2
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "111"),
                    svg.prop("width", "134"),
                    svg.prop("height", "100"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect2))
                )
            ),
            // large lower left rect | rect3
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "211"),
                    svg.prop("width", "212"),
                    svg.prop("height", "56"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect3))
                )
            ),
            // small lower central rect | rect4
            svg.rect(
                string.concat(
                    svg.prop("x", "72"),
                    svg.prop("y", "267"),
                    svg.prop("width", "78"),
                    svg.prop("height", "56"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect4))
                )
            ),
            // small lower right rect | rect5
            svg.rect(
                string.concat(
                    svg.prop("x", "150"),
                    svg.prop("y", "267"),
                    svg.prop("width", "134"),
                    svg.prop("height", "56"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect5))
                )
            )
        );
    }

    function _circles2(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            //lower left circle | circle1
            svg.circle(
                string.concat(
                    svg.prop("cx", "44"),
                    svg.prop("cy", "295"),
                    svg.prop("r", "28"),
                    svg.prop("fill", _colorCode2Hex(_colors.circle1))
                )
            ),
            //upper left half circle | circle2
            svg.path(
                "M16 55C16 62.4 17.4 69.6 20.3 76.4C23.1 83.2 27.2 89.4 32.4 94.6C37.6 99.8 43.8 103.9 50.6 106.7C57.4 109.6 64.6 111 72 111C79.4 111 86.6 109.6 93.4 106.7C100.2 103.9 106.4 99.8 111.6 94.6C116.8 89.4 120.9 83.2 123.7 76.4C126.6 69.6 128 62.4 128 55L16 55Z",
                svg.prop("fill", _colorCode2Hex(_colors.circle2))
            ),
            //central right half circle | circle3
            svg.path(
                "M284 211C284 190.3 275.8 170.5 261.2 155.8C246.5 141.2 226.7 133 206 133C185.3 133 165.5 141.2 150.9 155.86C136.2 170.5 128 190.3 128 211L284 211Z",
                svg.prop("fill", _colorCode2Hex(_colors.circle3))
            )
        );
    }

    function _colors3(uint256 _variant) internal pure returns (COLORS memory) {
        if (_variant == 0) {
            return COLORS(
                colorCode.BLUE, // rect1
                colorCode.CORAL, // rect2
                colorCode.BLUE, // rect3
                colorCode.GREEN, // rect4
                colorCode.GOLDEN, // unused
                colorCode.GOLDEN, // unused
                colorCode.GOLDEN, // circle1
                colorCode.CYAN, // circle2
                colorCode.GOLDEN // circle3
            );
        } else if (_variant == 1) {
            return COLORS(
                colorCode.CORAL, // rect1
                colorCode.GREEN, // rect2
                colorCode.BROWN, // rect3
                colorCode.GOLDEN, // rect4
                colorCode.GOLDEN, // unused
                colorCode.GOLDEN, // unused
                colorCode.BLUE, // circle1
                colorCode.BLUE, // circle2
                colorCode.CYAN // circle3
            );
        } else if (_variant == 2) {
            return COLORS(
                colorCode.CORAL, // rect1
                colorCode.CYAN, // rect2
                colorCode.CORAL, // rect3
                colorCode.GOLDEN, // rect4
                colorCode.GOLDEN, // unused
                colorCode.GOLDEN, // unused
                colorCode.GREEN, // circle1
                colorCode.BLUE, // circle2
                colorCode.GREEN // circle3
            );
        } else {
            return COLORS(
                colorCode.GOLDEN, // rect1
                colorCode.CORAL, // rect2
                colorCode.GREEN, // rect3
                colorCode.BLUE, // rect4
                colorCode.GOLDEN, // unused
                colorCode.GOLDEN, // unused
                colorCode.BROWN, // circle1
                colorCode.BLUE, // circle2
                colorCode.GREEN // circle3
            );
        }
    }

    function _img3(uint256 _variant) internal pure returns (string memory) {
        COLORS memory colors = _colors3(_variant);
        return string.concat(_rects3(colors), _circles3(colors));
    }

    function _rects3(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            //background
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "55"),
                    svg.prop("width", "268"),
                    svg.prop("height", "268"),
                    svg.prop("fill", DARK_BLUE)
                )
            ),
            // lower left rect | rect1
            svg.rect(
                string.concat(
                    svg.prop("x", "16"),
                    svg.prop("y", "205"),
                    svg.prop("width", "75"),
                    svg.prop("height", "118"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect1))
                )
            ),
            // central rect | rect2
            svg.rect(
                string.concat(
                    svg.prop("x", "91"),
                    svg.prop("y", "205"),
                    svg.prop("width", "136"),
                    svg.prop("height", "59"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect2))
                )
            ),
            // central right rect | rect3
            svg.rect(
                string.concat(
                    svg.prop("x", "166"),
                    svg.prop("y", "180"),
                    svg.prop("width", "118"),
                    svg.prop("height", "25"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect3))
                )
            ),
            // upper right rect | rect4
            svg.rect(
                string.concat(
                    svg.prop("x", "166"),
                    svg.prop("y", "55"),
                    svg.prop("width", "118"),
                    svg.prop("height", "126"),
                    svg.prop("fill", _colorCode2Hex(_colors.rect4))
                )
            )
        );
    }

    function _circles3(COLORS memory _colors) internal pure returns (string memory) {
        return string.concat(
            //upper left circle | circle1
            svg.circle(
                string.concat(
                    svg.prop("cx", "91"),
                    svg.prop("cy", "130"),
                    svg.prop("r", "75"),
                    svg.prop("fill", _colorCode2Hex(_colors.circle1))
                )
            ),
            //upper right half circle | circle2
            svg.path(
                "M284 264 166 264 166 263C166 232 193 206 225 205C258 206 284 232 284 264C284 264 284 264 284 264Z",
                svg.prop("fill", _colorCode2Hex(_colors.circle2))
            ),
            //lower right half circle | circle3
            svg.path(
                "M284 323 166 323 166 323C166 290 193 265 225 264C258 265 284 290 284 323C284 323 284 323 284 323Z",
                svg.prop("fill", _colorCode2Hex(_colors.circle3))
            )
        );
    }
}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

/**
 * @title Super app definitions library
 * @author Superfluid
 */
library SuperAppDefinitions {

    /**************************************************************************
    / App manifest config word
    /**************************************************************************/

    /*
     * App level is a way to allow the app to whitelist what other app it can
     * interact with (aka. composite app feature).
     *
     * For more details, refer to the technical paper of superfluid protocol.
     */
    uint256 constant internal APP_LEVEL_MASK = 0xFF;

    // The app is at the final level, hence it doesn't want to interact with any other app
    uint256 constant internal APP_LEVEL_FINAL = 1 << 0;

    // The app is at the second level, it may interact with other final level apps if whitelisted
    uint256 constant internal APP_LEVEL_SECOND = 1 << 1;

    function getAppCallbackLevel(uint256 configWord) internal pure returns (uint8) {
        return uint8(configWord & APP_LEVEL_MASK);
    }

    uint256 constant internal APP_JAIL_BIT = 1 << 15;
    function isAppJailed(uint256 configWord) internal pure returns (bool) {
        return (configWord & SuperAppDefinitions.APP_JAIL_BIT) > 0;
    }

    /**************************************************************************
    / Callback implementation bit masks
    /**************************************************************************/
    uint256 constant internal AGREEMENT_CALLBACK_NOOP_BITMASKS = 0xFF << 32;
    uint256 constant internal BEFORE_AGREEMENT_CREATED_NOOP = 1 << (32 + 0);
    uint256 constant internal AFTER_AGREEMENT_CREATED_NOOP = 1 << (32 + 1);
    uint256 constant internal BEFORE_AGREEMENT_UPDATED_NOOP = 1 << (32 + 2);
    uint256 constant internal AFTER_AGREEMENT_UPDATED_NOOP = 1 << (32 + 3);
    uint256 constant internal BEFORE_AGREEMENT_TERMINATED_NOOP = 1 << (32 + 4);
    uint256 constant internal AFTER_AGREEMENT_TERMINATED_NOOP = 1 << (32 + 5);

    /**************************************************************************
    / App Jail Reasons
    /**************************************************************************/
    uint256 constant internal APP_RULE_NO_REVERT_ON_TERMINATION_CALLBACK = 10;
    uint256 constant internal APP_RULE_NO_CRITICAL_SENDER_ACCOUNT = 11;
    uint256 constant internal APP_RULE_NO_CRITICAL_RECEIVER_ACCOUNT = 12;
    uint256 constant internal APP_RULE_CTX_IS_READONLY = 20;
    uint256 constant internal APP_RULE_CTX_IS_NOT_CLEAN = 21;
    uint256 constant internal APP_RULE_CTX_IS_MALFORMATED = 22;
    uint256 constant internal APP_RULE_COMPOSITE_APP_IS_NOT_WHITELISTED = 30;
    uint256 constant internal APP_RULE_COMPOSITE_APP_IS_JAILED = 31;
    uint256 constant internal APP_RULE_MAX_APP_LEVEL_REACHED = 40;

    // Validate configWord cleaness for future compatibility, or else may introduce undefined future behavior
    function isConfigWordClean(uint256 configWord) internal pure returns (bool) {
        return (configWord & ~(APP_LEVEL_MASK | APP_JAIL_BIT | AGREEMENT_CALLBACK_NOOP_BITMASKS)) == uint256(0);
    }
}

/**
 * @title Context definitions library
 * @author Superfluid
 */
library ContextDefinitions {

    /**************************************************************************
    / Call info
    /**************************************************************************/

    // app level
    uint256 constant internal CALL_INFO_APP_LEVEL_MASK = 0xFF;

    // call type
    uint256 constant internal CALL_INFO_CALL_TYPE_SHIFT = 32;
    uint256 constant internal CALL_INFO_CALL_TYPE_MASK = 0xF << CALL_INFO_CALL_TYPE_SHIFT;
    uint8 constant internal CALL_INFO_CALL_TYPE_AGREEMENT = 1;
    uint8 constant internal CALL_INFO_CALL_TYPE_APP_ACTION = 2;
    uint8 constant internal CALL_INFO_CALL_TYPE_APP_CALLBACK = 3;

    function decodeCallInfo(uint256 callInfo)
        internal pure
        returns (uint8 appCallbackLevel, uint8 callType)
    {
        appCallbackLevel = uint8(callInfo & CALL_INFO_APP_LEVEL_MASK);
        callType = uint8((callInfo & CALL_INFO_CALL_TYPE_MASK) >> CALL_INFO_CALL_TYPE_SHIFT);
    }

    function encodeCallInfo(uint8 appCallbackLevel, uint8 callType)
        internal pure
        returns (uint256 callInfo)
    {
        return uint256(appCallbackLevel) | (uint256(callType) << CALL_INFO_CALL_TYPE_SHIFT);
    }

}

/**
 * @title Flow Operator definitions library
  * @author Superfluid
 */
library FlowOperatorDefinitions {
   uint8 constant internal AUTHORIZE_FLOW_OPERATOR_CREATE = uint8(1) << 0;
   uint8 constant internal AUTHORIZE_FLOW_OPERATOR_UPDATE = uint8(1) << 1;
   uint8 constant internal AUTHORIZE_FLOW_OPERATOR_DELETE = uint8(1) << 2;
   uint8 constant internal AUTHORIZE_FULL_CONTROL =
       AUTHORIZE_FLOW_OPERATOR_CREATE | AUTHORIZE_FLOW_OPERATOR_UPDATE | AUTHORIZE_FLOW_OPERATOR_DELETE;
   uint8 constant internal REVOKE_FLOW_OPERATOR_CREATE = ~(uint8(1) << 0);
   uint8 constant internal REVOKE_FLOW_OPERATOR_UPDATE = ~(uint8(1) << 1);
   uint8 constant internal REVOKE_FLOW_OPERATOR_DELETE = ~(uint8(1) << 2);

   function isPermissionsClean(uint8 permissions) internal pure returns (bool) {
       return (
           permissions & ~(AUTHORIZE_FLOW_OPERATOR_CREATE
               | AUTHORIZE_FLOW_OPERATOR_UPDATE
               | AUTHORIZE_FLOW_OPERATOR_DELETE)
           ) == uint8(0);
   }
}

/**
 * @title Batch operation library
 * @author Superfluid
 */
library BatchOperation {
    /**
     * @dev ERC20.approve batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationApprove(
     *     abi.decode(data, (address spender, uint256 amount))
     * )
     */
    uint32 constant internal OPERATION_TYPE_ERC20_APPROVE = 1;
    /**
     * @dev ERC20.transferFrom batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationTransferFrom(
     *     abi.decode(data, (address sender, address recipient, uint256 amount)
     * )
     */
    uint32 constant internal OPERATION_TYPE_ERC20_TRANSFER_FROM = 2;
    /**
     * @dev ERC777.send batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationSend(
     *     abi.decode(data, (address recipient, uint256 amount, bytes userData)
     * )
     */
    uint32 constant internal OPERATION_TYPE_ERC777_SEND = 3;
    /**
     * @dev ERC20.increaseAllowance batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationIncreaseAllowance(
     *     abi.decode(data, (address account, address spender, uint256 addedValue))
     * )
     */
    uint32 constant internal OPERATION_TYPE_ERC20_INCREASE_ALLOWANCE = 4;
    /**
     * @dev ERC20.decreaseAllowance batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationDecreaseAllowance(
     *     abi.decode(data, (address account, address spender, uint256 subtractedValue))
     * )
     */
    uint32 constant internal OPERATION_TYPE_ERC20_DECREASE_ALLOWANCE = 5;
    /**
     * @dev SuperToken.upgrade batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationUpgrade(
     *     abi.decode(data, (uint256 amount)
     * )
     */
    uint32 constant internal OPERATION_TYPE_SUPERTOKEN_UPGRADE = 1 + 100;
    /**
     * @dev SuperToken.downgrade batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationDowngrade(
     *     abi.decode(data, (uint256 amount)
     * )
     */
    uint32 constant internal OPERATION_TYPE_SUPERTOKEN_DOWNGRADE = 2 + 100;
    /**
     * @dev SuperToken.upgradeTo batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationUpgradeTo(
     *     abi.decode(data, (address to, uint256 amount)
     * )
     */
    uint32 constant internal OPERATION_TYPE_SUPERTOKEN_UPGRADE_TO = 3 + 100;
    /**
     * @dev SuperToken.downgradeTo batch operation type
     *
     * Call spec:
     * ISuperToken(target).operationDowngradeTo(
     *     abi.decode(data, (address to, uint256 amount)
     * )
     */
    uint32 constant internal OPERATION_TYPE_SUPERTOKEN_DOWNGRADE_TO = 4 + 100;
    /**
     * @dev Superfluid.callAgreement batch operation type
     *
     * Call spec:
     * callAgreement(
     *     ISuperAgreement(target)),
     *     abi.decode(data, (bytes callData, bytes userData)
     * )
     */
    uint32 constant internal OPERATION_TYPE_SUPERFLUID_CALL_AGREEMENT = 1 + 200;
    /**
     * @dev Superfluid.callAppAction batch operation type
     *
     * Call spec:
     * callAppAction(
     *     ISuperApp(target)),
     *     data
     * )
     */
    uint32 constant internal OPERATION_TYPE_SUPERFLUID_CALL_APP_ACTION = 2 + 200;
    /**
     * @dev SimpleForwarder.forwardCall batch operation type
     *
     * Call spec:
     * forwardCall(
     *     target,
     *     data
     * )
     * NOTE: This operation allows to make arbitrary calls to arbitrary targets.
     * The calls are routed through a dedicated utility contract `SimpleForwarder`.
     * This is important because the host contract has privileged access to other framework contracts,
     * SuperTokens, SuperApps etc.
     * Allowing arbitrary calls to arbitrary targets with the host as sender would thus be unsafe.
     */
    uint32 constant internal OPERATION_TYPE_SIMPLE_FORWARD_CALL = 1 + 300;
    /**
     * @dev ERC2771Forwarder.forward2771Call batch operation type
     *
     * Call spec:
     * forward2771Call(
     *     target,
     *     msgSender,
     *     data
     * )
     *
     * NOTE: In the context of this operation, the `ERC2771Forwarder` contract acts as the
     * _trusted forwarder_ which must be trusted by the _recipient contract_ (operation target).
     * It shall do so by dynamically looking up the ERC2771Forwarder used by the host, like this:
     *
     * function isTrustedForwarder(address forwarder) public view returns(bool) {
     *     return forwarder == address(host.getERC2771Forwarder());
     * }
     *
     * If used in the context of a `forwardBatchCall`, we effectively have a chaining/nesting
     * of ERC-2771 calls where the host acts as _recipient contract_ of the enveloping 2771 call
     * and the ERC2771Forwarder acts as the _trusted forwarder_ of the nested 2771 call(s).
     * That's why `msgSender` could be either the actual `msg.sender` (if using `batchCall`)
     * or the relayed sender address (if using `forwardBatchCall`).
     */
    uint32 constant internal OPERATION_TYPE_ERC2771_FORWARD_CALL = 2 + 300;
}

/**
 * @title Superfluid governance configs library
 * @author Superfluid
 */
library SuperfluidGovernanceConfigs {

    bytes32 constant internal SUPERFLUID_REWARD_ADDRESS_CONFIG_KEY =
        keccak256("org.superfluid-finance.superfluid.rewardAddress");
    bytes32 constant internal CFAV1_PPP_CONFIG_KEY =
        keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1.PPPConfiguration");
    bytes32 constant internal SUPERTOKEN_MINIMUM_DEPOSIT_KEY =
        keccak256("org.superfluid-finance.superfluid.superTokenMinimumDeposit");

    function getTrustedForwarderConfigKey(address forwarder) internal pure returns (bytes32) {
        return keccak256(abi.encode(
            "org.superfluid-finance.superfluid.trustedForwarder",
            forwarder));
    }

    function getAppRegistrationConfigKey(address deployer, string memory registrationKey) internal pure
        returns (bytes32)
    {
        return keccak256(abi.encode(
            "org.superfluid-finance.superfluid.appWhiteListing.registrationKey",
            deployer,
            registrationKey));
    }

    function getAppFactoryConfigKey(address factory) internal pure returns (bytes32)
    {
        return keccak256(abi.encode(
            "org.superfluid-finance.superfluid.appWhiteListing.factory",
            factory));
    }

    function decodePPPConfig(uint256 pppConfig) internal pure
        returns (uint256 liquidationPeriod, uint256 patricianPeriod)
    {
        liquidationPeriod = (pppConfig >> 32) & type(uint32).max;
        patricianPeriod = pppConfig & type(uint32).max;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC777/IERC777.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC777Token standard as defined in the EIP.
 *
 * This contract uses the
 * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
 * token holders and recipients react to token movements by using setting implementers
 * for the associated interfaces in said registry. See {IERC1820Registry} and
 * {ERC1820Implementer}.
 */
interface IERC777 {
    /**
     * @dev Emitted when `amount` tokens are created by `operator` and assigned to `to`.
     *
     * Note that some additional user `data` and `operatorData` can be logged in the event.
     */
    event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);

    /**
     * @dev Emitted when `operator` destroys `amount` tokens from `account`.
     *
     * Note that some additional user `data` and `operatorData` can be logged in the event.
     */
    event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);

    /**
     * @dev Emitted when `operator` is made operator for `tokenHolder`.
     */
    event AuthorizedOperator(address indexed operator, address indexed tokenHolder);

    /**
     * @dev Emitted when `operator` is revoked its operator status for `tokenHolder`.
     */
    event RevokedOperator(address indexed operator, address indexed tokenHolder);

    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the smallest part of the token that is not divisible. This
     * means all token operations (creation, movement and destruction) must have
     * amounts that are a multiple of this number.
     *
     * For most token contracts, this value will equal 1.
     */
    function granularity() external view returns (uint256);

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

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * If send or receive hooks are registered for the caller and `recipient`,
     * the corresponding functions will be called with `data` and empty
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * Emits a {Sent} event.
     *
     * Requirements
     *
     * - the caller must have at least `amount` tokens.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function send(address recipient, uint256 amount, bytes calldata data) external;

    /**
     * @dev Destroys `amount` tokens from the caller's account, reducing the
     * total supply.
     *
     * If a send hook is registered for the caller, the corresponding function
     * will be called with `data` and empty `operatorData`. See {IERC777Sender}.
     *
     * Emits a {Burned} event.
     *
     * Requirements
     *
     * - the caller must have at least `amount` tokens.
     */
    function burn(uint256 amount, bytes calldata data) external;

    /**
     * @dev Returns true if an account is an operator of `tokenHolder`.
     * Operators can send and burn tokens on behalf of their owners. All
     * accounts are their own operator.
     *
     * See {operatorSend} and {operatorBurn}.
     */
    function isOperatorFor(address operator, address tokenHolder) external view returns (bool);

    /**
     * @dev Make an account an operator of the caller.
     *
     * See {isOperatorFor}.
     *
     * Emits an {AuthorizedOperator} event.
     *
     * Requirements
     *
     * - `operator` cannot be calling address.
     */
    function authorizeOperator(address operator) external;

    /**
     * @dev Revoke an account's operator status for the caller.
     *
     * See {isOperatorFor} and {defaultOperators}.
     *
     * Emits a {RevokedOperator} event.
     *
     * Requirements
     *
     * - `operator` cannot be calling address.
     */
    function revokeOperator(address operator) external;

    /**
     * @dev Returns the list of default operators. These accounts are operators
     * for all token holders, even if {authorizeOperator} was never called on
     * them.
     *
     * This list is immutable, but individual holders may revoke these via
     * {revokeOperator}, in which case {isOperatorFor} will return false.
     */
    function defaultOperators() external view returns (address[] memory);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
     * be an operator of `sender`.
     *
     * If send or receive hooks are registered for `sender` and `recipient`,
     * the corresponding functions will be called with `data` and
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * Emits a {Sent} event.
     *
     * Requirements
     *
     * - `sender` cannot be the zero address.
     * - `sender` must have at least `amount` tokens.
     * - the caller must be an operator for `sender`.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function operatorSend(
        address sender,
        address recipient,
        uint256 amount,
        bytes calldata data,
        bytes calldata operatorData
    ) external;

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the total supply.
     * The caller must be an operator of `account`.
     *
     * If a send hook is registered for `account`, the corresponding function
     * will be called with `data` and `operatorData`. See {IERC777Sender}.
     *
     * Emits a {Burned} event.
     *
     * Requirements
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     * - the caller must be an operator for `account`.
     */
    function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external;

    event Sent(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256 amount,
        bytes data,
        bytes operatorData
    );
}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

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

/**
 * @title Superfluid token interface
 * @author Superfluid
 */
interface ISuperfluidToken {

    /**************************************************************************
     * Errors
     *************************************************************************/
    error SF_TOKEN_AGREEMENT_ALREADY_EXISTS();  // 0xf05521f6
    error SF_TOKEN_AGREEMENT_DOES_NOT_EXIST();  // 0xdae18809
    error SF_TOKEN_BURN_INSUFFICIENT_BALANCE(); // 0x10ecdf44
    error SF_TOKEN_MOVE_INSUFFICIENT_BALANCE(); // 0x2f4cb941
    error SF_TOKEN_ONLY_LISTED_AGREEMENT();     // 0xc9ff6644
    error SF_TOKEN_ONLY_HOST();                 // 0xc51efddd

    /**************************************************************************
     * Basic information
     *************************************************************************/

    /**
     * @dev Get superfluid host contract address
     */
    function getHost() external view returns(address host);

    /**
     * @dev Encoded liquidation type data mainly used for handling stack to deep errors
     *
     * @custom:note 
     * - version: 1
     * - liquidationType key:
     *    - 0 = reward account receives reward (PIC period)
     *    - 1 = liquidator account receives reward (Pleb period)
     *    - 2 = liquidator account receives reward (Pirate period/bailout)
     */
    struct LiquidationTypeData {
        uint256 version;
        uint8 liquidationType;
    }

    /**************************************************************************
     * Real-time balance functions
     *************************************************************************/

    /**
    * @dev Calculate the real balance of a user, taking in consideration all agreements of the account
    * @param account for the query
    * @param timestamp Time of balance
    * @return availableBalance Real-time balance
    * @return deposit Account deposit
    * @return owedDeposit Account owed Deposit
    */
    function realtimeBalanceOf(
       address account,
       uint256 timestamp
    )
        external view
        returns (
            int256 availableBalance,
            uint256 deposit,
            uint256 owedDeposit);

    /**
     * @notice Calculate the realtime balance given the current host.getNow() value
     * @dev realtimeBalanceOf with timestamp equals to block timestamp
     * @param account for the query
     * @return availableBalance Real-time balance
     * @return deposit Account deposit
     * @return owedDeposit Account owed Deposit
     */
    function realtimeBalanceOfNow(
       address account
    )
        external view
        returns (
            int256 availableBalance,
            uint256 deposit,
            uint256 owedDeposit,
            uint256 timestamp);

    /**
    * @notice Check if account is critical
    * @dev A critical account is when availableBalance < 0
    * @param account The account to check
    * @param timestamp The time we'd like to check if the account is critical (should use future)
    * @return isCritical Whether the account is critical
    */
    function isAccountCritical(
        address account,
        uint256 timestamp
    )
        external view
        returns(bool isCritical);

    /**
    * @notice Check if account is critical now (current host.getNow())
    * @dev A critical account is when availableBalance < 0
    * @param account The account to check
    * @return isCritical Whether the account is critical
    */
    function isAccountCriticalNow(
        address account
    )
        external view
        returns(bool isCritical);

    /**
     * @notice Check if account is solvent
     * @dev An account is insolvent when the sum of deposits for a token can't cover the negative availableBalance
     * @param account The account to check
     * @param timestamp The time we'd like to check if the account is solvent (should use future)
     * @return isSolvent True if the account is solvent, false otherwise
     */
    function isAccountSolvent(
        address account,
        uint256 timestamp
    )
        external view
        returns(bool isSolvent);

    /**
     * @notice Check if account is solvent now
     * @dev An account is insolvent when the sum of deposits for a token can't cover the negative availableBalance
     * @param account The account to check
     * @return isSolvent True if the account is solvent, false otherwise
     */
    function isAccountSolventNow(
        address account
    )
        external view
        returns(bool isSolvent);

    /**
    * @notice Get a list of agreements that is active for the account
    * @dev An active agreement is one that has state for the account
    * @param account Account to query
    * @return activeAgreements List of accounts that have non-zero states for the account
    */
    function getAccountActiveAgreements(address account)
       external view
       returns(ISuperAgreement[] memory activeAgreements);


   /**************************************************************************
    * Super Agreement hosting functions
    *************************************************************************/

    /**
     * @dev Create a new agreement
     * @param id Agreement ID
     * @param data Agreement data
     */
    function createAgreement(
        bytes32 id,
        bytes32[] calldata data
    )
        external;
    /**
     * @dev Agreement created event
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     * @param data Agreement data
     */
    event AgreementCreated(
        address indexed agreementClass,
        bytes32 id,
        bytes32[] data
    );

    /**
     * @dev Get data of the agreement
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     * @return data Data of the agreement
     */
    function getAgreementData(
        address agreementClass,
        bytes32 id,
        uint dataLength
    )
        external view
        returns(bytes32[] memory data);

    /**
     * @dev Create a new agreement
     * @param id Agreement ID
     * @param data Agreement data
     */
    function updateAgreementData(
        bytes32 id,
        bytes32[] calldata data
    )
        external;
    /**
     * @dev Agreement updated event
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     * @param data Agreement data
     */
    event AgreementUpdated(
        address indexed agreementClass,
        bytes32 id,
        bytes32[] data
    );

    /**
     * @dev Close the agreement
     * @param id Agreement ID
     */
    function terminateAgreement(
        bytes32 id,
        uint dataLength
    )
        external;
    /**
     * @dev Agreement terminated event
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     */
    event AgreementTerminated(
        address indexed agreementClass,
        bytes32 id
    );

    /**
     * @dev Update agreement state slot
     * @param account Account to be updated
     *
     * @custom:note 
     * - To clear the storage out, provide zero-ed array of intended length
     */
    function updateAgreementStateSlot(
        address account,
        uint256 slotId,
        bytes32[] calldata slotData
    )
        external;
    /**
     * @dev Agreement account state updated event
     * @param agreementClass Contract address of the agreement
     * @param account Account updated
     * @param slotId slot id of the agreement state
     */
    event AgreementStateUpdated(
        address indexed agreementClass,
        address indexed account,
        uint256 slotId
    );

    /**
     * @dev Get data of the slot of the state of an agreement
     * @param agreementClass Contract address of the agreement
     * @param account Account to query
     * @param slotId slot id of the state
     * @param dataLength length of the state data
     */
    function getAgreementStateSlot(
        address agreementClass,
        address account,
        uint256 slotId,
        uint dataLength
    )
        external view
        returns (bytes32[] memory slotData);

    /**
     * @notice Settle balance from an account by the agreement
     * @dev The agreement needs to make sure that the balance delta is balanced afterwards
     * @param account Account to query.
     * @param delta Amount of balance delta to be settled
     *
     * @custom:modifiers 
     *  - onlyAgreement
     */
    function settleBalance(
        address account,
        int256 delta
    )
        external;

    /**
     * @dev Make liquidation payouts (v2)
     * @param id Agreement ID
     * @param liquidationTypeData Data regarding the version of the liquidation schema and the type
     * @param liquidatorAccount Address of the executor of the liquidation
     * @param useDefaultRewardAccount Whether or not the default reward account receives the rewardAmount
     * @param targetAccount Account to be liquidated
     * @param rewardAmount The amount the rewarded account will receive
     * @param targetAccountBalanceDelta The delta amount the target account balance should change by
     *
     * @custom:note 
     * - If a bailout is required (bailoutAmount > 0)
     *   - the actual reward (single deposit) goes to the executor,
     *   - while the reward account becomes the bailout account
     *   - total bailout include: bailout amount + reward amount
     *   - the targetAccount will be bailed out
     * - If a bailout is not required
     *   - the targetAccount will pay the rewardAmount
     *   - the liquidator (reward account in PIC period) will receive the rewardAmount
     *
     * @custom:modifiers 
     *  - onlyAgreement
     */
    function makeLiquidationPayoutsV2
    (
        bytes32 id,
        bytes memory liquidationTypeData,
        address liquidatorAccount,
        bool useDefaultRewardAccount,
        address targetAccount,
        uint256 rewardAmount,
        int256 targetAccountBalanceDelta
    ) external;
    /**
     * @dev Agreement liquidation event v2 (including agent account)
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     * @param liquidatorAccount Address of the executor of the liquidation
     * @param targetAccount Account of the stream sender
     * @param rewardAmountReceiver Account that collects the reward or bails out insolvent accounts
     * @param rewardAmount The amount the reward recipient account balance should change by
     * @param targetAccountBalanceDelta The amount the sender account balance should change by
     * @param liquidationTypeData The encoded liquidation type data including the version (how to decode)
     *
     * @custom:note 
     * Reward account rule:
     * - if the agreement is liquidated during the PIC period
     *   - the rewardAmountReceiver will get the rewardAmount (remaining deposit), regardless of the liquidatorAccount
     *   - the targetAccount will pay for the rewardAmount
     * - if the agreement is liquidated after the PIC period AND the targetAccount is solvent
     *   - the rewardAmountReceiver will get the rewardAmount (remaining deposit)
     *   - the targetAccount will pay for the rewardAmount
     * - if the targetAccount is insolvent
     *   - the liquidatorAccount will get the rewardAmount (single deposit)
     *   - the default reward account (governance) will pay for both the rewardAmount and bailoutAmount
     *   - the targetAccount will receive the bailoutAmount
     */
    event AgreementLiquidatedV2(
        address indexed agreementClass,
        bytes32 id,
        address indexed liquidatorAccount,
        address indexed targetAccount,
        address rewardAmountReceiver,
        uint256 rewardAmount,
        int256 targetAccountBalanceDelta,
        bytes liquidationTypeData
    );

    /**************************************************************************
     * Function modifiers for access control and parameter validations
     *
     * While they cannot be explicitly stated in function definitions, they are
     * listed in function definition comments instead for clarity.
     *
     * NOTE: solidity-coverage not supporting it
     *************************************************************************/

     /// @dev The msg.sender must be host contract
     //modifier onlyHost() virtual;

    /// @dev The msg.sender must be a listed agreement.
    //modifier onlyAgreement() virtual;

    /**************************************************************************
     * DEPRECATED
     *************************************************************************/

    /**
     * @dev Agreement liquidation event (DEPRECATED BY AgreementLiquidatedBy)
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     * @param penaltyAccount Account of the agreement to be penalized
     * @param rewardAccount Account that collect the reward
     * @param rewardAmount Amount of liquidation reward
     *
     * @custom:deprecated Use AgreementLiquidatedV2 instead
     */
    event AgreementLiquidated(
        address indexed agreementClass,
        bytes32 id,
        address indexed penaltyAccount,
        address indexed rewardAccount,
        uint256 rewardAmount
    );

    /**
     * @dev System bailout occurred (DEPRECATED BY AgreementLiquidatedBy)
     * @param bailoutAccount Account that bailout the penalty account
     * @param bailoutAmount Amount of account bailout
     *
     * @custom:deprecated Use AgreementLiquidatedV2 instead
     */
    event Bailout(
        address indexed bailoutAccount,
        uint256 bailoutAmount
    );

    /**
     * @dev Agreement liquidation event (DEPRECATED BY AgreementLiquidatedV2)
     * @param liquidatorAccount Account of the agent that performed the liquidation.
     * @param agreementClass Contract address of the agreement
     * @param id Agreement ID
     * @param penaltyAccount Account of the agreement to be penalized
     * @param bondAccount Account that collect the reward or bailout accounts
     * @param rewardAmount Amount of liquidation reward
     * @param bailoutAmount Amount of liquidation bailouot
     *
     * @custom:deprecated Use AgreementLiquidatedV2 instead
     *
     * @custom:note 
     * Reward account rule:
     * - if bailout is equal to 0, then
     *   - the bondAccount will get the rewardAmount,
     *   - the penaltyAccount will pay for the rewardAmount.
     * - if bailout is larger than 0, then
     *   - the liquidatorAccount will get the rewardAmouont,
     *   - the bondAccount will pay for both the rewardAmount and bailoutAmount,
     *   - the penaltyAccount will pay for the rewardAmount while get the bailoutAmount.
     */
    event AgreementLiquidatedBy(
        address liquidatorAccount,
        address indexed agreementClass,
        bytes32 id,
        address indexed penaltyAccount,
        address indexed bondAccount,
        uint256 rewardAmount,
        uint256 bailoutAmount
    );
}

File 51 of 70 : ISuperToken.sol
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

import { ISuperfluidToken } from "./ISuperfluidToken.sol";
import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import { IPoolAdminNFT } from "../agreements/gdav1/IPoolAdminNFT.sol";
import { IPoolMemberNFT } from "../agreements/gdav1/IPoolMemberNFT.sol";

/**
 * @title Super token (Superfluid Token + ERC20 + ERC777) interface
 * @author Superfluid
 */
interface ISuperToken is ISuperfluidToken, IERC20Metadata, IERC777 {

    /**************************************************************************
     * Errors
     *************************************************************************/
    error SUPER_TOKEN_CALLER_IS_NOT_OPERATOR_FOR_HOLDER();       // 0xf7f02227
    error SUPER_TOKEN_NOT_ERC777_TOKENS_RECIPIENT();             // 0xfe737d05
    error SUPER_TOKEN_INFLATIONARY_DEFLATIONARY_NOT_SUPPORTED(); // 0xe3e13698
    error SUPER_TOKEN_NO_UNDERLYING_TOKEN();                     // 0xf79cf656
    error SUPER_TOKEN_ONLY_SELF();                               // 0x7ffa6648
    error SUPER_TOKEN_ONLY_ADMIN();                              // 0x0484acab
    error SUPER_TOKEN_ONLY_GOV_OWNER();                          // 0xd9c7ed08
    error SUPER_TOKEN_APPROVE_FROM_ZERO_ADDRESS();               // 0x81638627
    error SUPER_TOKEN_APPROVE_TO_ZERO_ADDRESS();                 // 0xdf070274
    error SUPER_TOKEN_BURN_FROM_ZERO_ADDRESS();                  // 0xba2ab184
    error SUPER_TOKEN_MINT_TO_ZERO_ADDRESS();                    // 0x0d243157
    error SUPER_TOKEN_TRANSFER_FROM_ZERO_ADDRESS();              // 0xeecd6c9b
    error SUPER_TOKEN_TRANSFER_TO_ZERO_ADDRESS();                // 0xe219bd39
    error SUPER_TOKEN_NFT_PROXY_ADDRESS_CHANGED();               // 0x6bef249d

    /**
     * @dev Initialize the contract
     */
    function initialize(
        IERC20 underlyingToken,
        uint8 underlyingDecimals,
        string calldata n,
        string calldata s
    ) external;

    /**
     * @dev Initialize the contract with an admin
     */
    function initializeWithAdmin(
        IERC20 underlyingToken,
        uint8 underlyingDecimals,
        string calldata n,
        string calldata s,
        address admin
    ) external;

    /**
     * @notice Changes the admin for the SuperToken
     * @dev Only the current admin can call this function
     * if admin is address(0), it is implicitly the host address
     * @param newAdmin New admin address
     */
    function changeAdmin(address newAdmin) external;

    event AdminChanged(address indexed oldAdmin, address indexed newAdmin);

    /**
     * @dev Returns the admin address for the SuperToken
     */
    function getAdmin() external view returns (address admin);

    /**************************************************************************
    * Immutable variables
    *************************************************************************/

    // solhint-disable-next-line func-name-mixedcase
    function POOL_ADMIN_NFT() external view returns (IPoolAdminNFT);
    // solhint-disable-next-line func-name-mixedcase
    function POOL_MEMBER_NFT() external view returns (IPoolMemberNFT);

    /**************************************************************************
    * IERC20Metadata & ERC777
    *************************************************************************/

    /**
     * @dev Returns the name of the token.
     */
    function name() external view override(IERC777, IERC20Metadata) returns (string memory);

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() external view override(IERC777, IERC20Metadata) returns (string memory);

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

    /**************************************************************************
    * ERC20 & ERC777
    *************************************************************************/

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() external view override(IERC777, IERC20) returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by an account (`owner`).
     */
    function balanceOf(address account) external view override(IERC777, IERC20) returns(uint256 balance);

    /**************************************************************************
    * ERC20
    *************************************************************************/

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * @return Returns Success a boolean value indicating whether the operation succeeded.
     *
     * @custom:emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external override(IERC20) 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.
     *
     * @notice This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external override(IERC20) view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * @return Returns Success a boolean value indicating whether the operation succeeded.
     *
     * @custom:note 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
     *
     * @custom:emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external override(IERC20) returns (bool);

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

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * @custom:emits an {Approval} event indicating the updated allowance.
     *
     * @custom:requirements
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) external returns (bool);

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * @custom:emits an {Approval} event indicating the updated allowance.
     *
     * @custom:requirements
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
     function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);

    /**************************************************************************
    * ERC777
    *************************************************************************/

    /**
     * @dev Returns the smallest part of the token that is not divisible. This
     *         means all token operations (creation, movement and destruction) must have
     *         amounts that are a multiple of this number.
     *
     * @custom:note For super token contracts, this value is always 1
     */
    function granularity() external view override(IERC777) returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * @dev If send or receive hooks are registered for the caller and `recipient`,
     *      the corresponding functions will be called with `userData` and empty
     *      `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * @custom:emits a {Sent} event.
     *
     * @custom:requirements
     * - the caller must have at least `amount` tokens.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function send(address recipient, uint256 amount, bytes calldata userData) external override(IERC777);

    /**
     * @dev Destroys `amount` tokens from the caller's account, reducing the
     * total supply and transfers the underlying token to the caller's account.
     *
     * If a send hook is registered for the caller, the corresponding function
     * will be called with `userData` and empty `operatorData`. See {IERC777Sender}.
     *
     * @custom:emits a {Burned} event.
     *
     * @custom:requirements
     * - the caller must have at least `amount` tokens.
     */
    function burn(uint256 amount, bytes calldata userData) external override(IERC777);

    /**
     * @dev Returns true if an account is an operator of `tokenHolder`.
     * Operators can send and burn tokens on behalf of their owners. All
     * accounts are their own operator.
     *
     * See {operatorSend} and {operatorBurn}.
     */
    function isOperatorFor(address operator, address tokenHolder) external override(IERC777) view returns (bool);

    /**
     * @dev Make an account an operator of the caller.
     *
     * See {isOperatorFor}.
     *
     * @custom:emits an {AuthorizedOperator} event.
     *
     * @custom:requirements
     * - `operator` cannot be calling address.
     */
    function authorizeOperator(address operator) external override(IERC777);

    /**
     * @dev Revoke an account's operator status for the caller.
     *
     * See {isOperatorFor} and {defaultOperators}.
     *
     * @custom:emits a {RevokedOperator} event.
     *
     * @custom:requirements
     * - `operator` cannot be calling address.
     */
    function revokeOperator(address operator) external override(IERC777);

    /**
     * @dev Returns the list of default operators. These accounts are operators
     * for all token holders, even if {authorizeOperator} was never called on
     * them.
     *
     * This list is immutable, but individual holders may revoke these via
     * {revokeOperator}, in which case {isOperatorFor} will return false.
     */
    function defaultOperators() external override(IERC777) view returns (address[] memory);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
     * be an operator of `sender`.
     *
     * If send or receive hooks are registered for `sender` and `recipient`,
     * the corresponding functions will be called with `userData` and
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * @custom:emits a {Sent} event.
     *
     * @custom:requirements
     * - `sender` cannot be the zero address.
     * - `sender` must have at least `amount` tokens.
     * - the caller must be an operator for `sender`.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function operatorSend(
        address sender,
        address recipient,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external override(IERC777);

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the total supply.
     * The caller must be an operator of `account`.
     *
     * If a send hook is registered for `account`, the corresponding function
     * will be called with `userData` and `operatorData`. See {IERC777Sender}.
     *
     * @custom:emits a {Burned} event.
     *
     * @custom:requirements
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     * - the caller must be an operator for `account`.
     */
    function operatorBurn(
        address account,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external override(IERC777);

    /**************************************************************************
     * SuperToken custom token functions
     *************************************************************************/

    /**
     * @dev Mint new tokens for the account
     * If `userData` is not empty, the `tokensReceived` hook is invoked according to ERC777 semantics.
     *
     * @custom:modifiers
     *  - onlySelf
     */
    function selfMint(
        address account,
        uint256 amount,
        bytes memory userData
    ) external;

   /**
    * @dev Burn existing tokens for the account
    * If `userData` is not empty, the `tokensToSend` hook is invoked according to ERC777 semantics.
    *
    * @custom:modifiers
    *  - onlySelf
    */
   function selfBurn(
       address account,
       uint256 amount,
       bytes memory userData
   ) external;

   /**
    * @dev Transfer `amount` tokens from the `sender` to `recipient`.
    * If `spender` isn't the same as `sender`, checks if `spender` has allowance to
    * spend tokens of `sender`.
    *
    * @custom:modifiers
    *  - onlySelf
    */
   function selfTransferFrom(
        address sender,
        address spender,
        address recipient,
        uint256 amount
   ) external;

   /**
    * @dev Give `spender`, `amount` allowance to spend the tokens of
    * `account`.
    *
    * @custom:modifiers
    *  - onlySelf
    */
   function selfApproveFor(
        address account,
        address spender,
        uint256 amount
   ) external;

    /**************************************************************************
     * SuperToken extra functions
     *************************************************************************/

    /**
     * @dev Transfer all available balance from `msg.sender` to `recipient`
     */
    function transferAll(address recipient) external;

    /**************************************************************************
     * ERC20 wrapping
     *************************************************************************/

    /**
     * @dev Return the underlying token contract
     * @return tokenAddr Underlying token address
     */
    function getUnderlyingToken() external view returns(address tokenAddr);

    /**
     * @dev Return the underlying token decimals
     * @return underlyingDecimals Underlying token decimals
     */
    function getUnderlyingDecimals() external view returns (uint8 underlyingDecimals);

    /**
     * @dev Return the underlying token conversion rate
     * @param amount Number of tokens to be upgraded (in 18 decimals)
     * @return underlyingAmount The underlying token amount after scaling
     * @return adjustedAmount The super token amount after scaling
     */
    function toUnderlyingAmount(uint256 amount)
        external
        view
        returns (uint256 underlyingAmount, uint256 adjustedAmount);

    /**
     * @dev Upgrade ERC20 to SuperToken.
     * @param amount Number of tokens to be upgraded (in 18 decimals)
     *
     * @custom:note It will use `transferFrom` to get tokens. Before calling this
     * function you should `approve` this contract
     */
    function upgrade(uint256 amount) external;

    /**
     * @dev Upgrade ERC20 to SuperToken and transfer immediately
     * @param to The account to receive upgraded tokens
     * @param amount Number of tokens to be upgraded (in 18 decimals)
     * @param userData User data for the TokensRecipient callback
     *
     * @custom:note It will use `transferFrom` to get tokens. Before calling this
     * function you should `approve` this contract
     *
     * @custom:warning
     * - there is potential of reentrancy IF the "to" account is a registered ERC777 recipient.
     * @custom:requirements
     * - if `userData` is NOT empty AND `to` is a contract, it MUST be a registered ERC777 recipient
     *   otherwise it reverts.
     */
    function upgradeTo(address to, uint256 amount, bytes calldata userData) external;

    /**
     * @dev Token upgrade event
     * @param account Account where tokens are upgraded to
     * @param amount Amount of tokens upgraded (in 18 decimals)
     */
    event TokenUpgraded(
        address indexed account,
        uint256 amount
    );

    /**
     * @dev Downgrade SuperToken to ERC20.
     * @dev It will call transfer to send tokens
     * @param amount Number of tokens to be downgraded
     */
    function downgrade(uint256 amount) external;

    /**
     * @dev Downgrade SuperToken to ERC20 and transfer immediately
     * @param to The account to receive downgraded tokens
     * @param amount Number of tokens to be downgraded (in 18 decimals)
     */
    function downgradeTo(address to, uint256 amount) external;

    /**
     * @dev Token downgrade event
     * @param account Account whose tokens are downgraded
     * @param amount Amount of tokens downgraded
     */
    event TokenDowngraded(
        address indexed account,
        uint256 amount
    );

    /**************************************************************************
    * Batch Operations
    *************************************************************************/

    /**
    * @dev Perform ERC20 approve by host contract.
    * @param account The account owner to be approved.
    * @param spender The spender of account owner's funds.
    * @param amount Number of tokens to be approved.
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationApprove(
        address account,
        address spender,
        uint256 amount
    ) external;

    function operationIncreaseAllowance(
        address account,
        address spender,
        uint256 addedValue
    ) external;

    function operationDecreaseAllowance(
        address account,
        address spender,
        uint256 subtractedValue
    ) external;

    /**
    * @dev Perform ERC20 transferFrom by host contract.
    * @param account The account to spend sender's funds.
    * @param spender The account where the funds is sent from.
    * @param recipient The recipient of the funds.
    * @param amount Number of tokens to be transferred.
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationTransferFrom(
        address account,
        address spender,
        address recipient,
        uint256 amount
    ) external;

    /**
    * @dev Perform ERC777 send by host contract.
    * @param spender The account where the funds is sent from.
    * @param recipient The recipient of the funds.
    * @param amount Number of tokens to be transferred.
    * @param userData Arbitrary user inputted data
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationSend(
        address spender,
        address recipient,
        uint256 amount,
        bytes memory userData
    ) external;

    /**
    * @dev Upgrade ERC20 to SuperToken by host contract.
    * @param account The account to be changed.
    * @param amount Number of tokens to be upgraded (in 18 decimals)
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationUpgrade(address account, uint256 amount) external;

    /**
    * @dev Downgrade ERC20 to SuperToken by host contract.
    * @param account The account to be changed.
    * @param amount Number of tokens to be downgraded (in 18 decimals)
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationDowngrade(address account, uint256 amount) external;

    /**
    * @dev Upgrade ERC20 to SuperToken by host contract and transfer immediately.
    * @param account The account to be changed.
    * @param to The account to receive upgraded tokens
    * @param amount Number of tokens to be upgraded (in 18 decimals)
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationUpgradeTo(address account, address to, uint256 amount) external;

    /**
    * @dev Downgrade ERC20 to SuperToken by host contract and transfer immediately.
    * @param account The account to be changed.
    * @param to The account to receive downgraded tokens
    * @param amount Number of tokens to be downgraded (in 18 decimals)
    *
    * @custom:modifiers
    *  - onlyHost
    */
    function operationDowngradeTo(address account, address to, uint256 amount) external;

    /**
     * @dev Pool Admin NFT proxy created event
     * @param poolAdminNFT pool admin nft address
     */
    event PoolAdminNFTCreated(
        IPoolAdminNFT indexed poolAdminNFT
    );

    /**
     * @dev Pool Member NFT proxy created event
     * @param poolMemberNFT pool member nft address
     */
    event PoolMemberNFTCreated(
        IPoolMemberNFT indexed poolMemberNFT
    );

    /**************************************************************************
    * Function modifiers for access control and parameter validations
    *
    * While they cannot be explicitly stated in function definitions, they are
    * listed in function definition comments instead for clarity.
    *
    * NOTE: solidity-coverage not supporting it
    *************************************************************************/

    /// @dev The msg.sender must be the contract itself
    //modifier onlySelf() virtual

}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ISuperToken } from "./ISuperToken.sol";
/**
 * @title Super token factory interface
 * @author Superfluid
 */
interface ISuperTokenFactory {

    /**************************************************************************
     * Errors
     *************************************************************************/
    error SUPER_TOKEN_FACTORY_ALREADY_EXISTS();                 // 0x91d67972
    error SUPER_TOKEN_FACTORY_DOES_NOT_EXIST();                 // 0x872cac48
    error SUPER_TOKEN_FACTORY_UNINITIALIZED();                  // 0x1b39b9b4
    error SUPER_TOKEN_FACTORY_ONLY_HOST();                      // 0x478b8e83
    error SUPER_TOKEN_FACTORY_NON_UPGRADEABLE_IS_DEPRECATED();  // 0xc4901a43
    error SUPER_TOKEN_FACTORY_ZERO_ADDRESS();                   // 0x305c9e82

    /**
     * @dev Get superfluid host contract address
     */
    function getHost() external view returns(address host);

    /// @dev Initialize the contract
    function initialize() external;

    /**
     * @notice Get the canonical super token logic.
     */
    function getSuperTokenLogic() external view returns (ISuperToken superToken);

    /**
     * @dev Upgradability modes
     */
    enum Upgradability {
        /// Non upgradable super token, `host.updateSuperTokenLogic` will revert
        NON_UPGRADABLE,
        /// Upgradable through `host.updateSuperTokenLogic` operation
        SEMI_UPGRADABLE,
        /// Always using the latest super token logic
        FULL_UPGRADABLE
    }

    /**
     * @notice Create new super token wrapper for the underlying ERC20 token
     * @param underlyingToken Underlying ERC20 token
     * @param underlyingDecimals Underlying token decimals
     * @param upgradability Upgradability mode
     * @param name Super token name
     * @param symbol Super token symbol
     * @param admin Admin address
     * @return superToken The deployed and initialized wrapper super token
     */
    function createERC20Wrapper(
        IERC20Metadata underlyingToken,
        uint8 underlyingDecimals,
        Upgradability upgradability,
        string calldata name,
        string calldata symbol,
        address admin
    )
        external
        returns (ISuperToken superToken);

    /**
     * @notice Create new super token wrapper for the underlying ERC20 token
     * @param underlyingToken Underlying ERC20 token
     * @param underlyingDecimals Underlying token decimals
     * @param upgradability Upgradability mode
     * @param name Super token name
     * @param symbol Super token symbol
     * @return superToken The deployed and initialized wrapper super token
     */
    function createERC20Wrapper(
        IERC20Metadata underlyingToken,
        uint8 underlyingDecimals,
        Upgradability upgradability,
        string calldata name,
        string calldata symbol
    )
        external
        returns (ISuperToken superToken);

    /**
     * @notice Create new super token wrapper for the underlying ERC20 token
     * @param underlyingToken Underlying ERC20 token
     * @param upgradability Upgradability mode
     * @param name Super token name
     * @param symbol Super token symbol
     * @param admin Admin address
     * @return superToken The deployed and initialized wrapper super token
     */
    function createERC20Wrapper(
        IERC20Metadata underlyingToken,
        Upgradability upgradability,
        string calldata name,
        string calldata symbol,
        address admin
    )
        external
        returns (ISuperToken superToken);

    /**
     * @notice Create new super token wrapper for the underlying ERC20 token with extra token info
     * @param underlyingToken Underlying ERC20 token
     * @param upgradability Upgradability mode
     * @param name Super token name
     * @param symbol Super token symbol
     * @return superToken The deployed and initialized wrapper super token
     * NOTE:
     * - It assumes token provide the .decimals() function
     */
    function createERC20Wrapper(
        IERC20Metadata underlyingToken,
        Upgradability upgradability,
        string calldata name,
        string calldata symbol
    )
        external
        returns (ISuperToken superToken);

    /**
     * @notice Creates a wrapper super token AND sets it in the canonical list OR reverts if it already exists
     * @dev salt for create2 is the keccak256 hash of abi.encode(address(_underlyingToken))
     * @param _underlyingToken Underlying ERC20 token
     * @return ISuperToken the created supertoken
     */
    function createCanonicalERC20Wrapper(IERC20Metadata _underlyingToken)
        external
        returns (ISuperToken);

    /**
     * @notice Computes/Retrieves wrapper super token address given the underlying token address
     * @dev We return from our canonical list if it already exists, otherwise we compute it
     * @dev note that this function only computes addresses for SEMI_UPGRADABLE SuperTokens
     * @param _underlyingToken Underlying ERC20 token address
     * @return superTokenAddress Super token address
     * @return isDeployed whether the super token is deployed AND set in the canonical mapping
     */
    function computeCanonicalERC20WrapperAddress(address _underlyingToken)
        external
        view
        returns (address superTokenAddress, bool isDeployed);

    /**
     * @notice Gets the canonical ERC20 wrapper super token address given the underlying token address
     * @dev We return the address if it exists and the zero address otherwise
     * @param _underlyingTokenAddress Underlying ERC20 token address
     * @return superTokenAddress Super token address
     */
    function getCanonicalERC20Wrapper(address _underlyingTokenAddress)
        external
        view
        returns (address superTokenAddress);

    /**
     * @dev Creates a new custom super token
     * @param customSuperTokenProxy address of the custom supertoken proxy
     */
    function initializeCustomSuperToken(
        address customSuperTokenProxy
    )
        external;

    /**
      * @dev Super token logic created event
      * @param tokenLogic Token logic address
      */
    event SuperTokenLogicCreated(ISuperToken indexed tokenLogic);

    /**
      * @dev Super token created event
      * @param token Newly created super token address
      */
    event SuperTokenCreated(ISuperToken indexed token);

    /**
      * @dev Custom super token created event
      * @param token Newly created custom super token address
      */
    event CustomSuperTokenCreated(ISuperToken indexed token);

}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

import { ISuperToken } from "../superfluid/ISuperToken.sol";


/**
 * @title Super ETH (SETH) custom token interface
 * @author Superfluid
 */
interface ISETHCustom {
    // using native token
    function upgradeByETH() external payable;
    function upgradeByETHTo(address to) external payable;
    function downgradeToETH(uint wad) external;
}

/**
 * @title Super ETH (SETH) full interface
 * @author Superfluid
 */
// solhint-disable-next-line no-empty-blocks
interface ISETH is ISETHCustom, ISuperToken {}

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.11;

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

interface IPoolAdminNFT is IPoolNFTBase {
    // PoolAdminNFTData struct storage packing:
    // b = bits
    // WORD 1: | pool   | FREE
    //         | 160b   | 96b
    // WORD 2: | admin  | FREE
    //         | 160b   | 96b
    struct PoolAdminNFTData {
        address pool;
        address admin;
    }

    /// Write Functions ///
    function mint(address pool) external;

    function poolAdminDataByTokenId(uint256 tokenId) external view returns (PoolAdminNFTData memory data);
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.11;

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

interface IPoolMemberNFT is IPoolNFTBase {
    // PoolMemberNFTData struct storage packing:
    // b = bits
    // WORD 1: | pool   | FREE
    //         | 160b   | 96b
    // WORD 2: | member | FREE
    //         | 160b   | 96b
    // WORD 3: | units  | FREE
    //         | 128b   | 128b
    struct PoolMemberNFTData {
        address pool;
        address member;
        uint128 units;
    }

    /// Errors ///

    error POOL_MEMBER_NFT_NO_ZERO_POOL();
    error POOL_MEMBER_NFT_NO_ZERO_MEMBER();
    error POOL_MEMBER_NFT_NO_UNITS();
    error POOL_MEMBER_NFT_HAS_UNITS();

    function onCreate(address pool, address member) external;

    function onUpdate(address pool, address member) external;

    function onDelete(address pool, address member) external;

    /// View Functions ///

    function poolMemberDataByTokenId(uint256 tokenId) external view returns (PoolMemberNFTData memory data);
}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

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

/**
 * @title Super agreement interface
 * @author Superfluid
 */
interface ISuperAgreement {

    /**
     * @dev Get the type of the agreement class
     */
    function agreementType() external view returns (bytes32);

    /**
     * @dev Calculate the real-time balance for the account of this agreement class
     * @param account Account the state belongs to
     * @param time Time used for the calculation
     * @return dynamicBalance Dynamic balance portion of real-time balance of this agreement
     * @return deposit Account deposit amount of this agreement
     * @return owedDeposit Account owed deposit amount of this agreement
     */
    function realtimeBalanceOf(
        ISuperfluidToken token,
        address account,
        uint256 time
    )
        external
        view
        returns (
            int256 dynamicBalance,
            uint256 deposit,
            uint256 owedDeposit
        );

}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

import { ISuperAgreement } from "../superfluid/ISuperAgreement.sol";
import { ISuperfluidToken } from "../superfluid/ISuperfluidToken.sol";

/**
 * @title Constant Flow Agreement interface
 * @author Superfluid
 */
abstract contract IConstantFlowAgreementV1 is ISuperAgreement {

    /**************************************************************************
     * Errors
     *************************************************************************/
    error CFA_ACL_NO_SENDER_CREATE();               // 0x4b993136
    error CFA_ACL_NO_SENDER_UPDATE();               // 0xedfa0d3b
    error CFA_ACL_OPERATOR_NO_CREATE_PERMISSIONS(); // 0xa3eab6ac
    error CFA_ACL_OPERATOR_NO_UPDATE_PERMISSIONS(); // 0xac434b5f
    error CFA_ACL_OPERATOR_NO_DELETE_PERMISSIONS(); // 0xe30f1bff
    error CFA_ACL_FLOW_RATE_ALLOWANCE_EXCEEDED();   // 0xa0645c1f
    error CFA_ACL_UNCLEAN_PERMISSIONS();            // 0x7939d66c
    error CFA_ACL_NO_SENDER_FLOW_OPERATOR();        // 0xb0ed394d
    error CFA_ACL_NO_NEGATIVE_ALLOWANCE();          // 0x86e0377d
    error CFA_FLOW_ALREADY_EXISTS();                // 0x801b6863
    error CFA_FLOW_DOES_NOT_EXIST();                // 0x5a32bf24
    error CFA_INSUFFICIENT_BALANCE();               // 0xea76c9b3
    error CFA_ZERO_ADDRESS_SENDER();                // 0x1ce9b067
    error CFA_ZERO_ADDRESS_RECEIVER();              // 0x78e02b2a
    error CFA_HOOK_OUT_OF_GAS();                    // 0x9f76430b
    error CFA_DEPOSIT_TOO_BIG();                    // 0x752c2b9c
    error CFA_FLOW_RATE_TOO_BIG();                  // 0x0c9c55c1
    error CFA_NON_CRITICAL_SENDER();                // 0xce11b5d1
    error CFA_INVALID_FLOW_RATE();                  // 0x91acad16
    error CFA_NO_SELF_FLOW();                       // 0xa47338ef

    /// @dev ISuperAgreement.agreementType implementation
    function agreementType() external override pure returns (bytes32) {
        return keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1");
    }

    /**
     * @notice Get the maximum flow rate allowed with the deposit
     * @dev The deposit is clipped and rounded down
     * @param deposit Deposit amount used for creating the flow
     * @return flowRate The maximum flow rate
     */
    function getMaximumFlowRateFromDeposit(
        ISuperfluidToken token,
        uint256 deposit)
        external view virtual
        returns (int96 flowRate);

    /**
     * @notice Get the deposit required for creating the flow
     * @dev Calculates the deposit based on the liquidationPeriod and flowRate
     * @param flowRate Flow rate to be tested
     * @return deposit The deposit amount based on flowRate and liquidationPeriod
     * @custom:note
     * - if calculated deposit (flowRate * liquidationPeriod) is less
     *   than the minimum deposit, we use the minimum deposit otherwise
     *   we use the calculated deposit
     */
    function getDepositRequiredForFlowRate(
        ISuperfluidToken token,
        int96 flowRate)
        external view virtual
        returns (uint256 deposit);

    /**
     * @dev Returns whether it is the patrician period based on host.getNow()
     * @param account The account we are interested in
     * @return isCurrentlyPatricianPeriod Whether it is currently the patrician period dictated by governance
     * @return timestamp The value of host.getNow()
     */
    function isPatricianPeriodNow(
        ISuperfluidToken token,
        address account)
        external view virtual
        returns (bool isCurrentlyPatricianPeriod, uint256 timestamp);

    /**
     * @dev Returns whether it is the patrician period based on timestamp
     * @param account The account we are interested in
     * @param timestamp The timestamp we are interested in observing the result of isPatricianPeriod
     * @return bool Whether it is currently the patrician period dictated by governance
     */
    function isPatricianPeriod(
        ISuperfluidToken token,
        address account,
        uint256 timestamp
    )
        public view virtual
        returns (bool);

    /**
     * @dev msgSender from `ctx` updates permissions for the `flowOperator` with `flowRateAllowance`
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param permissions A bitmask representation of the granted permissions
     * @param flowRateAllowance The flow rate allowance the `flowOperator` is granted (only goes down)
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     */
    function updateFlowOperatorPermissions(
        ISuperfluidToken token,
        address flowOperator,
        uint8 permissions,
        int96 flowRateAllowance,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
     * @notice msgSender from `ctx` increases flow rate allowance for the `flowOperator` by `addedFlowRateAllowance`
     * @dev if `addedFlowRateAllowance` is negative, we revert with CFA_ACL_NO_NEGATIVE_ALLOWANCE
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param addedFlowRateAllowance The flow rate allowance delta
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     * @return newCtx The new context bytes
     */
    function increaseFlowRateAllowance(
        ISuperfluidToken token,
        address flowOperator,
        int96 addedFlowRateAllowance,
        bytes calldata ctx
    ) external virtual returns(bytes memory newCtx);

    /**
     * @dev msgSender from `ctx` decreases flow rate allowance for the `flowOperator` by `subtractedFlowRateAllowance`
     * @dev if `subtractedFlowRateAllowance` is negative, we revert with CFA_ACL_NO_NEGATIVE_ALLOWANCE
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param subtractedFlowRateAllowance The flow rate allowance delta
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     * @return newCtx The new context bytes
     */
    function decreaseFlowRateAllowance(
        ISuperfluidToken token,
        address flowOperator,
        int96 subtractedFlowRateAllowance,
        bytes calldata ctx
    ) external virtual returns(bytes memory newCtx);

    /**
     * @dev msgSender from `ctx` increases flow rate allowance for the `flowOperator` by `addedFlowRateAllowance`
     * @dev if `addedFlowRateAllowance` is negative, we revert with CFA_ACL_NO_NEGATIVE_ALLOWANCE
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param permissionsToAdd A bitmask representation of the granted permissions to add as a delta
     * @param addedFlowRateAllowance The flow rate allowance delta
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     * @return newCtx The new context bytes
     */
    function increaseFlowRateAllowanceWithPermissions(
        ISuperfluidToken token,
        address flowOperator,
        uint8 permissionsToAdd,
        int96 addedFlowRateAllowance,
        bytes calldata ctx
    ) external virtual returns(bytes memory newCtx);

    /**
     * @dev msgSender from `ctx` decreases flow rate allowance for the `flowOperator` by `subtractedFlowRateAllowance`
     * @dev if `subtractedFlowRateAllowance` is negative, we revert with CFA_ACL_NO_NEGATIVE_ALLOWANCE
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param permissionsToRemove A bitmask representation of the granted permissions to remove as a delta
     * @param subtractedFlowRateAllowance The flow rate allowance delta
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     * @return newCtx The new context bytes
     */
    function decreaseFlowRateAllowanceWithPermissions(
        ISuperfluidToken token,
        address flowOperator,
        uint8 permissionsToRemove,
        int96 subtractedFlowRateAllowance,
        bytes calldata ctx
    ) external virtual returns(bytes memory newCtx);

    /**
     * @dev msgSender from `ctx` grants `flowOperator` all permissions with flowRateAllowance as type(int96).max
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     */
    function authorizeFlowOperatorWithFullControl(
        ISuperfluidToken token,
        address flowOperator,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

     /**
     * @notice msgSender from `ctx` revokes `flowOperator` create/update/delete permissions
     * @dev `permissions` and `flowRateAllowance` will both be set to 0
     * @param token Super token address
     * @param flowOperator The permission grantee address
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     */
    function revokeFlowOperatorWithFullControl(
        ISuperfluidToken token,
        address flowOperator,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
     * @notice Get the permissions of a flow operator between `sender` and `flowOperator` for `token`
     * @param token Super token address
     * @param sender The permission granter address
     * @param flowOperator The permission grantee address
     * @return flowOperatorId The keccak256 hash of encoded string "flowOperator", sender and flowOperator
     * @return permissions A bitmask representation of the granted permissions
     * @return flowRateAllowance The flow rate allowance the `flowOperator` is granted (only goes down)
     */
    function getFlowOperatorData(
       ISuperfluidToken token,
       address sender,
       address flowOperator
    )
        public view virtual
        returns (
            bytes32 flowOperatorId,
            uint8 permissions,
            int96 flowRateAllowance
        );

    /**
     * @notice Get flow operator using flowOperatorId
     * @param token Super token address
     * @param flowOperatorId The keccak256 hash of encoded string "flowOperator", sender and flowOperator
     * @return permissions A bitmask representation of the granted permissions
     * @return flowRateAllowance The flow rate allowance the `flowOperator` is granted (only goes down)
     */
    function getFlowOperatorDataByID(
       ISuperfluidToken token,
       bytes32 flowOperatorId
    )
        external view virtual
        returns (
            uint8 permissions,
            int96 flowRateAllowance
        );

    /**
     * @notice Create a flow betwen ctx.msgSender and receiver
     * @dev flowId (agreementId) is the keccak256 hash of encoded sender and receiver
     * @param token Super token address
     * @param receiver Flow receiver address
     * @param flowRate New flow rate in amount per second
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * - AgreementCreated
     *   - agreementId - can be used in getFlowByID
     *   - agreementData - abi.encode(address flowSender, address flowReceiver)
     *
     * @custom:note
     * - A deposit is taken as safety margin for the solvency agents
     * - A extra gas fee may be taken to pay for solvency agent liquidations
     */
    function createFlow(
        ISuperfluidToken token,
        address receiver,
        int96 flowRate,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
    * @notice Create a flow between sender and receiver
    * @dev A flow created by an approved flow operator (see above for details on callbacks)
    * @param token Super token address
    * @param sender Flow sender address (has granted permissions)
    * @param receiver Flow receiver address
    * @param flowRate New flow rate in amount per second
    * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
    */
    function createFlowByOperator(
        ISuperfluidToken token,
        address sender,
        address receiver,
        int96 flowRate,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
     * @notice Update the flow rate between ctx.msgSender and receiver
     * @dev flowId (agreementId) is the keccak256 hash of encoded sender and receiver
     * @param token Super token address
     * @param receiver Flow receiver address
     * @param flowRate New flow rate in amount per second
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * - AgreementUpdated
     *   - agreementId - can be used in getFlowByID
     *   - agreementData - abi.encode(address flowSender, address flowReceiver)
     *
     * @custom:note
     * - Only the flow sender may update the flow rate
     * - Even if the flow rate is zero, the flow is not deleted
     * from the system
     * - Deposit amount will be adjusted accordingly
     * - No new gas fee is charged
     */
    function updateFlow(
        ISuperfluidToken token,
        address receiver,
        int96 flowRate,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
    * @notice Update a flow between sender and receiver
    * @dev A flow updated by an approved flow operator (see above for details on callbacks)
    * @param token Super token address
    * @param sender Flow sender address (has granted permissions)
    * @param receiver Flow receiver address
    * @param flowRate New flow rate in amount per second
    * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
    */
    function updateFlowByOperator(
        ISuperfluidToken token,
        address sender,
        address receiver,
        int96 flowRate,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
     * @dev Get the flow data between `sender` and `receiver` of `token`
     * @param token Super token address
     * @param sender Flow sender
     * @param receiver Flow receiver
     * @return timestamp Timestamp of when the flow is updated
     * @return flowRate The flow rate
     * @return deposit The amount of deposit the flow
     * @return owedDeposit The amount of owed deposit of the flow
     */
    function getFlow(
        ISuperfluidToken token,
        address sender,
        address receiver
    )
        external view virtual
        returns (
            uint256 timestamp,
            int96 flowRate,
            uint256 deposit,
            uint256 owedDeposit
        );

    /**
     * @notice Get flow data using agreementId
     * @dev flowId (agreementId) is the keccak256 hash of encoded sender and receiver
     * @param token Super token address
     * @param agreementId The agreement ID
     * @return timestamp Timestamp of when the flow is updated
     * @return flowRate The flow rate
     * @return deposit The deposit amount of the flow
     * @return owedDeposit The owed deposit amount of the flow
     */
    function getFlowByID(
       ISuperfluidToken token,
       bytes32 agreementId
    )
        external view virtual
        returns (
            uint256 timestamp,
            int96 flowRate,
            uint256 deposit,
            uint256 owedDeposit
        );

    /**
     * @dev Get the aggregated flow info of the account
     * @param token Super token address
     * @param account Account for the query
     * @return timestamp Timestamp of when a flow was last updated for account
     * @return flowRate The net flow rate of token for account
     * @return deposit The sum of all deposits for account's flows
     * @return owedDeposit The sum of all owed deposits for account's flows
     */
    function getAccountFlowInfo(
        ISuperfluidToken token,
        address account
    )
        external view virtual
        returns (
            uint256 timestamp,
            int96 flowRate,
            uint256 deposit,
            uint256 owedDeposit);

    /**
     * @dev Get the net flow rate of the account
     * @param token Super token address
     * @param account Account for the query
     * @return flowRate Net flow rate
     */
    function getNetFlow(
        ISuperfluidToken token,
        address account
    )
        external view virtual
        returns (int96 flowRate);

    /**
     * @notice Delete the flow between sender and receiver
     * @dev flowId (agreementId) is the keccak256 hash of encoded sender and receiver
     * @param token Super token address
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     * @param receiver Flow receiver address
     *
     * @custom:callbacks
     * - AgreementTerminated
     *   - agreementId - can be used in getFlowByID
     *   - agreementData - abi.encode(address flowSender, address flowReceiver)
     *
     * @custom:note
     * - Both flow sender and receiver may delete the flow
     * - If Sender account is insolvent or in critical state, a solvency agent may
     *   also terminate the agreement
     * - Gas fee may be returned to the sender
     */
    function deleteFlow(
        ISuperfluidToken token,
        address sender,
        address receiver,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
     * @notice Delete the flow between sender and receiver
     * @dev A flow deleted by an approved flow operator (see above for details on callbacks)
     * @param token Super token address
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     * @param receiver Flow receiver address
     */
    function deleteFlowByOperator(
        ISuperfluidToken token,
        address sender,
        address receiver,
        bytes calldata ctx
    )
        external virtual
        returns(bytes memory newCtx);

    /**
     * @dev Flow operator updated event
     * @param token Super token address
     * @param sender Flow sender address
     * @param flowOperator Flow operator address
     * @param permissions Octo bitmask representation of permissions
     * @param flowRateAllowance The flow rate allowance the `flowOperator` is granted (only goes down)
     */
    event FlowOperatorUpdated(
        ISuperfluidToken indexed token,
        address indexed sender,
        address indexed flowOperator,
        uint8 permissions,
        int96 flowRateAllowance
    );

    /**
     * @dev Flow updated event
     * @param token Super token address
     * @param sender Flow sender address
     * @param receiver Flow recipient address
     * @param flowRate Flow rate in amount per second for this flow
     * @param totalSenderFlowRate Total flow rate in amount per second for the sender
     * @param totalReceiverFlowRate Total flow rate in amount per second for the receiver
     * @param userData The user provided data
     *
     */
    event FlowUpdated(
        ISuperfluidToken indexed token,
        address indexed sender,
        address indexed receiver,
        int96 flowRate,
        int256 totalSenderFlowRate,
        int256 totalReceiverFlowRate,
        bytes userData
    );

    /**
     * @dev Flow updated extension event
     * @param flowOperator Flow operator address - the Context.msgSender
     * @param deposit The deposit amount for the stream
     */
    event FlowUpdatedExtension(
        address indexed flowOperator,
        uint256 deposit
    );
}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

import { ISuperAgreement } from "../superfluid/ISuperAgreement.sol";
import { ISuperfluidToken } from "../superfluid/ISuperfluidToken.sol";

/**
 * @title [DEPRECATED] Instant Distribution Agreement interface
 * @custom:deprecated Use IGeneralDistributionAgreementV1 instead
 * @author Superfluid
 *
 * @notice
 *   - A publisher can create as many as indices as possibly identifiable with `indexId`.
 *     - `indexId` is deliberately limited to 32 bits, to avoid the chance for sha-3 collision.
 *       Despite knowing sha-3 collision is only theoretical.
 *   - A publisher can create a subscription to an index for any subscriber.
 *   - A subscription consists of:
 *     - The index it subscribes to.
 *     - Number of units subscribed.
 *   - An index consists of:
 *     - Current value as `uint128 indexValue`.
 *     - Total units of the approved subscriptions as `uint128 totalUnitsApproved`.
 *     - Total units of the non approved subscription as `uint128 totalUnitsPending`.
 *   - A publisher can update an index with a new value that doesn't decrease.
 *   - A publisher can update a subscription with any number of units.
 *   - A publisher or a subscriber can delete a subscription and reset its units to zero.
 *   - A subscriber must approve the index in order to receive distributions from the publisher
 *     each time the index is updated.
 *     - The amount distributed is $$\Delta{index} * units$$
 *   - Distributions to a non approved subscription stays in the publisher's deposit until:
 *     - the subscriber approves the subscription (side effect),
 *     - the publisher updates the subscription (side effect),
 *     - the subscriber deletes the subscription even if it is never approved (side effect),
 *     - or the subscriber can explicitly claim them.
 */
abstract contract IInstantDistributionAgreementV1 is ISuperAgreement {

    /**************************************************************************
     * Errors
     *************************************************************************/
    error IDA_INDEX_SHOULD_GROW();             // 0xcfdca725
    error IDA_OPERATION_NOT_ALLOWED();         // 0x92da6d17
    error IDA_INDEX_ALREADY_EXISTS();          // 0x5c02a517
    error IDA_INDEX_DOES_NOT_EXIST();          // 0xedeaa63b
    error IDA_SUBSCRIPTION_DOES_NOT_EXIST();   // 0xb6c8c980
    error IDA_SUBSCRIPTION_ALREADY_APPROVED(); // 0x3eb2f849
    error IDA_SUBSCRIPTION_IS_NOT_APPROVED();  // 0x37412573
    error IDA_INSUFFICIENT_BALANCE();          // 0x16e759bb
    error IDA_ZERO_ADDRESS_SUBSCRIBER();       // 0xc90a4674

    /// @dev ISuperAgreement.agreementType implementation
    function agreementType() external override pure returns (bytes32) {
        return keccak256("org.superfluid-finance.agreements.InstantDistributionAgreement.v1");
    }

    /**************************************************************************
     * Index operations
     *************************************************************************/

    /**
     * @dev Create a new index for the publisher
     * @param token Super token address
     * @param indexId Id of the index
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * None
     */
    function createIndex(
        ISuperfluidToken token,
        uint32 indexId,
        bytes calldata ctx)
            external
            virtual
            returns(bytes memory newCtx);
    /**
    * @dev Index created event
    * @param token Super token address
    * @param publisher Index creator and publisher
    * @param indexId The specified indexId of the newly created index
    * @param userData The user provided data
    */
    event IndexCreated(
        ISuperfluidToken indexed token,
        address indexed publisher,
        uint32 indexed indexId,
        bytes userData);

    /**
     * @dev Query the data of a index
     * @param token Super token address
     * @param publisher The publisher of the index
     * @param indexId Id of the index
     * @return exist Does the index exist
     * @return indexValue Value of the current index
     * @return totalUnitsApproved Total units approved for the index
     * @return totalUnitsPending Total units pending approval for the index
     */
    function getIndex(
        ISuperfluidToken token,
        address publisher,
        uint32 indexId)
            external
            view
            virtual
            returns(
                bool exist,
                uint128 indexValue,
                uint128 totalUnitsApproved,
                uint128 totalUnitsPending);

    /**
     * @dev Calculate actual distribution amount
     * @param token Super token address
     * @param publisher The publisher of the index
     * @param indexId Id of the index
     * @param amount The amount of tokens desired to be distributed
     * @return actualAmount The amount to be distributed after ensuring no rounding errors
     * @return newIndexValue The index value given the desired amount of tokens to be distributed
     */
    function calculateDistribution(
       ISuperfluidToken token,
       address publisher,
       uint32 indexId,
       uint256 amount)
           external view
           virtual
           returns(
               uint256 actualAmount,
               uint128 newIndexValue);

    /**
     * @dev Update index value of an index
     * @param token Super token address
     * @param indexId Id of the index
     * @param indexValue Value of the index
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * None
     */
    function updateIndex(
        ISuperfluidToken token,
        uint32 indexId,
        uint128 indexValue,
        bytes calldata ctx)
            external
            virtual
            returns(bytes memory newCtx);
    /**
      * @dev Index updated event
      * @param token Super token address
      * @param publisher Index updater and publisher
      * @param indexId The specified indexId of the updated index
      * @param oldIndexValue The previous index value
      * @param newIndexValue The updated index value
      * @param totalUnitsPending The total units pending when the indexValue was updated
      * @param totalUnitsApproved The total units approved when the indexValue was updated
      * @param userData The user provided data
      */
    event IndexUpdated(
        ISuperfluidToken indexed token,
        address indexed publisher,
        uint32 indexed indexId,
        uint128 oldIndexValue,
        uint128 newIndexValue,
        uint128 totalUnitsPending,
        uint128 totalUnitsApproved,
        bytes userData);

    /**
     * @dev Distribute tokens through the index
     * @param token Super token address
     * @param indexId Id of the index
     * @param amount The amount of tokens desired to be distributed
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:note
     * - This is a convenient version of updateIndex. It adds to the index
     *   a delta that equals to `amount / totalUnits`
     * - The actual amount distributed could be obtained via
     *   `calculateDistribution`. This is due to precision error with index
     *   value and units data range
     *
     * @custom:callbacks
     * None
     */
    function distribute(
        ISuperfluidToken token,
        uint32 indexId,
        uint256 amount,
        bytes calldata ctx)
            external
            virtual
            returns(bytes memory newCtx);


    /**************************************************************************
     * Subscription operations
     *************************************************************************/

    /**
     * @dev Approve the subscription of an index
     * @param token Super token address
     * @param publisher The publisher of the index
     * @param indexId Id of the index
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * - if subscription exist
     *   - AgreementCreated callback to the publisher:
     *      - agreementId is for the subscription
     * - if subscription does not exist
     *   - AgreementUpdated callback to the publisher:
     *      - agreementId is for the subscription
     */
    function approveSubscription(
        ISuperfluidToken token,
        address publisher,
        uint32 indexId,
        bytes calldata ctx)
            external
            virtual
            returns(bytes memory newCtx);
    /**
      * @dev Index subscribed event
      * @param token Super token address
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param subscriber The approved subscriber
      * @param userData The user provided data
      */
    event IndexSubscribed(
        ISuperfluidToken indexed token,
        address indexed publisher,
        uint32 indexed indexId,
        address subscriber,
        bytes userData);

    /**
      * @dev Subscription approved event
      * @param token Super token address
      * @param subscriber The approved subscriber
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param userData The user provided data
      */
    event SubscriptionApproved(
        ISuperfluidToken indexed token,
        address indexed subscriber,
        address publisher,
        uint32 indexId,
        bytes userData);

    /**
    * @notice Revoke the subscription of an index
    * @dev "Unapproves" the subscription and moves approved units to pending
    * @param token Super token address
    * @param publisher The publisher of the index
    * @param indexId Id of the index
    * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
    *
    * @custom:callbacks
    * - AgreementUpdated callback to the publisher:
    *    - agreementId is for the subscription
    */
    function revokeSubscription(
        ISuperfluidToken token,
        address publisher,
        uint32 indexId,
        bytes calldata ctx)
         external
         virtual
         returns(bytes memory newCtx);
    /**
      * @dev Index unsubscribed event
      * @param token Super token address
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param subscriber The unsubscribed subscriber
      * @param userData The user provided data
      */
    event IndexUnsubscribed(
        ISuperfluidToken indexed token,
        address indexed publisher,
        uint32 indexed indexId,
        address subscriber,
        bytes userData);

    /**
      * @dev Subscription approved event
      * @param token Super token address
      * @param subscriber The approved subscriber
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param userData The user provided data
      */
    event SubscriptionRevoked(
        ISuperfluidToken indexed token,
        address indexed subscriber,
        address publisher,
        uint32 indexId,
        bytes userData);

    /**
     * @dev Update the nuber of units of a subscription
     * @param token Super token address
     * @param indexId Id of the index
     * @param subscriber The subscriber of the index
     * @param units Number of units of the subscription
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * - if subscription exist
     *   - AgreementCreated callback to the subscriber:
     *      - agreementId is for the subscription
     * - if subscription does not exist
     *   - AgreementUpdated callback to the subscriber:
     *      - agreementId is for the subscription
     */
    function updateSubscription(
        ISuperfluidToken token,
        uint32 indexId,
        address subscriber,
        uint128 units,
        bytes calldata ctx)
            external
            virtual
            returns(bytes memory newCtx);

    /**
      * @dev Index units updated event
      * @param token Super token address
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param subscriber The subscriber units updated
      * @param units The new units amount
      * @param userData The user provided data
      */
    event IndexUnitsUpdated(
        ISuperfluidToken indexed token,
        address indexed publisher,
        uint32 indexed indexId,
        address subscriber,
        uint128 units,
        bytes userData);

    /**
      * @dev Subscription units updated event
      * @param token Super token address
      * @param subscriber The subscriber units updated
      * @param indexId The specified indexId
      * @param publisher Index publisher
      * @param units The new units amount
      * @param userData The user provided data
      */
    event SubscriptionUnitsUpdated(
        ISuperfluidToken indexed token,
        address indexed subscriber,
        address publisher,
        uint32 indexId,
        uint128 units,
        bytes userData);

    /**
     * @dev Get data of a subscription
     * @param token Super token address
     * @param publisher The publisher of the index
     * @param indexId Id of the index
     * @param subscriber The subscriber of the index
     * @return exist Does the subscription exist?
     * @return approved Is the subscription approved?
     * @return units Units of the suscription
     * @return pendingDistribution Pending amount of tokens to be distributed for unapproved subscription
     */
    function getSubscription(
        ISuperfluidToken token,
        address publisher,
        uint32 indexId,
        address subscriber)
            external
            view
            virtual
            returns(
                bool exist,
                bool approved,
                uint128 units,
                uint256 pendingDistribution
            );

    /**
     * @notice Get data of a subscription by agreement ID
     * @dev indexId (agreementId) is the keccak256 hash of encodePacked("publisher", publisher, indexId)
     * @param token Super token address
     * @param agreementId The agreement ID
     * @return publisher The publisher of the index
     * @return indexId Id of the index
     * @return approved Is the subscription approved?
     * @return units Units of the suscription
     * @return pendingDistribution Pending amount of tokens to be distributed for unapproved subscription
     */
    function getSubscriptionByID(
        ISuperfluidToken token,
        bytes32 agreementId)
            external
            view
            virtual
            returns(
                address publisher,
                uint32 indexId,
                bool approved,
                uint128 units,
                uint256 pendingDistribution
            );

    /**
     * @dev List subscriptions of an user
     * @param token Super token address
     * @param subscriber The subscriber's address
     * @return publishers Publishers of the subcriptions
     * @return indexIds Indexes of the subscriptions
     * @return unitsList Units of the subscriptions
     */
    function listSubscriptions(
        ISuperfluidToken token,
        address subscriber)
            external
            view
            virtual
            returns(
                address[] memory publishers,
                uint32[] memory indexIds,
                uint128[] memory unitsList);

    /**
     * @dev Delete the subscription of an user
     * @param token Super token address
     * @param publisher The publisher of the index
     * @param indexId Id of the index
     * @param subscriber The subscriber's address
     * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
     *
     * @custom:callbacks
     * - if the subscriber called it
     *   - AgreementTerminated callback to the publsiher:
     *      - agreementId is for the subscription
     * - if the publisher called it
     *   - AgreementTerminated callback to the subscriber:
     *      - agreementId is for the subscription
     */
    function deleteSubscription(
        ISuperfluidToken token,
        address publisher,
        uint32 indexId,
        address subscriber,
        bytes calldata ctx)
            external
            virtual
            returns(bytes memory newCtx);

    /**
    * @dev Claim pending distributions
    * @param token Super token address
    * @param publisher The publisher of the index
    * @param indexId Id of the index
    * @param subscriber The subscriber's address
    * @param ctx Context bytes (see ISuperfluid.sol for Context struct)
    *
    * @custom:note The subscription should not be approved yet
    *
    * @custom:callbacks
    * - AgreementUpdated callback to the publisher:
    *    - agreementId is for the subscription
    */
    function claim(
        ISuperfluidToken token,
        address publisher,
        uint32 indexId,
        address subscriber,
        bytes calldata ctx)
        external
        virtual
        returns(bytes memory newCtx);

    /**
      * @dev Index distribution claimed event
      * @param token Super token address
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param subscriber The subscriber units updated
      * @param amount The pending amount claimed
      */
    event IndexDistributionClaimed(
        ISuperfluidToken indexed token,
        address indexed publisher,
        uint32 indexed indexId,
        address subscriber,
        uint256 amount);

    /**
      * @dev Subscription distribution claimed event
      * @param token Super token address
      * @param subscriber The subscriber units updated
      * @param publisher Index publisher
      * @param indexId The specified indexId
      * @param amount The pending amount claimed
      */
    event SubscriptionDistributionClaimed(
        ISuperfluidToken indexed token,
        address indexed subscriber,
        address publisher,
        uint32 indexId,
        uint256 amount);

}

// SPDX-License-Identifier: AGPLv3
pragma solidity >=0.8.4;

import { ISuperAgreement } from "../../superfluid/ISuperAgreement.sol";
import { ISuperfluidToken } from "../../superfluid/ISuperfluidToken.sol";
import { ISuperfluidPool } from "../../agreements/gdav1/ISuperfluidPool.sol";

struct PoolConfig {
    /// @dev if true, the pool members can transfer their owned units
    /// else, only the pool admin can manipulate the units for pool members
    bool transferabilityForUnitsOwner;
    /// @dev if true, anyone can execute distributions via the pool
    /// else, only the pool admin can execute distributions via the pool
    bool distributionFromAnyAddress;
}

struct PoolERC20Metadata {
    string name;
    string symbol;
    uint8 decimals;
}

/**
 * @title General Distribution Agreement interface
 * @author Superfluid
 */
abstract contract IGeneralDistributionAgreementV1 is ISuperAgreement {

    // Custom Errors
    error GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();          // 0xf67d263e
    error GDA_DISTRIBUTE_FROM_ANY_ADDRESS_NOT_ALLOWED();    // 0x7761a5e5
    error GDA_FLOW_DOES_NOT_EXIST();                        // 0x29f4697e
    error GDA_NON_CRITICAL_SENDER();                        // 0x666f381d
    error GDA_INSUFFICIENT_BALANCE();                       // 0x33115c3f
    error GDA_NO_NEGATIVE_FLOW_RATE();                      // 0x15f25663
    error GDA_ADMIN_CANNOT_BE_POOL();                       // 0x9ab88a26
    error GDA_NOT_POOL_ADMIN();                             // 0x3a87e565
    error GDA_NO_ZERO_ADDRESS_ADMIN();                      // 0x82c5d837
    error GDA_ONLY_SUPER_TOKEN_POOL();                      // 0x90028c37


    // Events
    event InstantDistributionUpdated(
        ISuperfluidToken indexed token,
        ISuperfluidPool indexed pool,
        address indexed distributor,
        address operator,
        uint256 requestedAmount,
        uint256 actualAmount,
        bytes userData
    );

    event FlowDistributionUpdated(
        ISuperfluidToken indexed token,
        ISuperfluidPool indexed pool,
        address indexed distributor,
        // operator's have permission to liquidate critical flows
        // on behalf of others
        address operator,
        int96 oldFlowRate,
        int96 newDistributorToPoolFlowRate,
        int96 newTotalDistributionFlowRate,
        address adjustmentFlowRecipient,
        int96 adjustmentFlowRate,
        bytes userData
    );

    event PoolCreated(ISuperfluidToken indexed token, address indexed admin, ISuperfluidPool pool);

    event PoolConnectionUpdated(
        ISuperfluidToken indexed token,
        ISuperfluidPool indexed pool,
        address indexed account,
        bool connected,
        bytes userData
    );

    event BufferAdjusted(
        ISuperfluidToken indexed token,
        ISuperfluidPool indexed pool,
        address indexed from,
        int256 bufferDelta,
        uint256 newBufferAmount,
        uint256 totalBufferAmount
    );

    /// @dev ISuperAgreement.agreementType implementation
    function agreementType() external pure override returns (bytes32) {
        return keccak256("org.superfluid-finance.agreements.GeneralDistributionAgreement.v1");
    }

    /// @dev Gets the GDA net flow rate of `account` for `token`.
    /// @param token The token address
    /// @param account The account address
    /// @return net flow rate
    function getNetFlow(ISuperfluidToken token, address account) external view virtual returns (int96);

    /// @notice Gets the GDA flow rate of `from` to `to` for `token`.
    /// @dev This is primarily used to get the flow distribution flow rate from a distributor to a pool or the
    /// adjustment flow rate of a pool.
    /// @param token The token address
    /// @param from The sender address
    /// @param to The receiver address (the pool)
    /// @return flow rate
    function getFlowRate(ISuperfluidToken token, address from, ISuperfluidPool to)
        external
        view
        virtual
        returns (int96);

    /// @dev Gets the GDA flow data between `from` and `to` of `token`
    /// @param token The token address
    /// @param from The sender address
    /// @param to The receiver address
    /// @return lastUpdated The timestamp of when the flow was last updated
    /// @return flowRate The flow rate
    /// @return deposit The amount of deposit the flow
    function getFlow(ISuperfluidToken token, address from, ISuperfluidPool to)
        external
        view
        virtual
        returns (uint256 lastUpdated, int96 flowRate, uint256 deposit);

    /// @dev Gets the aggregated GDA flow info of `account` for `token`
    /// @param token The token address
    /// @param account The account address
    /// @return timestamp The timestamp of when the flow was last updated for account
    /// @return flowRate The net flow rate of token for account
    /// @return deposit The sum of all deposits for account's flows
    function getAccountFlowInfo(ISuperfluidToken token, address account)
        external
        view
        virtual
        returns (uint256 timestamp, int96 flowRate, uint256 deposit);

    /// @notice Executes an optimistic estimation of what the actual flow distribution flow rate may be.
    /// The actual flow distribution flow rate is the flow rate that will be sent from `from`.
    /// NOTE: this is only precise in an atomic transaction. DO NOT rely on this if querying off-chain.
    /// @dev The difference between the requested flow rate and the actual flow rate is the adjustment flow rate,
    /// this adjustment flow rate goes to the pool admin.
    /// @param token The token address
    /// @param from The sender address
    /// @param to The pool address
    /// @param requestedFlowRate The requested flow rate
    /// @return actualFlowRate and totalDistributionFlowRate
    function estimateFlowDistributionActualFlowRate(
        ISuperfluidToken token,
        address from,
        ISuperfluidPool to,
        int96 requestedFlowRate
    ) external view virtual returns (int96 actualFlowRate, int96 totalDistributionFlowRate);

    /// @notice Executes an optimistic estimation of what the actual amount distributed may be.
    /// The actual amount distributed is the amount that will be sent from `from`.
    /// NOTE: this is only precise in an atomic transaction. DO NOT rely on this if querying off-chain.
    /// @dev The difference between the requested amount and the actual amount is the adjustment amount.
    /// @param token The token address
    /// @param from The sender address
    /// @param to The pool address
    /// @param requestedAmount The requested amount
    /// @return actualAmount
    function estimateDistributionActualAmount(
        ISuperfluidToken token,
        address from,
        ISuperfluidPool to,
        uint256 requestedAmount
    ) external view virtual returns (uint256 actualAmount);

    /// @notice Gets the adjustment flow rate of `pool` for `token`.
    /// @param pool The pool address
    /// @return adjustment flow rate
    function getPoolAdjustmentFlowRate(address pool) external view virtual returns (int96);

    ////////////////////////////////////////////////////////////////////////////////
    // Pool Operations
    ////////////////////////////////////////////////////////////////////////////////

    /// @notice Creates a new pool for `token` where the admin is `admin`.
    /// @param token The token address
    /// @param admin The admin of the pool
    /// @param poolConfig The pool configuration (see PoolConfig struct)
    function createPool(ISuperfluidToken token, address admin, PoolConfig memory poolConfig)
        external
        virtual
        returns (ISuperfluidPool pool);

    /// @notice Creates a new pool for `token` with custom ERC20 metadata.
    /// @param token The token address
    /// @param admin The admin of the pool
    /// @param poolConfig The pool configuration (see PoolConfig struct)
    /// @param poolERC20Metadata The pool ERC20 metadata (see PoolERC20Metadata struct)
    /// @return pool The pool address
    function createPoolWithCustomERC20Metadata(
        ISuperfluidToken token,
        address admin,
        PoolConfig memory poolConfig,
        PoolERC20Metadata memory poolERC20Metadata
    ) external virtual returns (ISuperfluidPool pool);

    function updateMemberUnits(ISuperfluidPool pool, address memberAddress, uint128 newUnits, bytes calldata ctx)
        external
        virtual
        returns (bytes memory newCtx);

    function claimAll(ISuperfluidPool pool, address memberAddress, bytes calldata ctx)
        external
        virtual
        returns (bytes memory newCtx);

    /// @notice Connects `msg.sender` to `pool`.
    /// @dev This is used to connect a pool to the GDA.
    /// @param pool The pool address
    /// @param ctx Context bytes (see ISuperfluid.sol for Context struct)
    /// @return newCtx the new context bytes
    function connectPool(ISuperfluidPool pool, bytes calldata ctx) external virtual returns (bytes memory newCtx);

    /// @notice Disconnects `msg.sender` from `pool`.
    /// @dev This is used to disconnect a pool from the GDA.
    /// @param pool The pool address
    /// @param ctx Context bytes (see ISuperfluidPoolAdmin for Context struct)
    /// @return newCtx the new context bytes
    function disconnectPool(ISuperfluidPool pool, bytes calldata ctx) external virtual returns (bytes memory newCtx);

    /// @notice Checks whether `account` is a pool.
    /// @param token The token address
    /// @param account The account address
    /// @return true if `account` is a pool
    function isPool(ISuperfluidToken token, address account) external view virtual returns (bool);

    /// Check if an address is connected to the pool
    function isMemberConnected(ISuperfluidPool pool, address memberAddr) external view virtual returns (bool);

    /// Get pool adjustment flow information: (recipient, flowHash, flowRate)
    function getPoolAdjustmentFlowInfo(ISuperfluidPool pool) external view virtual returns (address, bytes32, int96);

    ////////////////////////////////////////////////////////////////////////////////
    // Agreement Operations
    ////////////////////////////////////////////////////////////////////////////////

    /// @notice Tries to distribute `requestedAmount` of `token` from `from` to `pool`.
    /// @dev NOTE: The actual amount distributed may differ.
    /// @param token The token address
    /// @param from The sender address
    /// @param pool The pool address
    /// @param requestedAmount The requested amount
    /// @param ctx Context bytes (see ISuperfluidPool for Context struct)
    /// @return newCtx the new context bytes
    function distribute(
        ISuperfluidToken token,
        address from,
        ISuperfluidPool pool,
        uint256 requestedAmount,
        bytes calldata ctx
    ) external virtual returns (bytes memory newCtx);

    /// @notice Tries to distributeFlow `requestedFlowRate` of `token` from `from` to `pool`.
    /// @dev NOTE: The actual distribution flow rate may differ.
    /// @param token The token address
    /// @param from The sender address
    /// @param pool The pool address
    /// @param requestedFlowRate The requested flow rate
    /// @param ctx Context bytes (see ISuperfluidPool for Context struct)
    /// @return newCtx the new context bytes
    function distributeFlow(
        ISuperfluidToken token,
        address from,
        ISuperfluidPool pool,
        int96 requestedFlowRate,
        bytes calldata ctx
    ) external virtual returns (bytes memory newCtx);

    ////////////////////////////////////////////////////////////////////////////////
    // Solvency Functions
    ////////////////////////////////////////////////////////////////////////////////

    /**
     * @dev Returns whether it is the patrician period based on host.getNow()
     * @param account The account we are interested in
     * @return isCurrentlyPatricianPeriod Whether it is currently the patrician period dictated by governance
     * @return timestamp The value of host.getNow()
     */
    function isPatricianPeriodNow(ISuperfluidToken token, address account)
        external
        view
        virtual
        returns (bool isCurrentlyPatricianPeriod, uint256 timestamp);

    /**
     * @dev Returns whether it is the patrician period based on timestamp
     * @param account The account we are interested in
     * @param timestamp The timestamp we are interested in observing the result of isPatricianPeriod
     * @return bool Whether it is currently the patrician period dictated by governance
     */
    function isPatricianPeriod(ISuperfluidToken token, address account, uint256 timestamp)
        public
        view
        virtual
        returns (bool);
}

// SPDX-License-Identifier: AGPLv3
pragma solidity >=0.8.4;

import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ISuperfluidToken } from "../../superfluid/ISuperfluidToken.sol";

/**
 * @dev The interface for any super token pool regardless of the distribution schemes.
 */
interface ISuperfluidPool is IERC20, IERC20Metadata {
    // Custom Errors

    error SUPERFLUID_POOL_INVALID_TIME();               // 0x83c35016
    error SUPERFLUID_POOL_NO_POOL_MEMBERS();            // 0xe10f405a
    error SUPERFLUID_POOL_NO_ZERO_ADDRESS();            // 0x54eb6ee6
    error SUPERFLUID_POOL_NOT_POOL_ADMIN_OR_GDA();      // 0x1c5fbdcb
    error SUPERFLUID_POOL_NOT_GDA();                    // 0xfcbe3f9e
    error SUPERFLUID_POOL_TRANSFER_UNITS_NOT_ALLOWED(); // 0x2285efba
    error SUPERFLUID_POOL_SELF_TRANSFER_NOT_ALLOWED();  // 0xceddc0be

    // Events
    event MemberUnitsUpdated(
        ISuperfluidToken indexed token, address indexed member, uint128 oldUnits, uint128 newUnits
    );
    event DistributionClaimed(
        ISuperfluidToken indexed token, address indexed member, int256 claimedAmount, int256 totalClaimed
    );

    /// @notice A boolean indicating whether pool members can transfer their units
    function transferabilityForUnitsOwner() external view returns (bool);

    /// @notice A boolean indicating whether addresses other than the pool admin can distribute via the pool
    function distributionFromAnyAddress() external view returns (bool);

    /// @notice The pool admin
    /// @dev The admin is the creator of the pool and has permissions to update member units
    /// and is the recipient of the adjustment flow rate
    function admin() external view returns (address);

    /// @notice The SuperToken for the pool
    function superToken() external view returns (ISuperfluidToken);

    /// @notice The total units of the pool
    function getTotalUnits() external view returns (uint128);

    /// @notice The total number of units of connected members
    function getTotalConnectedUnits() external view returns (uint128);

    /// @notice The total number of units of disconnected members
    function getTotalDisconnectedUnits() external view returns (uint128);

    /// @notice The total number of units for `memberAddr`
    /// @param memberAddr The address of the member
    function getUnits(address memberAddr) external view returns (uint128);

    /// @notice The total flow rate of the pool
    function getTotalFlowRate() external view returns (int96);

    /// @notice The flow rate of the connected members
    function getTotalConnectedFlowRate() external view returns (int96);

    /// @notice The flow rate of the disconnected members
    function getTotalDisconnectedFlowRate() external view returns (int96);

    /// @notice The balance of all the disconnected members at `time`
    /// @param time The time to query
    function getDisconnectedBalance(uint32 time) external view returns (int256 balance);

    /// @notice The total amount received by `memberAddr` in the pool
    /// @param memberAddr The address of the member
    /// @return totalAmountReceived The total amount received by the member
    function getTotalAmountReceivedByMember(address memberAddr) external view returns (uint256 totalAmountReceived);

    /// @notice The flow rate a member is receiving from the pool
    /// @param memberAddr The address of the member
    function getMemberFlowRate(address memberAddr) external view returns (int96);

    /// @notice The claimable balance for `memberAddr` at `time` in the pool
    /// @param memberAddr The address of the member
    /// @param time The time to query
    function getClaimable(address memberAddr, uint32 time) external view returns (int256);

    /// @notice The claimable balance for `memberAddr` at `block.timestamp` in the pool
    /// @param memberAddr The address of the member
    function getClaimableNow(address memberAddr) external view returns (int256 claimableBalance, uint256 timestamp);

    /// @notice Sets `memberAddr` ownedUnits to `newUnits`
    /// @param memberAddr The address of the member
    /// @param newUnits The new units for the member
    function updateMemberUnits(address memberAddr, uint128 newUnits) external returns (bool);

    /// @notice Claims the claimable balance for `memberAddr` at `block.timestamp`
    /// @param memberAddr The address of the member
    function claimAll(address memberAddr) external returns (bool);

    /// @notice Claims the claimable balance for `msg.sender` at `block.timestamp`
    function claimAll() external returns (bool);

    /// @notice Increases the allowance of `spender` by `addedValue`
    /// @param spender The address of the spender
    /// @param addedValue The amount to increase the allowance by
    /// @return true if successful
    function increaseAllowance(address spender, uint256 addedValue) external returns (bool);

    /// @notice Decreases the allowance of `spender` by `subtractedValue`
    /// @param spender The address of the spender
    /// @param subtractedValue The amount to decrease the allowance by
    /// @return true if successful
    function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

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

/**
 * @title SuperApp interface
 * @author Superfluid
 * @dev Be aware of the app being jailed, when the word permitted is used.
 */
interface ISuperApp {

    /**
     * @dev Callback before a new agreement is created.
     * @param superToken The super token used for the agreement.
     * @param agreementClass The agreement class address.
     * @param agreementId The agreementId
     * @param agreementData The agreement data (non-compressed)
     * @param ctx The context data.
     * @return cbdata A free format in memory data the app can use to pass
     *          arbitary information to the after-hook callback.
     *
     * @custom:note 
     * - It will be invoked with `staticcall`, no state changes are permitted.
     * - Only revert with a "reason" is permitted.
     */
    function beforeAgreementCreated(
        ISuperToken superToken,
        address agreementClass,
        bytes32 agreementId,
        bytes calldata agreementData,
        bytes calldata ctx
    )
        external
        view
        returns (bytes memory cbdata);

    /**
     * @dev Callback after a new agreement is created.
     * @param superToken The super token used for the agreement.
     * @param agreementClass The agreement class address.
     * @param agreementId The agreementId
     * @param agreementData The agreement data (non-compressed)
     * @param cbdata The data returned from the before-hook callback.
     * @param ctx The context data.
     * @return newCtx The current context of the transaction.
     *
     * @custom:note 
     * - State changes is permitted.
     * - Only revert with a "reason" is permitted.
     */
    function afterAgreementCreated(
        ISuperToken superToken,
        address agreementClass,
        bytes32 agreementId,
        bytes calldata agreementData,
        bytes calldata cbdata,
        bytes calldata ctx
    )
        external
        returns (bytes memory newCtx);

    /**
     * @dev Callback before a new agreement is updated.
     * @param superToken The super token used for the agreement.
     * @param agreementClass The agreement class address.
     * @param agreementId The agreementId
     * @param agreementData The agreement data (non-compressed)
     * @param ctx The context data.
     * @return cbdata A free format in memory data the app can use to pass
     *          arbitary information to the after-hook callback.
     *
     * @custom:note 
     * - It will be invoked with `staticcall`, no state changes are permitted.
     * - Only revert with a "reason" is permitted.
     */
    function beforeAgreementUpdated(
        ISuperToken superToken,
        address agreementClass,
        bytes32 agreementId,
        bytes calldata agreementData,
        bytes calldata ctx
    )
        external
        view
        returns (bytes memory cbdata);


    /**
    * @dev Callback after a new agreement is updated.
    * @param superToken The super token used for the agreement.
    * @param agreementClass The agreement class address.
    * @param agreementId The agreementId
    * @param agreementData The agreement data (non-compressed)
    * @param cbdata The data returned from the before-hook callback.
    * @param ctx The context data.
    * @return newCtx The current context of the transaction.
    *
    * @custom:note 
    * - State changes is permitted.
    * - Only revert with a "reason" is permitted.
    */
    function afterAgreementUpdated(
        ISuperToken superToken,
        address agreementClass,
        bytes32 agreementId,
        bytes calldata agreementData,
        bytes calldata cbdata,
        bytes calldata ctx
    )
        external
        returns (bytes memory newCtx);

    /**
    * @dev Callback before a new agreement is terminated.
    * @param superToken The super token used for the agreement.
    * @param agreementClass The agreement class address.
    * @param agreementId The agreementId
    * @param agreementData The agreement data (non-compressed)
    * @param ctx The context data.
    * @return cbdata A free format in memory data the app can use to pass arbitary information to
    *         the after-hook callback.
    *
    * @custom:note 
    * - It will be invoked with `staticcall`, no state changes are permitted.
    * - Revert is not permitted.
    */
    function beforeAgreementTerminated(
        ISuperToken superToken,
        address agreementClass,
        bytes32 agreementId,
        bytes calldata agreementData,
        bytes calldata ctx
    )
        external
        view
        returns (bytes memory cbdata);

    /**
    * @dev Callback after a new agreement is terminated.
    * @param superToken The super token used for the agreement.
    * @param agreementClass The agreement class address.
    * @param agreementId The agreementId
    * @param agreementData The agreement data (non-compressed)
    * @param cbdata The data returned from the before-hook callback.
    * @param ctx The context data.
    * @return newCtx The current context of the transaction.
    *
    * @custom:note 
    * - State changes is permitted.
    * - Revert is not permitted.
    */
    function afterAgreementTerminated(
        ISuperToken superToken,
        address agreementClass,
        bytes32 agreementId,
        bytes calldata agreementData,
        bytes calldata cbdata,
        bytes calldata ctx
    )
        external
        returns (bytes memory newCtx);
}

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.11;

import { ISuperfluid } from "./ISuperfluid.sol";
import { ISuperToken } from "./ISuperToken.sol";
import { ISuperfluidToken } from "./ISuperfluidToken.sol";

/**
 * @title Superfluid governance interface
 * @author Superfluid
 */
interface ISuperfluidGovernance {

    /**************************************************************************
     * Errors
     *************************************************************************/
    error SF_GOV_INVALID_LIQUIDATION_OR_PATRICIAN_PERIOD(); // 0xe171980a
    error SF_GOV_MUST_BE_CONTRACT();                        // 0x80dddd73

    /**
     * @dev Replace the current governance with a new governance
     */
    function replaceGovernance(
        ISuperfluid host,
        address newGov) external;

    /**
     * @dev Register a new agreement class
     */
    function registerAgreementClass(
        ISuperfluid host,
        address agreementClass) external;

    /**
     * @dev Update logics of the contracts
     *
     * @custom:note
     * - Because they might have inter-dependencies, it is good to have one single function to update them all
     */
    function updateContracts(
        ISuperfluid host,
        address hostNewLogic,
        address[] calldata agreementClassNewLogics,
        address superTokenFactoryNewLogic,
        address beaconNewLogic
    ) external;

    /**
     * @dev Update supertoken logic contract to the latest that is managed by the super token factory
     */
    function batchUpdateSuperTokenLogic(
        ISuperfluid host,
        ISuperToken[] calldata tokens) external;

    /**
     * @dev Update supertoken logic contract to the provided logic contracts.
     *      Note that this is an overloaded version taking an additional argument `tokenLogics`
     */
    function batchUpdateSuperTokenLogic(
        ISuperfluid host,
        ISuperToken[] calldata tokens,
        address[] calldata tokenLogics) external;

    /**
     * @dev Set configuration as address value
     */
    function setConfig(
        ISuperfluid host,
        ISuperfluidToken superToken,
        bytes32 key,
        address value
    ) external;

    /**
     * @dev Set configuration as uint256 value
     */
    function setConfig(
        ISuperfluid host,
        ISuperfluidToken superToken,
        bytes32 key,
        uint256 value
    ) external;

    /**
     * @dev Clear configuration
     */
    function clearConfig(
        ISuperfluid host,
        ISuperfluidToken superToken,
        bytes32 key
    ) external;

    /**
     * @dev Get configuration as address value
     */
    function getConfigAsAddress(
        ISuperfluid host,
        ISuperfluidToken superToken,
        bytes32 key) external view returns (address value);

    /**
     * @dev Get configuration as uint256 value
     */
    function getConfigAsUint256(
        ISuperfluid host,
        ISuperfluidToken superToken,
        bytes32 key) external view returns (uint256 value);

}

// 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 64 of 70 : SVG.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import {utils, LibString} from "./Utils.sol";

/// @notice Core SVG utility library which helps us construct onchain SVG's with a simple, web-like API.
/// @author Modified from (https://github.com/w1nt3r-eth/hot-chain-svg/blob/main/contracts/SVG.sol) by w1nt3r-eth.

library svg {
    /* GLOBAL CONSTANTS */
    string internal constant _SVG = 'xmlns="http://www.w3.org/2000/svg"';
    string internal constant _HTML = 'xmlns="http://www.w3.org/1999/xhtml"';
    string internal constant _XMLNS = "http://www.w3.org/2000/xmlns/ ";
    string internal constant _XLINK = "http://www.w3.org/1999/xlink ";

    /* MAIN ELEMENTS */
    function g(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("g", _props, _children);
    }

    function _svg(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("svg", string.concat(_SVG, " ", _props), _children);
    }

    function style(string memory _title, string memory _props) internal pure returns (string memory) {
        return el("style", string.concat(".", _title, " ", _props));
    }

    function path(string memory _d) internal pure returns (string memory) {
        return el("path", prop("d", _d, true));
    }

    function path(string memory _d, string memory _props) internal pure returns (string memory) {
        return el("path", string.concat(prop("d", _d), _props));
    }

    function path(string memory _d, string memory _props, string memory _children)
        internal
        pure
        returns (string memory)
    {
        return el("path", string.concat(prop("d", _d), _props), _children);
    }

    function text(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("text", _props, _children);
    }

    function line(string memory _props) internal pure returns (string memory) {
        return el("line", _props);
    }

    function line(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("line", _props, _children);
    }

    function circle(string memory _props) internal pure returns (string memory) {
        return el("circle", _props);
    }

    function circle(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("circle", _props, _children);
    }

    function circle(string memory cx, string memory cy, string memory r) internal pure returns (string memory) {
        return el("circle", string.concat(prop("cx", cx), prop("cy", cy), prop("r", r, true)));
    }

    function circle(string memory cx, string memory cy, string memory r, string memory _children)
        internal
        pure
        returns (string memory)
    {
        return el("circle", string.concat(prop("cx", cx), prop("cy", cy), prop("r", r, true)), _children);
    }

    function circle(string memory cx, string memory cy, string memory r, string memory _props, string memory _children)
        internal
        pure
        returns (string memory)
    {
        return el("circle", string.concat(prop("cx", cx), prop("cy", cy), prop("r", r), _props), _children);
    }

    function ellipse(string memory _props) internal pure returns (string memory) {
        return el("ellipse", _props);
    }

    function ellipse(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("ellipse", _props, _children);
    }

    function polygon(string memory _props) internal pure returns (string memory) {
        return el("polygon", _props);
    }

    function polygon(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("polygon", _props, _children);
    }

    function polyline(string memory _props) internal pure returns (string memory) {
        return el("polyline", _props);
    }

    function polyline(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("polyline", _props, _children);
    }

    function rect(string memory _props) internal pure returns (string memory) {
        return el("rect", _props);
    }

    function rect(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("rect", _props, _children);
    }

    function filter(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("filter", _props, _children);
    }

    function cdata(string memory _content) internal pure returns (string memory) {
        return string.concat("<![CDATA[", _content, "]]>");
    }

    /* GRADIENTS */
    function radialGradient(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("radialGradient", _props, _children);
    }

    function linearGradient(string memory _props, string memory _children) internal pure returns (string memory) {
        return el("linearGradient", _props, _children);
    }

    function gradientStop(uint256 offset, string memory stopColor, string memory _props)
        internal
        pure
        returns (string memory)
    {
        return el(
            "stop",
            string.concat(
                prop("stop-color", stopColor),
                " ",
                prop("offset", string.concat(LibString.toString(offset), "%")),
                " ",
                _props
            ),
            utils.NULL
        );
    }

    /* ANIMATION */
    function animateTransform(string memory _props) internal pure returns (string memory) {
        return el("animateTransform", _props);
    }

    function animate(string memory _props) internal pure returns (string memory) {
        return el("animate", _props);
    }

    /* COMMON */
    // A generic element, can be used to construct any SVG (or HTML) element
    function el(string memory _tag, string memory _props, string memory _children)
        internal
        pure
        returns (string memory)
    {
        return string.concat("<", _tag, " ", _props, ">", _children, "</", _tag, ">");
    }

    // A generic element, can be used to construct SVG (or HTML) elements without children
    function el(string memory _tag, string memory _props) internal pure returns (string memory) {
        return string.concat("<", _tag, " ", _props, "/>");
    }

    // an SVG attribute
    function prop(string memory _key, string memory _val) internal pure returns (string memory) {
        return string.concat(_key, "=", '"', _val, '" ');
    }

    function prop(string memory _key, string memory _val, bool last) internal pure returns (string memory) {
        if (last) {
            return string.concat(_key, "=", '"', _val, '"');
        } else {
            return string.concat(_key, "=", '"', _val, '" ');
        }
    }
}

//SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "lib/Solady/src/utils/LibString.sol";

library numUtils {
    function toLocale(string memory _wholeNumber) internal pure returns (string memory) {
        bytes memory b = bytes(_wholeNumber);
        uint256 len = b.length;
        if (len < 4) return _wholeNumber;

        uint256 numCommas = (len - 1) / 3;

        bytes memory result = new bytes(len + numCommas);

        uint256 j = result.length - 1;
        uint256 k = len;
        for (uint256 i = 0; i < len; i++) {
            result[j] = b[k - 1];
            j = j > 1 ? j - 1 : 0;
            k--;
            if (k > 0 && (len - k) % 3 == 0) {
                result[j] = ",";
                j = j > 1 ? j - 1 : 0;
            }
        }

        return string(result);
    }

    // returns a string representation of a number with commas, where result = _value / 10 ** _divisor
    function toLocaleString(uint256 _value, uint8 _divisor, uint8 _precision) internal pure returns (string memory) {
        uint256 whole;
        uint256 fraction;

        if (_divisor > 0) {
            whole = _value / 10 ** _divisor;
            // check if the divisor is less than the precision
            if (_divisor <= _precision) {
                fraction = (_value % 10 ** _divisor);
                // adjust fraction to be the same as the precision
                fraction = fraction * 10 ** (_precision - _divisor);

                // if whole is zero, then add another zero to the fraction, special case if the value is 1
                fraction = (whole == 0 && _value != 1) ? fraction * 10 : fraction;
            } else {
                fraction = (_value % 10 ** _divisor) / 10 ** (_divisor - _precision - 1);
            }
        } else {
            whole = _value;
        }

        string memory wholeStr = toLocale(LibString.toString(whole));

        if (fraction == 0) {
            if (whole > 0 && _precision > 0) wholeStr = string.concat(wholeStr, ".");
            for (uint8 i = 0; i < _precision; i++) {
                wholeStr = string.concat(wholeStr, "0");
            }

            return wholeStr;
        }

        string memory fractionStr = LibString.slice(LibString.toString(fraction), 0, _precision);

        // pad with leading zeros
        if (_precision > bytes(fractionStr).length) {
            uint256 len = _precision - bytes(fractionStr).length;
            string memory zeroStr = "";

            for (uint8 i = 0; i < len; i++) {
                zeroStr = string.concat(zeroStr, "0");
            }

            fractionStr = string.concat(zeroStr, fractionStr);
        }

        return string.concat(wholeStr, _precision > 0 ? "." : "", fractionStr);
    }
}

/// @notice Core utils used extensively to format CSS and numbers.
/// @author Modified from (https://github.com/w1nt3r-eth/hot-chain-svg/blob/main/contracts/Utils.sol) by w1nt3r-eth.

library utils {
    // used to simulate empty strings
    string internal constant NULL = "";

    // formats a CSS variable line. includes a semicolon for formatting.
    function setCssVar(string memory _key, string memory _val) internal pure returns (string memory) {
        return string.concat("--", _key, ":", _val, ";");
    }

    // formats getting a css variable
    function getCssVar(string memory _key) internal pure returns (string memory) {
        return string.concat("var(--", _key, ")");
    }

    // formats getting a def URL
    function getDefURL(string memory _id) internal pure returns (string memory) {
        return string.concat("url(#", _id, ")");
    }

    // formats rgba white with a specified opacity / alpha
    function white_a(uint256 _a) internal pure returns (string memory) {
        return rgba(255, 255, 255, _a);
    }

    // formats rgba black with a specified opacity / alpha
    function black_a(uint256 _a) internal pure returns (string memory) {
        return rgba(0, 0, 0, _a);
    }

    // formats generic rgba color in css
    function rgba(uint256 _r, uint256 _g, uint256 _b, uint256 _a) internal pure returns (string memory) {
        string memory formattedA = _a < 100 ? string.concat("0.", LibString.toString(_a)) : "1";
        return string.concat(
            "rgba(",
            LibString.toString(_r),
            ",",
            LibString.toString(_g),
            ",",
            LibString.toString(_b),
            ",",
            formattedA,
            ")"
        );
    }

    function cssBraces(string memory _attribute, string memory _value) internal pure returns (string memory) {
        return string.concat(" {", _attribute, ": ", _value, "}");
    }

    function cssBraces(string[] memory _attributes, string[] memory _values) internal pure returns (string memory) {
        require(_attributes.length == _values.length, "Utils: Unbalanced Arrays");

        uint256 len = _attributes.length;

        string memory results = " {";

        for (uint256 i = 0; i < len; i++) {
            results = string.concat(results, _attributes[i], ": ", _values[i], "; ");
        }

        return string.concat(results, "}");
    }

    //deals with integers (i.e. no decimals)
    function points(uint256[2][] memory pointsArray) internal pure returns (string memory) {
        require(pointsArray.length >= 3, "Utils: Array too short");

        uint256 len = pointsArray.length - 1;

        string memory results = 'points="';

        for (uint256 i = 0; i < len; i++) {
            results = string.concat(
                results, LibString.toString(pointsArray[i][0]), ",", LibString.toString(pointsArray[i][1]), " "
            );
        }

        return string.concat(
            results, LibString.toString(pointsArray[len][0]), ",", LibString.toString(pointsArray[len][1]), '"'
        );
    }

    // allows for a uniform precision to be applied to all points
    function points(uint256[2][] memory pointsArray, uint256 decimalPrecision) internal pure returns (string memory) {
        require(pointsArray.length >= 3, "Utils: Array too short");

        uint256 len = pointsArray.length - 1;

        string memory results = 'points="';

        for (uint256 i = 0; i < len; i++) {
            results = string.concat(
                results,
                toString(pointsArray[i][0], decimalPrecision),
                ",",
                toString(pointsArray[i][1], decimalPrecision),
                " "
            );
        }

        return string.concat(
            results,
            toString(pointsArray[len][0], decimalPrecision),
            ",",
            toString(pointsArray[len][1], decimalPrecision),
            '"'
        );
    }

    // checks if two strings are equal
    function stringsEqual(string memory _a, string memory _b) internal pure returns (bool) {
        return keccak256(abi.encodePacked(_a)) == keccak256(abi.encodePacked(_b));
    }

    // returns the length of a string in characters
    function utfStringLength(string memory _str) internal pure returns (uint256 length) {
        uint256 i = 0;
        bytes memory string_rep = bytes(_str);

        while (i < string_rep.length) {
            if (string_rep[i] >> 7 == 0) {
                i += 1;
            } else if (string_rep[i] >> 5 == bytes1(uint8(0x6))) {
                i += 2;
            } else if (string_rep[i] >> 4 == bytes1(uint8(0xE))) {
                i += 3;
            } else if (string_rep[i] >> 3 == bytes1(uint8(0x1E))) {
                i += 4;
            }
            //For safety
            else {
                i += 1;
            }

            length++;
        }
    }

    // allows the insertion of a decimal point in the returned string at precision
    function toString(uint256 value, uint256 precision) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        require(precision <= digits && precision > 0, "Utils: precision invalid");
        precision == digits ? digits += 2 : digits++; //adds a space for the decimal point, 2 if it is the whole uint

        uint256 decimalPlacement = digits - precision - 1;
        bytes memory buffer = new bytes(digits);

        buffer[decimalPlacement] = 0x2E; // add the decimal point, ASCII 46/hex 2E
        if (decimalPlacement == 1) {
            buffer[0] = 0x30;
        }

        while (value != 0) {
            digits -= 1;
            if (digits != decimalPlacement) {
                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                value /= 10;
            }
        }

        return string(buffer);
    }
}

//SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import "lib/Solady/src/utils/SSTORE2.sol";

contract FixedAssetReader {
    struct Asset {
        uint128 start;
        uint128 end;
    }

    address public immutable pointer;

    mapping(bytes4 => Asset) public assets;

    function readAsset(bytes4 _sig) public view returns (string memory) {
        return string(SSTORE2.read(pointer, uint256(assets[_sig].start), uint256(assets[_sig].end)));
    }

    constructor(address _pointer, bytes4[] memory _sigs, Asset[] memory _assets) {
        pointer = _pointer;
        require(_sigs.length == _assets.length, "FixedAssetReader: Invalid input");
        for (uint256 i = 0; i < _sigs.length; i++) {
            assets[_sigs[i]] = _assets[i];
        }
    }
}

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

contract USNDLogoSVG {

    string public constant USND_LOGO = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTIwIiBoZWlnaHQ9IjUyMCIgdmlld0JveD0iMCAwIDUyMCA1MjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+DQo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDBfMjA0MF8xMjkxKSIgZmlsdGVyPSJ1cmwoI2ZpbHRlcjBfZF8yMDQwXzEyOTEpIj4NCjxwYXRoIGQ9Ik0yNjAgNTEyQzQwMS4zODUgNTEyIDUxNiAzOTcuMzg1IDUxNiAyNTZDNTE2IDExNC42MTUgNDAxLjM4NSAwIDI2MCAwQzExOC42MTUgMCA0IDExNC42MTUgNCAyNTZDNCAzOTcuMzg1IDExOC42MTUgNTEyIDI2MCA1MTJaIiBmaWxsPSIjMUQzMTE3Ii8+DQo8cGF0aCBkPSJNMzIwLjUzNCA3MC45NTc2QzMyMi43MTcgNjEuODI2MiAzMTcuMDg1IDUyLjY1MzYgMzA3Ljk1NCA1MC40N0MyOTguODIyIDQ4LjI4NjQgMjg5LjY1IDUzLjkxODcgMjg3LjQ2NiA2My4wNTAxTDI3OS41NzMgOTYuMDU4M0MyMjIuNjE3IDk3Ljg2NzMgMTc3IDE0NC42MDkgMTc3IDIwMi4wMDRDMTc3IDI0MS43NjkgMjA5LjIzNSAyNzMuMDA0IDI0OSAyNzMuMDA0QzI1Mi41NDMgMjczLjAwNCAyNTYuMDQgMjcyLjc1MyAyNTkuNTMxIDI3Mi41MDNDMjYzLjAxMiAyNzIuMjUzIDI2Ni40ODcgMjcyLjAwNCAyNzAgMjcyLjAwNEMyOTAuOTg3IDI3Mi4wMDQgMzA4IDI4OC4wMTcgMzA4IDMwOS4wMDRDMzA4IDM0OC43NjggMjc1Ljc2NSAzODEuMDA0IDIzNiAzODEuMDA0QzIxNS4wMTMgMzgxLjAwNCAxOTggMzYzLjk5MSAxOTggMzQzLjAwNEMxOTggMzQxLjc2NSAxOTguMTMzIDM0MC41NTcgMTk4LjM4NCAzMzkuMzk0QzIwMC40NTkgMzUxLjEwOCAyMTAuNjkxIDM2MC4wMDQgMjIzIDM2MC4wMDRDMjM5LjU2OSAzNjAuMDA0IDI1MyAzNDYuNTczIDI1MyAzMzAuMDA0QzI1MyAzMDkuMDE3IDIzNS45ODcgMjkyLjAwNCAyMTUgMjkyLjAwNEMxODYuODMzIDI5Mi4wMDQgMTY0IDMxNC44MzcgMTY0IDM0My4wMDRDMTY0IDM3Mi4wNjggMTgxLjIyMSAzOTcuMTA5IDIwNi4wMTUgNDA4LjQ4MkwxOTguNDY2IDQ0MC4wNUMxOTYuMjgzIDQ0OS4xODIgMjAxLjkxNSA0NTguMzU0IDIxMS4wNDYgNDYwLjUzOEMyMjAuMTc4IDQ2Mi43MjEgMjI5LjM1IDQ1Ny4wODkgMjMxLjUzNCA0NDcuOTU4TDIzOS40MjcgNDE0Ljk1QzI5Ni4zODMgNDEzLjE0MSAzNDIgMzY2LjM5OSAzNDIgMzA5LjAwNEMzNDIgMjY5LjIzOSAzMDkuNzY0IDIzOC4wMDQgMjcwIDIzOC4wMDRDMjY2LjQ0NyAyMzguMDA0IDI2Mi45NDIgMjM4LjI1NSAyNTkuNDQ3IDIzOC41MDZDMjU1Ljk2OSAyMzguNzU1IDI1Mi40OTkgMjM5LjAwNCAyNDkgMjM5LjAwNEMyMjguMDEzIDIzOS4wMDQgMjExIDIyMi45OTEgMjExIDIwMi4wMDRDMjExIDE2Mi4yNCAyNDMuMjM1IDEzMC4wMDQgMjgzIDEzMC4wMDRDMzAzLjk4NyAxMzAuMDA0IDMyMSAxNDcuMDE3IDMyMSAxNjguMDA0QzMyMSAxNjkuMjQzIDMyMC44NjcgMTcwLjQ1MSAzMjAuNjE2IDE3MS42MTRDMzE4LjU0MSAxNTkuOSAzMDguMzA5IDE1MS4wMDQgMjk2IDE1MS4wMDRDMjc5LjQzMSAxNTEuMDA0IDI2NiAxNjQuNDM1IDI2NiAxODEuMDA0QzI2NiAyMDEuOTkxIDI4My4wMTMgMjE5LjAwNCAzMDQgMjE5LjAwNEMzMzIuMTY3IDIxOS4wMDQgMzU1IDE5Ni4xNzEgMzU1IDE2OC4wMDRDMzU1IDEzOC45NCAzMzcuNzc5IDExMy44OTggMzEyLjk4NSAxMDIuNTI2TDMyMC41MzQgNzAuOTU3NloiIGZpbGw9IiNENUY2Q0EiLz4NCjwvZz4NCjxkZWZzPg0KPGZpbHRlciBpZD0iZmlsdGVyMF9kXzIwNDBfMTI5MSIgeD0iMCIgeT0iMCIgd2lkdGg9IjUyMCIgaGVpZ2h0PSI1MjAiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4NCjxmZUZsb29kIGZsb29kLW9wYWNpdHk9IjAiIHJlc3VsdD0iQmFja2dyb3VuZEltYWdlRml4Ii8+DQo8ZmVDb2xvck1hdHJpeCBpbj0iU291cmNlQWxwaGEiIHR5cGU9Im1hdHJpeCIgdmFsdWVzPSIwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAxMjcgMCIgcmVzdWx0PSJoYXJkQWxwaGEiLz4NCjxmZU9mZnNldCBkeT0iNCIvPg0KPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iMiIvPg0KPGZlQ29tcG9zaXRlIGluMj0iaGFyZEFscGhhIiBvcGVyYXRvcj0ib3V0Ii8+DQo8ZmVDb2xvck1hdHJpeCB0eXBlPSJtYXRyaXgiIHZhbHVlcz0iMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMCAwIDAgMC4yNSAwIi8+DQo8ZmVCbGVuZCBtb2RlPSJub3JtYWwiIGluMj0iQmFja2dyb3VuZEltYWdlRml4IiByZXN1bHQ9ImVmZmVjdDFfZHJvcFNoYWRvd18yMDQwXzEyOTEiLz4NCjxmZUJsZW5kIG1vZGU9Im5vcm1hbCIgaW49IlNvdXJjZUdyYXBoaWMiIGluMj0iZWZmZWN0MV9kcm9wU2hhZG93XzIwNDBfMTI5MSIgcmVzdWx0PSJzaGFwZSIvPg0KPC9maWx0ZXI+DQo8Y2xpcFBhdGggaWQ9ImNsaXAwXzIwNDBfMTI5MSI+DQo8cmVjdCB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgZmlsbD0id2hpdGUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDQpIi8+DQo8L2NsaXBQYXRoPg0KPC9kZWZzPg0KPC9zdmc+";

    function getLogo() external pure returns (string memory) {
        return USND_LOGO;
    }
}

// SPDX-License-Identifier: AGPLv3
pragma solidity >=0.8.4;

import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";

interface IPoolNFTBase is IERC721Metadata {
    error POOL_NFT_APPROVE_TO_CALLER();                             // 0x9212b333
    error POOL_NFT_ONLY_SUPER_TOKEN_FACTORY();                      // 0x1fd7e3d8
    error POOL_NFT_INVALID_TOKEN_ID();                              // 0x09275994
    error POOL_NFT_APPROVE_TO_CURRENT_OWNER();                      // 0x020226d3
    error POOL_NFT_APPROVE_CALLER_NOT_OWNER_OR_APPROVED_FOR_ALL();  // 0x1e82f255
    error POOL_NFT_NOT_REGISTERED_POOL();                           // 0x6421912e
    error POOL_NFT_TRANSFER_NOT_ALLOWED();                          // 0x432fb160
    error POOL_NFT_TRANSFER_CALLER_NOT_OWNER_OR_APPROVED_FOR_ALL(); // 0x4028ee0e

    /// @notice Informs third-party platforms that NFT metadata should be updated
    /// @dev This event comes from https://eips.ethereum.org/EIPS/eip-4906
    /// @param tokenId the id of the token that should have its metadata updated
    event MetadataUpdate(uint256 tokenId);

    function initialize(string memory nftName, string memory nftSymbol) external; // initializer;

    function triggerMetadataUpdate(uint256 tokenId) external;

    /// @notice Gets the token id
    /// @dev For PoolAdminNFT, `account` is admin and for PoolMemberNFT, `account` is member
    function getTokenId(address pool, address account) external view returns (uint256 tokenId);
}

// 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 70 of 70 : LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The length of the output is too small to contain all the hex digits.
    error HexLengthInsufficient();

    /// @dev The length of the string is more than 32 bytes.
    error TooBigForSmallString();

    /// @dev The input string must be a 7-bit ASCII.
    error StringNot7BitASCII();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The constant returned when the `search` is not found in the string.
    uint256 internal constant NOT_FOUND = type(uint256).max;

    /// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
    uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;

    /// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
    uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;

    /// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
    uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;

    /// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
    uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;

    /// @dev Lookup for '0123456789'.
    uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;

    /// @dev Lookup for '0123456789abcdefABCDEF'.
    uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;

    /// @dev Lookup for '01234567'.
    uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;

    /// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
    uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;

    /// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
    uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;

    /// @dev Lookup for ' \t\n\r\x0b\x0c'.
    uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     DECIMAL OPERATIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the base 10 decimal representation of `value`.
    function toString(uint256 value) internal pure returns (string memory str) {
        /// @solidity memory-safe-assembly
        assembly {
            // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
            // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
            // We will need 1 word for the trailing zeros padding, 1 word for the length,
            // and 3 words for a maximum of 78 digits.
            str := add(mload(0x40), 0x80)
            mstore(0x40, add(str, 0x20)) // Allocate the memory.
            mstore(str, 0) // Zeroize the slot after the string.

            let end := str // Cache the end of the memory to calculate the length later.
            let w := not(0) // Tsk.
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for { let temp := value } 1 {} {
                str := add(str, w) // `sub(str, 1)`.
                // Store the character to the pointer.
                // The ASCII index of the '0' character is 48.
                mstore8(str, add(48, mod(temp, 10)))
                temp := div(temp, 10) // Keep dividing `temp` until zero.
                if iszero(temp) { break }
            }
            let length := sub(end, str)
            str := sub(str, 0x20) // Move the pointer 32 bytes back to make room for the length.
            mstore(str, length) // Store the length.
        }
    }

    /// @dev Returns the base 10 decimal representation of `value`.
    function toString(int256 value) internal pure returns (string memory str) {
        if (value >= 0) return toString(uint256(value));
        unchecked {
            str = toString(~uint256(value) + 1);
        }
        /// @solidity memory-safe-assembly
        assembly {
            // We still have some spare memory space on the left,
            // as we have allocated 3 words (96 bytes) for up to 78 digits.
            let length := mload(str) // Load the string length.
            mstore(str, 0x2d) // Store the '-' character.
            str := sub(str, 1) // Move back the string pointer by a byte.
            mstore(str, add(length, 1)) // Update the string length.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   HEXADECIMAL OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the hexadecimal representation of `value`,
    /// left-padded to an input length of `length` bytes.
    /// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
    /// giving a total length of `length * 2 + 2` bytes.
    /// Reverts if `length` is too small for the output to contain all the digits.
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
        str = toHexStringNoPrefix(value, length);
        /// @solidity memory-safe-assembly
        assembly {
            let strLength := add(mload(str), 2) // Compute the length.
            mstore(str, 0x3078) // Store the "0x" prefix.
            str := sub(str, 2) // Move the pointer.
            mstore(str, strLength) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`,
    /// left-padded to an input length of `length` bytes.
    /// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
    /// giving a total length of `length * 2` bytes.
    /// Reverts if `length` is too small for the output to contain all the digits.
    function toHexStringNoPrefix(uint256 value, uint256 length)
        internal
        pure
        returns (string memory str)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
            // for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
            // We add 0x20 to the total and round down to a multiple of 0x20.
            // (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
            str := add(mload(0x40), and(add(shl(1, length), 0x42), not(0x1f)))
            mstore(0x40, add(str, 0x20)) // Allocate the memory.
            mstore(str, 0) // Zeroize the slot after the string.

            let end := str // Cache the end to calculate the length later.
            // Store "0123456789abcdef" in scratch space.
            mstore(0x0f, 0x30313233343536373839616263646566)

            let start := sub(str, add(length, length))
            let w := not(1) // Tsk.
            let temp := value
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for {} 1 {} {
                str := add(str, w) // `sub(str, 2)`.
                mstore8(add(str, 1), mload(and(temp, 15)))
                mstore8(str, mload(and(shr(4, temp), 15)))
                temp := shr(8, temp)
                if iszero(xor(str, start)) { break }
            }
            if temp {
                mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
                revert(0x1c, 0x04)
            }
            let strLength := sub(end, str)
            str := sub(str, 0x20)
            mstore(str, strLength) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
    /// As address are 20 bytes long, the output will left-padded to have
    /// a length of `20 * 2 + 2` bytes.
    function toHexString(uint256 value) internal pure returns (string memory str) {
        str = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let strLength := add(mload(str), 2) // Compute the length.
            mstore(str, 0x3078) // Store the "0x" prefix.
            str := sub(str, 2) // Move the pointer.
            mstore(str, strLength) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x".
    /// The output excludes leading "0" from the `toHexString` output.
    /// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
    function toMinimalHexString(uint256 value) internal pure returns (string memory str) {
        str = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
            let strLength := add(mload(str), 2) // Compute the length.
            mstore(add(str, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
            str := sub(add(str, o), 2) // Move the pointer, accounting for leading zero.
            mstore(str, sub(strLength, o)) // Store the length, accounting for leading zero.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output excludes leading "0" from the `toHexStringNoPrefix` output.
    /// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
    function toMinimalHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
        str = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
            let strLength := mload(str) // Get the length.
            str := add(str, o) // Move the pointer, accounting for leading zero.
            mstore(str, sub(strLength, o)) // Store the length, accounting for leading zero.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is encoded using 2 hexadecimal digits per byte.
    /// As address are 20 bytes long, the output will left-padded to have
    /// a length of `20 * 2` bytes.
    function toHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
        /// @solidity memory-safe-assembly
        assembly {
            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
            // 0x02 bytes for the prefix, and 0x40 bytes for the digits.
            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
            str := add(mload(0x40), 0x80)
            mstore(0x40, add(str, 0x20)) // Allocate the memory.
            mstore(str, 0) // Zeroize the slot after the string.

            let end := str // Cache the end to calculate the length later.
            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.

            let w := not(1) // Tsk.
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for { let temp := value } 1 {} {
                str := add(str, w) // `sub(str, 2)`.
                mstore8(add(str, 1), mload(and(temp, 15)))
                mstore8(str, mload(and(shr(4, temp), 15)))
                temp := shr(8, temp)
                if iszero(temp) { break }
            }
            let strLength := sub(end, str)
            str := sub(str, 0x20)
            mstore(str, strLength) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
    /// and the alphabets are capitalized conditionally according to
    /// https://eips.ethereum.org/EIPS/eip-55
    function toHexStringChecksummed(address value) internal pure returns (string memory str) {
        str = toHexString(value);
        /// @solidity memory-safe-assembly
        assembly {
            let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
            let o := add(str, 0x22)
            let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
            let t := shl(240, 136) // `0b10001000 << 240`
            for { let i := 0 } 1 {} {
                mstore(add(i, i), mul(t, byte(i, hashed)))
                i := add(i, 1)
                if eq(i, 20) { break }
            }
            mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
            o := add(o, 0x20)
            mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
    function toHexString(address value) internal pure returns (string memory str) {
        str = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let strLength := add(mload(str), 2) // Compute the length.
            mstore(str, 0x3078) // Store the "0x" prefix.
            str := sub(str, 2) // Move the pointer.
            mstore(str, strLength) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is encoded using 2 hexadecimal digits per byte.
    function toHexStringNoPrefix(address value) internal pure returns (string memory str) {
        /// @solidity memory-safe-assembly
        assembly {
            str := mload(0x40)
            // Allocate the memory.
            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
            // 0x02 bytes for the prefix, and 0x28 bytes for the digits.
            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
            mstore(0x40, add(str, 0x80))
            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.

            str := add(str, 2)
            mstore(str, 40) // Store the length.
            let o := add(str, 0x20)
            mstore(add(o, 40), 0) // Zeroize the slot after the string.
            value := shl(96, value)
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for { let i := 0 } 1 {} {
                let p := add(o, add(i, i))
                let temp := byte(i, value)
                mstore8(add(p, 1), mload(and(temp, 15)))
                mstore8(p, mload(shr(4, temp)))
                i := add(i, 1)
                if eq(i, 20) { break }
            }
        }
    }

    /// @dev Returns the hex encoded string from the raw bytes.
    /// The output is encoded using 2 hexadecimal digits per byte.
    function toHexString(bytes memory raw) internal pure returns (string memory str) {
        str = toHexStringNoPrefix(raw);
        /// @solidity memory-safe-assembly
        assembly {
            let strLength := add(mload(str), 2) // Compute the length.
            mstore(str, 0x3078) // Store the "0x" prefix.
            str := sub(str, 2) // Move the pointer.
            mstore(str, strLength) // Store the length.
        }
    }

    /// @dev Returns the hex encoded string from the raw bytes.
    /// The output is encoded using 2 hexadecimal digits per byte.
    function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory str) {
        /// @solidity memory-safe-assembly
        assembly {
            let length := mload(raw)
            str := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
            mstore(str, add(length, length)) // Store the length of the output.

            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
            let o := add(str, 0x20)
            let end := add(raw, length)
            for {} iszero(eq(raw, end)) {} {
                raw := add(raw, 1)
                mstore8(add(o, 1), mload(and(mload(raw), 15)))
                mstore8(o, mload(and(shr(4, mload(raw)), 15)))
                o := add(o, 2)
            }
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(0x40, add(o, 0x20)) // Allocate the memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RUNE STRING OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the number of UTF characters in the string.
    function runeCount(string memory s) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if mload(s) {
                mstore(0x00, div(not(0), 255))
                mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
                let o := add(s, 0x20)
                let end := add(o, mload(s))
                for { result := 1 } 1 { result := add(result, 1) } {
                    o := add(o, byte(0, mload(shr(250, mload(o)))))
                    if iszero(lt(o, end)) { break }
                }
            }
        }
    }

    /// @dev Returns if this string is a 7-bit ASCII string.
    /// (i.e. all characters codes are in [0..127])
    function is7BitASCII(string memory s) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            let mask := shl(7, div(not(0), 255))
            result := 1
            let n := mload(s)
            if n {
                let o := add(s, 0x20)
                let end := add(o, n)
                let last := mload(end)
                mstore(end, 0)
                for {} 1 {} {
                    if and(mask, mload(o)) {
                        result := 0
                        break
                    }
                    o := add(o, 0x20)
                    if iszero(lt(o, end)) { break }
                }
                mstore(end, last)
            }
        }
    }

    /// @dev Returns if this string is a 7-bit ASCII string,
    /// AND all characters are in the `allowed` lookup.
    /// Note: If `s` is empty, returns true regardless of `allowed`.
    function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := 1
            if mload(s) {
                let allowed_ := shr(128, shl(128, allowed))
                let o := add(s, 0x20)
                let end := add(o, mload(s))
                for {} 1 {} {
                    result := and(result, shr(byte(0, mload(o)), allowed_))
                    o := add(o, 1)
                    if iszero(and(result, lt(o, end))) { break }
                }
            }
        }
    }

    /// @dev Converts the bytes in the 7-bit ASCII string `s` to
    /// an allowed lookup for use in `is7BitASCII(s, allowed)`.
    /// To save runtime gas, you can cache the result in an immutable variable.
    function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if mload(s) {
                let o := add(s, 0x20)
                let end := add(o, mload(s))
                for {} 1 {} {
                    result := or(result, shl(byte(0, mload(o)), 1))
                    o := add(o, 1)
                    if iszero(lt(o, end)) { break }
                }
                if shr(128, result) {
                    mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   BYTE STRING OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // For performance and bytecode compactness, byte string operations are restricted
    // to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
    // Usage of byte string operations on charsets with runes spanning two or more bytes
    // can lead to undefined behavior.

    /// @dev Returns `subject` all occurrences of `search` replaced with `replacement`.
    function replace(string memory subject, string memory search, string memory replacement)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let subjectLength := mload(subject)
            let searchLength := mload(search)
            let replacementLength := mload(replacement)

            subject := add(subject, 0x20)
            search := add(search, 0x20)
            replacement := add(replacement, 0x20)
            result := add(mload(0x40), 0x20)

            let subjectEnd := add(subject, subjectLength)
            if iszero(gt(searchLength, subjectLength)) {
                let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
                let h := 0
                if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
                let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
                let s := mload(search)
                for {} 1 {} {
                    let t := mload(subject)
                    // Whether the first `searchLength % 32` bytes of
                    // `subject` and `search` matches.
                    if iszero(shr(m, xor(t, s))) {
                        if h {
                            if iszero(eq(keccak256(subject, searchLength), h)) {
                                mstore(result, t)
                                result := add(result, 1)
                                subject := add(subject, 1)
                                if iszero(lt(subject, subjectSearchEnd)) { break }
                                continue
                            }
                        }
                        // Copy the `replacement` one word at a time.
                        for { let o := 0 } 1 {} {
                            mstore(add(result, o), mload(add(replacement, o)))
                            o := add(o, 0x20)
                            if iszero(lt(o, replacementLength)) { break }
                        }
                        result := add(result, replacementLength)
                        subject := add(subject, searchLength)
                        if searchLength {
                            if iszero(lt(subject, subjectSearchEnd)) { break }
                            continue
                        }
                    }
                    mstore(result, t)
                    result := add(result, 1)
                    subject := add(subject, 1)
                    if iszero(lt(subject, subjectSearchEnd)) { break }
                }
            }

            let resultRemainder := result
            result := add(mload(0x40), 0x20)
            let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
            // Copy the rest of the string one word at a time.
            for {} lt(subject, subjectEnd) {} {
                mstore(resultRemainder, mload(subject))
                resultRemainder := add(resultRemainder, 0x20)
                subject := add(subject, 0x20)
            }
            result := sub(result, 0x20)
            let last := add(add(result, 0x20), k) // Zeroize the slot after the string.
            mstore(last, 0)
            mstore(0x40, add(last, 0x20)) // Allocate the memory.
            mstore(result, k) // Store the length.
        }
    }

    /// @dev Returns the byte index of the first location of `search` in `subject`,
    /// searching from left to right, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
    function indexOf(string memory subject, string memory search, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            for { let subjectLength := mload(subject) } 1 {} {
                if iszero(mload(search)) {
                    if iszero(gt(from, subjectLength)) {
                        result := from
                        break
                    }
                    result := subjectLength
                    break
                }
                let searchLength := mload(search)
                let subjectStart := add(subject, 0x20)

                result := not(0) // Initialize to `NOT_FOUND`.
                subject := add(subjectStart, from)
                let end := add(sub(add(subjectStart, subjectLength), searchLength), 1)

                let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
                let s := mload(add(search, 0x20))

                if iszero(and(lt(subject, end), lt(from, subjectLength))) { break }

                if iszero(lt(searchLength, 0x20)) {
                    for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
                        if iszero(shr(m, xor(mload(subject), s))) {
                            if eq(keccak256(subject, searchLength), h) {
                                result := sub(subject, subjectStart)
                                break
                            }
                        }
                        subject := add(subject, 1)
                        if iszero(lt(subject, end)) { break }
                    }
                    break
                }
                for {} 1 {} {
                    if iszero(shr(m, xor(mload(subject), s))) {
                        result := sub(subject, subjectStart)
                        break
                    }
                    subject := add(subject, 1)
                    if iszero(lt(subject, end)) { break }
                }
                break
            }
        }
    }

    /// @dev Returns the byte index of the first location of `search` in `subject`,
    /// searching from left to right.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
    function indexOf(string memory subject, string memory search)
        internal
        pure
        returns (uint256 result)
    {
        result = indexOf(subject, search, 0);
    }

    /// @dev Returns the byte index of the first location of `search` in `subject`,
    /// searching from right to left, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
    function lastIndexOf(string memory subject, string memory search, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                result := not(0) // Initialize to `NOT_FOUND`.
                let searchLength := mload(search)
                if gt(searchLength, mload(subject)) { break }
                let w := result

                let fromMax := sub(mload(subject), searchLength)
                if iszero(gt(fromMax, from)) { from := fromMax }

                let end := add(add(subject, 0x20), w)
                subject := add(add(subject, 0x20), from)
                if iszero(gt(subject, end)) { break }
                // As this function is not too often used,
                // we shall simply use keccak256 for smaller bytecode size.
                for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
                    if eq(keccak256(subject, searchLength), h) {
                        result := sub(subject, add(end, 1))
                        break
                    }
                    subject := add(subject, w) // `sub(subject, 1)`.
                    if iszero(gt(subject, end)) { break }
                }
                break
            }
        }
    }

    /// @dev Returns the byte index of the first location of `search` in `subject`,
    /// searching from right to left.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
    function lastIndexOf(string memory subject, string memory search)
        internal
        pure
        returns (uint256 result)
    {
        result = lastIndexOf(subject, search, uint256(int256(-1)));
    }

    /// @dev Returns true if `search` is found in `subject`, false otherwise.
    function contains(string memory subject, string memory search) internal pure returns (bool) {
        return indexOf(subject, search) != NOT_FOUND;
    }

    /// @dev Returns whether `subject` starts with `search`.
    function startsWith(string memory subject, string memory search)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let searchLength := mload(search)
            // Just using keccak256 directly is actually cheaper.
            // forgefmt: disable-next-item
            result := and(
                iszero(gt(searchLength, mload(subject))),
                eq(
                    keccak256(add(subject, 0x20), searchLength),
                    keccak256(add(search, 0x20), searchLength)
                )
            )
        }
    }

    /// @dev Returns whether `subject` ends with `search`.
    function endsWith(string memory subject, string memory search)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let searchLength := mload(search)
            let subjectLength := mload(subject)
            // Whether `search` is not longer than `subject`.
            let withinRange := iszero(gt(searchLength, subjectLength))
            // Just using keccak256 directly is actually cheaper.
            // forgefmt: disable-next-item
            result := and(
                withinRange,
                eq(
                    keccak256(
                        // `subject + 0x20 + max(subjectLength - searchLength, 0)`.
                        add(add(subject, 0x20), mul(withinRange, sub(subjectLength, searchLength))),
                        searchLength
                    ),
                    keccak256(add(search, 0x20), searchLength)
                )
            )
        }
    }

    /// @dev Returns `subject` repeated `times`.
    function repeat(string memory subject, uint256 times)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let subjectLength := mload(subject)
            if iszero(or(iszero(times), iszero(subjectLength))) {
                subject := add(subject, 0x20)
                result := mload(0x40)
                let output := add(result, 0x20)
                for {} 1 {} {
                    // Copy the `subject` one word at a time.
                    for { let o := 0 } 1 {} {
                        mstore(add(output, o), mload(add(subject, o)))
                        o := add(o, 0x20)
                        if iszero(lt(o, subjectLength)) { break }
                    }
                    output := add(output, subjectLength)
                    times := sub(times, 1)
                    if iszero(times) { break }
                }
                mstore(output, 0) // Zeroize the slot after the string.
                let resultLength := sub(output, add(result, 0x20))
                mstore(result, resultLength) // Store the length.
                mstore(0x40, add(result, add(resultLength, 0x40))) // Allocate the memory.
            }
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
    /// `start` and `end` are byte offsets.
    function slice(string memory subject, uint256 start, uint256 end)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let subjectLength := mload(subject)
            if iszero(gt(subjectLength, end)) { end := subjectLength }
            if iszero(gt(subjectLength, start)) { start := subjectLength }
            if lt(start, end) {
                result := mload(0x40)
                let resultLength := sub(end, start)
                mstore(result, resultLength)
                subject := add(subject, start)
                let w := not(0x1f)
                // Copy the `subject` one word at a time, backwards.
                for { let o := and(add(resultLength, 0x1f), w) } 1 {} {
                    mstore(add(result, o), mload(add(subject, o)))
                    o := add(o, w) // `sub(o, 0x20)`.
                    if iszero(o) { break }
                }
                // Zeroize the slot after the string.
                mstore(add(add(result, 0x20), resultLength), 0)
                mstore(0x40, add(result, add(resultLength, 0x40))) // Allocate the memory.
            }
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
    /// `start` is a byte offset.
    function slice(string memory subject, uint256 start)
        internal
        pure
        returns (string memory result)
    {
        result = slice(subject, start, uint256(int256(-1)));
    }

    /// @dev Returns all the indices of `search` in `subject`.
    /// The indices are byte offsets.
    function indicesOf(string memory subject, string memory search)
        internal
        pure
        returns (uint256[] memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let subjectLength := mload(subject)
            let searchLength := mload(search)

            if iszero(gt(searchLength, subjectLength)) {
                subject := add(subject, 0x20)
                search := add(search, 0x20)
                result := add(mload(0x40), 0x20)

                let subjectStart := subject
                let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)
                let h := 0
                if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
                let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
                let s := mload(search)
                for {} 1 {} {
                    let t := mload(subject)
                    // Whether the first `searchLength % 32` bytes of
                    // `subject` and `search` matches.
                    if iszero(shr(m, xor(t, s))) {
                        if h {
                            if iszero(eq(keccak256(subject, searchLength), h)) {
                                subject := add(subject, 1)
                                if iszero(lt(subject, subjectSearchEnd)) { break }
                                continue
                            }
                        }
                        // Append to `result`.
                        mstore(result, sub(subject, subjectStart))
                        result := add(result, 0x20)
                        // Advance `subject` by `searchLength`.
                        subject := add(subject, searchLength)
                        if searchLength {
                            if iszero(lt(subject, subjectSearchEnd)) { break }
                            continue
                        }
                    }
                    subject := add(subject, 1)
                    if iszero(lt(subject, subjectSearchEnd)) { break }
                }
                let resultEnd := result
                // Assign `result` to the free memory pointer.
                result := mload(0x40)
                // Store the length of `result`.
                mstore(result, shr(5, sub(resultEnd, add(result, 0x20))))
                // Allocate memory for result.
                // We allocate one more word, so this array can be recycled for {split}.
                mstore(0x40, add(resultEnd, 0x20))
            }
        }
    }

    /// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.
    function split(string memory subject, string memory delimiter)
        internal
        pure
        returns (string[] memory result)
    {
        uint256[] memory indices = indicesOf(subject, delimiter);
        /// @solidity memory-safe-assembly
        assembly {
            let w := not(0x1f)
            let indexPtr := add(indices, 0x20)
            let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
            mstore(add(indicesEnd, w), mload(subject))
            mstore(indices, add(mload(indices), 1))
            let prevIndex := 0
            for {} 1 {} {
                let index := mload(indexPtr)
                mstore(indexPtr, 0x60)
                if iszero(eq(index, prevIndex)) {
                    let element := mload(0x40)
                    let elementLength := sub(index, prevIndex)
                    mstore(element, elementLength)
                    // Copy the `subject` one word at a time, backwards.
                    for { let o := and(add(elementLength, 0x1f), w) } 1 {} {
                        mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
                        o := add(o, w) // `sub(o, 0x20)`.
                        if iszero(o) { break }
                    }
                    // Zeroize the slot after the string.
                    mstore(add(add(element, 0x20), elementLength), 0)
                    // Allocate memory for the length and the bytes,
                    // rounded up to a multiple of 32.
                    mstore(0x40, add(element, and(add(elementLength, 0x3f), w)))
                    // Store the `element` into the array.
                    mstore(indexPtr, element)
                }
                prevIndex := add(index, mload(delimiter))
                indexPtr := add(indexPtr, 0x20)
                if iszero(lt(indexPtr, indicesEnd)) { break }
            }
            result := indices
            if iszero(mload(delimiter)) {
                result := add(indices, 0x20)
                mstore(result, sub(mload(indices), 2))
            }
        }
    }

    /// @dev Returns a concatenated string of `a` and `b`.
    /// Cheaper than `string.concat()` and does not de-align the free memory pointer.
    function concat(string memory a, string memory b)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let w := not(0x1f)
            result := mload(0x40)
            let aLength := mload(a)
            // Copy `a` one word at a time, backwards.
            for { let o := and(add(aLength, 0x20), w) } 1 {} {
                mstore(add(result, o), mload(add(a, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            let bLength := mload(b)
            let output := add(result, aLength)
            // Copy `b` one word at a time, backwards.
            for { let o := and(add(bLength, 0x20), w) } 1 {} {
                mstore(add(output, o), mload(add(b, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            let totalLength := add(aLength, bLength)
            let last := add(add(result, 0x20), totalLength)
            mstore(last, 0) // Zeroize the slot after the string.
            mstore(result, totalLength) // Store the length.
            mstore(0x40, add(last, 0x20)) // Allocate the memory.
        }
    }

    /// @dev Returns a copy of the string in either lowercase or UPPERCASE.
    /// WARNING! This function is only compatible with 7-bit ASCII strings.
    function toCase(string memory subject, bool toUpper)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let length := mload(subject)
            if length {
                result := add(mload(0x40), 0x20)
                subject := add(subject, 1)
                let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
                let w := not(0)
                for { let o := length } 1 {} {
                    o := add(o, w)
                    let b := and(0xff, mload(add(subject, o)))
                    mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
                    if iszero(o) { break }
                }
                result := mload(0x40)
                mstore(result, length) // Store the length.
                let last := add(add(result, 0x20), length)
                mstore(last, 0) // Zeroize the slot after the string.
                mstore(0x40, add(last, 0x20)) // Allocate the memory.
            }
        }
    }

    /// @dev Returns a string from a small bytes32 string.
    /// `s` must be null-terminated, or behavior will be undefined.
    function fromSmallString(bytes32 s) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let n := 0
            for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
            mstore(result, n) // Store the length.
            let o := add(result, 0x20)
            mstore(o, s) // Store the bytes of the string.
            mstore(add(o, n), 0) // Zeroize the slot after the string.
            mstore(0x40, add(result, 0x40)) // Allocate the memory.
        }
    }

    /// @dev Returns the small string, with all bytes after the first null byte zeroized.
    function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
            mstore(0x00, s)
            mstore(result, 0x00)
            result := mload(0x00)
        }
    }

    /// @dev Returns the string as a normalized null-terminated small string.
    function toSmallString(string memory s) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(s)
            if iszero(lt(result, 33)) {
                mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
                revert(0x1c, 0x04)
            }
            result := shl(shl(3, sub(32, result)), mload(add(s, result)))
        }
    }

    /// @dev Returns a lowercased copy of the string.
    /// WARNING! This function is only compatible with 7-bit ASCII strings.
    function lower(string memory subject) internal pure returns (string memory result) {
        result = toCase(subject, false);
    }

    /// @dev Returns an UPPERCASED copy of the string.
    /// WARNING! This function is only compatible with 7-bit ASCII strings.
    function upper(string memory subject) internal pure returns (string memory result) {
        result = toCase(subject, true);
    }

    /// @dev Escapes the string to be used within HTML tags.
    function escapeHTML(string memory s) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            let end := add(s, mload(s))
            result := add(mload(0x40), 0x20)
            // Store the bytes of the packed offsets and strides into the scratch space.
            // `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
            mstore(0x1f, 0x900094)
            mstore(0x08, 0xc0000000a6ab)
            // Store "&quot;&amp;&#39;&lt;&gt;" into the scratch space.
            mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
            for {} iszero(eq(s, end)) {} {
                s := add(s, 1)
                let c := and(mload(s), 0xff)
                // Not in `["\"","'","&","<",">"]`.
                if iszero(and(shl(c, 1), 0x500000c400000000)) {
                    mstore8(result, c)
                    result := add(result, 1)
                    continue
                }
                let t := shr(248, mload(c))
                mstore(result, mload(and(t, 0x1f)))
                result := add(result, shr(5, t))
            }
            let last := result
            mstore(last, 0) // Zeroize the slot after the string.
            result := mload(0x40)
            mstore(result, sub(last, add(result, 0x20))) // Store the length.
            mstore(0x40, add(last, 0x20)) // Allocate the memory.
        }
    }

    /// @dev Escapes the string to be used within double-quotes in a JSON.
    /// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
    function escapeJSON(string memory s, bool addDoubleQuotes)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let end := add(s, mload(s))
            result := add(mload(0x40), 0x20)
            if addDoubleQuotes {
                mstore8(result, 34)
                result := add(1, result)
            }
            // Store "\\u0000" in scratch space.
            // Store "0123456789abcdef" in scratch space.
            // Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
            // into the scratch space.
            mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
            // Bitmask for detecting `["\"","\\"]`.
            let e := or(shl(0x22, 1), shl(0x5c, 1))
            for {} iszero(eq(s, end)) {} {
                s := add(s, 1)
                let c := and(mload(s), 0xff)
                if iszero(lt(c, 0x20)) {
                    if iszero(and(shl(c, 1), e)) {
                        // Not in `["\"","\\"]`.
                        mstore8(result, c)
                        result := add(result, 1)
                        continue
                    }
                    mstore8(result, 0x5c) // "\\".
                    mstore8(add(result, 1), c)
                    result := add(result, 2)
                    continue
                }
                if iszero(and(shl(c, 1), 0x3700)) {
                    // Not in `["\b","\t","\n","\f","\d"]`.
                    mstore8(0x1d, mload(shr(4, c))) // Hex value.
                    mstore8(0x1e, mload(and(c, 15))) // Hex value.
                    mstore(result, mload(0x19)) // "\\u00XX".
                    result := add(result, 6)
                    continue
                }
                mstore8(result, 0x5c) // "\\".
                mstore8(add(result, 1), mload(add(c, 8)))
                result := add(result, 2)
            }
            if addDoubleQuotes {
                mstore8(result, 34)
                result := add(1, result)
            }
            let last := result
            mstore(last, 0) // Zeroize the slot after the string.
            result := mload(0x40)
            mstore(result, sub(last, add(result, 0x20))) // Store the length.
            mstore(0x40, add(last, 0x20)) // Allocate the memory.
        }
    }

    /// @dev Escapes the string to be used within double-quotes in a JSON.
    function escapeJSON(string memory s) internal pure returns (string memory result) {
        result = escapeJSON(s, false);
    }

    /// @dev Returns whether `a` equals `b`.
    function eq(string memory a, string memory b) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
        }
    }

    /// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
    function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            // These should be evaluated on compile time, as far as possible.
            let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
            let x := not(or(m, or(b, add(m, and(b, m)))))
            let r := shl(7, iszero(iszero(shr(128, x))))
            r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
                xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
        }
    }

    /// @dev Packs a single string with its length into a single word.
    /// Returns `bytes32(0)` if the length is zero or greater than 31.
    function packOne(string memory a) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // We don't need to zero right pad the string,
            // since this is our own custom non-standard packing scheme.
            result :=
                mul(
                    // Load the length and the bytes.
                    mload(add(a, 0x1f)),
                    // `length != 0 && length < 32`. Abuses underflow.
                    // Assumes that the length is valid and within the block gas limit.
                    lt(sub(mload(a), 1), 0x1f)
                )
        }
    }

    /// @dev Unpacks a string packed using {packOne}.
    /// Returns the empty string if `packed` is `bytes32(0)`.
    /// If `packed` is not an output of {packOne}, the output behavior is undefined.
    function unpackOne(bytes32 packed) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40) // Grab the free memory pointer.
            mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
            mstore(result, 0) // Zeroize the length slot.
            mstore(add(result, 0x1f), packed) // Store the length and bytes.
            mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
        }
    }

    /// @dev Packs two strings with their lengths into a single word.
    /// Returns `bytes32(0)` if combined length is zero or greater than 30.
    function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let aLength := mload(a)
            // We don't need to zero right pad the strings,
            // since this is our own custom non-standard packing scheme.
            result :=
                mul(
                    or( // Load the length and the bytes of `a` and `b`.
                        shl(shl(3, sub(0x1f, aLength)), mload(add(a, aLength))),
                        mload(sub(add(b, 0x1e), aLength))
                    ),
                    // `totalLength != 0 && totalLength < 31`. Abuses underflow.
                    // Assumes that the lengths are valid and within the block gas limit.
                    lt(sub(add(aLength, mload(b)), 1), 0x1e)
                )
        }
    }

    /// @dev Unpacks strings packed using {packTwo}.
    /// Returns the empty strings if `packed` is `bytes32(0)`.
    /// If `packed` is not an output of {packTwo}, the output behavior is undefined.
    function unpackTwo(bytes32 packed)
        internal
        pure
        returns (string memory resultA, string memory resultB)
    {
        /// @solidity memory-safe-assembly
        assembly {
            resultA := mload(0x40) // Grab the free memory pointer.
            resultB := add(resultA, 0x40)
            // Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
            mstore(0x40, add(resultB, 0x40))
            // Zeroize the length slots.
            mstore(resultA, 0)
            mstore(resultB, 0)
            // Store the lengths and bytes.
            mstore(add(resultA, 0x1f), packed)
            mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
            // Right pad with zeroes.
            mstore(add(add(resultA, 0x20), mload(resultA)), 0)
            mstore(add(add(resultB, 0x20), mload(resultB)), 0)
        }
    }

    /// @dev Directly returns `a` without copying.
    function directReturn(string memory a) internal pure {
        assembly {
            // Assumes that the string does not start from the scratch space.
            let retStart := sub(a, 0x20)
            let retUnpaddedSize := add(mload(a), 0x40)
            // Right pad with zeroes. Just in case the string is produced
            // by a method that doesn't zero right pad.
            mstore(add(retStart, retUnpaddedSize), 0)
            mstore(retStart, 0x20) // Store the return offset.
            // End the transaction, returning the string.
            return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
        }
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "openzeppelin/=lib/V2-gov/lib/openzeppelin-contracts/",
    "@superfluid-finance/=lib/superfluid-protocol-monorepo/packages/",
    "@chimera/=lib/V2-gov/lib/chimera/src/",
    "Solady/=lib/Solady/src/",
    "V2-gov/=lib/V2-gov/",
    "chimera/=lib/V2-gov/lib/chimera/src/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "superfluid-protocol-monorepo/=lib/superfluid-protocol-monorepo/packages/solidity-semantic-money/src/",
    "v4-core/=lib/V2-gov/lib/v4-core/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 5
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false,
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"contract IAddressesRegistry","name":"_addressesRegistry","type":"address"},{"internalType":"contract IFlashLoanProvider","name":"_flashLoanProvider","type":"address"},{"internalType":"contract IExchange","name":"_exchange","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EmptyManager","type":"error"},{"inputs":[],"name":"NotBorrower","type":"error"},{"inputs":[],"name":"NotOwnerNorAddManager","type":"error"},{"inputs":[],"name":"NotOwnerNorRemoveManager","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"_troveId","type":"uint256"},{"indexed":false,"internalType":"address","name":"_newAddManager","type":"address"}],"name":"AddManagerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"_troveId","type":"uint256"},{"indexed":false,"internalType":"address","name":"_newRemoveManager","type":"address"},{"indexed":false,"internalType":"address","name":"_newReceiver","type":"address"}],"name":"RemoveManagerAndReceiverUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newTroveNFTAddress","type":"address"}],"name":"TroveNFTAddressChanged","type":"event"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"contract IWETH","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"addColl","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"addManagerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_collChange","type":"uint256"},{"internalType":"bool","name":"_isCollIncrease","type":"bool"},{"internalType":"uint256","name":"_boldChange","type":"uint256"},{"internalType":"bool","name":"_isDebtIncrease","type":"bool"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"adjustTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_collChange","type":"uint256"},{"internalType":"bool","name":"_isCollIncrease","type":"bool"},{"internalType":"uint256","name":"_boldChange","type":"uint256"},{"internalType":"bool","name":"_isDebtIncrease","type":"bool"},{"internalType":"uint256","name":"_upperHint","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"adjustZombieTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"boldToken","outputs":[{"internalType":"contract IBoldToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowerOperations","outputs":[{"internalType":"contract IBorrowerOperations","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"_minExpectedCollateral","type":"uint256"}],"name":"closeTroveFromCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"}],"name":"closeTroveToRawETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exchange","outputs":[{"internalType":"contract IExchange","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"flashLoanProvider","outputs":[{"internalType":"contract IFlashLoanProvider","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"troveId","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"minBoldAmount","type":"uint256"}],"internalType":"struct ILeverageZapper.LeverDownTroveParams","name":"_params","type":"tuple"}],"name":"leverDownTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"troveId","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"boldAmount","type":"uint256"},{"internalType":"uint256","name":"maxUpfrontFee","type":"uint256"}],"internalType":"struct ILeverageZapper.LeverUpTroveParams","name":"_params","type":"tuple"}],"name":"leverUpTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_inputRatio","type":"uint256"}],"name":"leverageRatioToCollateralRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"ownerIndex","type":"uint256"},{"internalType":"uint256","name":"collAmount","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"boldAmount","type":"uint256"},{"internalType":"uint256","name":"upperHint","type":"uint256"},{"internalType":"uint256","name":"lowerHint","type":"uint256"},{"internalType":"uint256","name":"annualInterestRate","type":"uint256"},{"internalType":"address","name":"batchManager","type":"address"},{"internalType":"uint256","name":"maxUpfrontFee","type":"uint256"},{"internalType":"address","name":"addManager","type":"address"},{"internalType":"address","name":"removeManager","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"internalType":"struct ILeverageZapper.OpenLeveragedTroveParams","name":"_params","type":"tuple"}],"name":"openLeveragedTroveWithRawETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"ownerIndex","type":"uint256"},{"internalType":"uint256","name":"collAmount","type":"uint256"},{"internalType":"uint256","name":"boldAmount","type":"uint256"},{"internalType":"uint256","name":"upperHint","type":"uint256"},{"internalType":"uint256","name":"lowerHint","type":"uint256"},{"internalType":"uint256","name":"annualInterestRate","type":"uint256"},{"internalType":"address","name":"batchManager","type":"address"},{"internalType":"uint256","name":"maxUpfrontFee","type":"uint256"},{"internalType":"address","name":"addManager","type":"address"},{"internalType":"address","name":"removeManager","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"internalType":"struct IZapper.OpenTroveParams","name":"_params","type":"tuple"}],"name":"openTroveWithRawETH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"troveId","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"minExpectedCollateral","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"internalType":"struct IZapper.CloseTroveParams","name":"_params","type":"tuple"},{"internalType":"uint256","name":"_effectiveFlashLoanAmount","type":"uint256"}],"name":"receiveFlashLoanOnCloseTroveFromCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"troveId","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"minBoldAmount","type":"uint256"}],"internalType":"struct ILeverageZapper.LeverDownTroveParams","name":"_params","type":"tuple"},{"internalType":"uint256","name":"_effectiveFlashLoanAmount","type":"uint256"}],"name":"receiveFlashLoanOnLeverDownTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"troveId","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"boldAmount","type":"uint256"},{"internalType":"uint256","name":"maxUpfrontFee","type":"uint256"}],"internalType":"struct ILeverageZapper.LeverUpTroveParams","name":"_params","type":"tuple"},{"internalType":"uint256","name":"_effectiveFlashLoanAmount","type":"uint256"}],"name":"receiveFlashLoanOnLeverUpTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_originalSender","type":"address"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"ownerIndex","type":"uint256"},{"internalType":"uint256","name":"collAmount","type":"uint256"},{"internalType":"uint256","name":"flashLoanAmount","type":"uint256"},{"internalType":"uint256","name":"boldAmount","type":"uint256"},{"internalType":"uint256","name":"upperHint","type":"uint256"},{"internalType":"uint256","name":"lowerHint","type":"uint256"},{"internalType":"uint256","name":"annualInterestRate","type":"uint256"},{"internalType":"address","name":"batchManager","type":"address"},{"internalType":"uint256","name":"maxUpfrontFee","type":"uint256"},{"internalType":"address","name":"addManager","type":"address"},{"internalType":"address","name":"removeManager","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"internalType":"struct ILeverageZapper.OpenLeveragedTroveParams","name":"_params","type":"tuple"},{"internalType":"uint256","name":"_effectiveFlashLoanAmount","type":"uint256"}],"name":"receiveFlashLoanOnOpenLeveragedTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"removeManagerReceiverOf","outputs":[{"internalType":"address","name":"manager","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_boldAmount","type":"uint256"}],"name":"repayBold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"address","name":"_manager","type":"address"}],"name":"setAddManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"address","name":"_manager","type":"address"}],"name":"setRemoveManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"address","name":"_manager","type":"address"},{"internalType":"address","name":"_receiver","type":"address"}],"name":"setRemoveManagerWithReceiver","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"troveManager","outputs":[{"internalType":"contract ITroveManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_boldAmount","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"withdrawBold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdrawColl","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

61018060405234801562000011575f80fd5b50604051620046aa380380620046aa833981016040819052620000349162000532565b82828282828282806001600160a01b031663059e01136040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000078573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200009e919062000583565b6001600160a01b031660808190526040519081527f39b3d3f08f5292d52497444fc183b3915a339c0b41fb021bf52ae59505e455b29060200160405180910390a150826001600160a01b03166377553ad46040518163ffffffff1660e01b8152600401602060405180830381865afa1580156200011d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000143919062000583565b6001600160a01b031660a0816001600160a01b031681525050826001600160a01b0316633d83908a6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000199573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620001bf919062000583565b6001600160a01b031660c0816001600160a01b031681525050826001600160a01b031663630afce56040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000215573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200023b919062000583565b6001600160a01b0316610100816001600160a01b031681525050826001600160a01b031663ad5c46486040518163ffffffff1660e01b81526004016020604051808303815f875af115801562000293573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002b9919062000583565b6001600160a01b0390811660e05291821661012052811661014052604080516318dc64a360e11b8152905191861692506331b8c9469160048083019260209291908290030181865afa15801562000312573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000338919062000583565b6001600160a01b0390811661016081905260e05190911603620003a15760405162461bcd60e51b815260206004820152601660248201527f47435a3a2057726f6e6720636f6c6c206272616e636800000000000000000000604482015260640160405180910390fd5b60e05160a05160405163095ea7b360e01b81526001600160a01b039092169163095ea7b391620003d7915f1990600401620005a8565b6020604051808303815f875af1158015620003f4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200041a9190620005c1565b506101605160a05160405163095ea7b360e01b81526001600160a01b039092169163095ea7b39162000452915f1990600401620005a8565b6020604051808303815f875af11580156200046f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620004959190620005c1565b50505050610100516001600160a01b031663095ea7b3825f196040518363ffffffff1660e01b8152600401620004cd929190620005a8565b6020604051808303815f875af1158015620004ea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620005109190620005c1565b50505050620005e2565b6001600160a01b03811681146200052f575f80fd5b50565b5f805f6060848603121562000545575f80fd5b835162000552816200051a565b602085015190935062000565816200051a565b604085015190925062000578816200051a565b809150509250925092565b5f6020828403121562000594575f80fd5b8151620005a1816200051a565b9392505050565b6001600160a01b03929092168252602082015260400190565b5f60208284031215620005d2575f80fd5b81518015158114620005a1575f80fd5b60805160a05160c05160e05161010051610120516101405161016051613e35620008755f395f81816102250152818161072c015281816108bf0152818161093701528181610b2701528181610c1301528181610d3e0152818161130f01528181611538015281816115c40152818161183b01528181611b2401528181611b8e01528181611fa8015281816120cc01528181612167015281816123c0015281816127c701528181612889015281816128ea01528181612d8701528181612de00152612ebc01525f81816104dc015281816106b30152818161172a01528181611a2c0152611f2f01525f8181610328015281816105ca015281816107500152818161090801528181611595015281816116d30152818161185f0152818161189801528181611b4801528181611c6701528181611fcc0152818161213e01526128bb01525f81816102f5015281816108e001528181610d5f01528181610d9b015281816110470152818161120f01528181611560015281816120ed01528181612627015281816127e801528181612da801528181612e240152612f0001525f818161041f0152818161135301528181611bd101528181612346015261280f01525f818161026501528181611181015261192801525f818161038f0152818161062801528181610ab601528181610be701528181610e2c01528181610e9401528181610fd30152818161129d015281816117bd01528181611ab801528181611cf201528181611e57015281816121f60152818161242b015281816125970152612a8601525f81816107840152818161082701528181610a1601528181610b6801528181610cb401528181610f26015281816110e001528181611472015281816120340152818161319f01526133440152613e355ff3fe608060405260043610610154575f3560e01c80630e01617c1461015f5780631d02c42e146101b5578063292a3f0b146101d65780632e59d86b146101f557806331b8c946146102145780633d83908a14610254578063580de3601461028757806359f54f40146102a65780635cd067cf146102c5578063630afce5146102e4578063639af6d01461031757806370986fe11461034a57806377553ad41461037e57806384e5253c146103b157806390de348a146103d0578063a89efd8c146103ef578063ad5c46481461040e578063ade8971a14610441578063b6ce0cc514610460578063bcc9e60e1461048d578063ce525841146104ac578063d2f7265a146104cb578063d30c4419146104fe578063d3695fa51461051d578063d6491eaf1461053c578063d7cf1f241461055b578063dcfbd2931461057a578063f926c2d214610599578063facb886f146105ac575f80fd5b3661015b57005b5f80fd5b34801561016a575f80fd5b5061019e61017936600461358c565b600160208190525f918252604090912080549101546001600160a01b03918216911682565b6040516101ac9291906135b0565b60405180910390f35b3480156101c0575f80fd5b506101d46101cf3660046135e0565b6105bf565b005b3480156101e1575f80fd5b506101d46101f036600461362d565b61077d565b348015610200575f80fd5b506101d461020f36600461365b565b61080f565b34801561021f575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b6040516101ac919061367c565b34801561025f575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b348015610292575f80fd5b506101d46102a1366004613690565b6109fe565b3480156102b1575f80fd5b506101d46102c0366004613690565b610b50565b3480156102d0575f80fd5b506101d46102df366004613690565b610c9c565b3480156102ef575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b348015610322575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b348015610355575f80fd5b5061024761036436600461358c565b5f602081905290815260409020546001600160a01b031681565b348015610389575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b3480156103bc575f80fd5b506101d46103cb3660046136bd565b610e63565b3480156103db575f80fd5b506101d46103ea366004613717565b610f0e565b3480156103fa575f80fd5b506101d461040936600461358c565b6110c8565b348015610419575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b34801561044c575f80fd5b506101d461045b366004613717565b61145a565b34801561046b575f80fd5b5061047f61047a36600461358c565b611693565b6040519081526020016101ac565b348015610498575f80fd5b506101d46104a7366004613750565b6116c8565b3480156104b7575f80fd5b506101d46104c63660046135e0565b61188d565b3480156104d6575f80fd5b506102477f000000000000000000000000000000000000000000000000000000000000000081565b348015610509575f80fd5b506101d461051836600461378a565b611c5c565b348015610528575f80fd5b506101d461053736600461362d565b611ff5565b348015610547575f80fd5b506101d46105563660046137c8565b612008565b348015610566575f80fd5b506101d4610575366004613807565b61201c565b348015610585575f80fd5b506101d4610594366004613821565b612193565b61047f6105a736600461388b565b612270565b6101d46105ba36600461389c565b6126e8565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146106105760405162461bcd60e51b8152600401610607906138b7565b60405180910390fd5b60408051632139494f60e21b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016916384e5253c916106709186359186916001919089013590829060608b0135906004016138f8565b5f604051808303815f87803b158015610687575f80fd5b505af1158015610699573d5f803e3d5ffd5b505060408051637d2976c160e11b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016935063fa52ed8292506106f29186013590602087013590600401613922565b5f604051808303815f87803b158015610709575f80fd5b505af115801561071b573d5f803e3d5ffd5b506107799250506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690507f00000000000000000000000000000000000000000000000000000000000000006020850135612986565b5050565b61077982827f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316636352211e866040518263ffffffff1660e01b81526004016107d091815260200190565b602060405180830381865afa1580156107eb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105569190613930565b6040516331a9108f60e11b8152813560048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015610874573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108989190613930565b90505f6108a68335836129dc565b90506108b28335612a6e565b6108ba613542565b6109067f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000008385612b63565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635fa54dd27f0000000000000000000000000000000000000000000000000000000000000000866020013560028860405160200161099491908135815260208083013590820152604080830135908201526060918201359181019190915260800190565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016109c29493929190613998565b5f604051808303815f87803b1580156109d9575f80fd5b505af11580156109eb573d5f803e3d5ffd5b505050506109f881612b88565b50505050565b6040516331a9108f60e11b8152600481018390525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015610a63573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a879190613930565b90505f610a9484836129dc565b9050610a9f84612a6e565b6040516302c06f1b60e51b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063580de36090610aed9087908790600401613922565b5f604051808303815f87803b158015610b04575f80fd5b505af1158015610b16573d5f803e3d5ffd5b506109f89250506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690508285612986565b6040516331a9108f60e11b8152600481018390525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015610bb5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bd99190613930565b9050610be58382612cc1565b7f0000000000000000000000000000000000000000000000000000000000000000610c3b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016333086612d45565b604051630167d53d60e61b81526001600160a01b038216906359f54f4090610c699087908790600401613922565b5f604051808303815f87803b158015610c80575f80fd5b505af1158015610c92573d5f803e3d5ffd5b5050505050505050565b6040516331a9108f60e11b8152600481018390525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015610d01573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d259190613930565b9050610d318382612cc1565b610d39613542565b610d847f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000083612d66565b6040516323b872dd60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906323b872dd90610dd4903390309088906004016139e2565b6020604051808303815f875af1158015610df0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e149190613a06565b50604051635cd067cf60e01b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690635cd067cf906109c29087908790600401613922565b610e6b613542565b5f610e7a888888888887612d72565b604051632139494f60e21b81529091506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906384e5253c90610ed3908b908b908b908b908b908b906004016138f8565b5f604051808303815f87803b158015610eea575f80fd5b505af1158015610efc573d5f803e3d5ffd5b50505050610c92878787878587612eaa565b6040516331a9108f60e11b8152600481018490525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015610f73573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f979190613930565b90505f610fa485836129dc565b9050610faf85612a6e565b60405163486f1a4560e11b81526004810186905260248101859052604481018490527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906390de348a906064015f604051808303815f87803b15801561101c575f80fd5b505af115801561102e573d5f803e3d5ffd5b505060405163a9059cbb60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016925063a9059cbb91506110809084908890600401613a21565b6020604051808303815f875af115801561109c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110c09190613a06565b505050505050565b6040516331a9108f60e11b8152600481018290525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa15801561112d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111519190613930565b90505f61115e83836129dc565b905061116983612a6e565b604051632ab4fd0160e21b8152600481018490525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063aad3f4049060240161014060405180830381865afa1580156111cf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111f39190613a6f565b80516040516323b872dd60e01b81529192506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016916323b872dd9161124691339130916004016139e2565b6020604051808303815f875af1158015611262573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112869190613a06565b50604051635aa6d46160e01b8152600481018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690635aa6d461906024015f604051808303815f87803b1580156112e6575f80fd5b505af11580156112f8573d5f803e3d5ffd5b505050602082015161133791506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016908490612986565b604051632e1a7d4d60e01b815266038d7ea4c6800060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b15801561139c575f80fd5b505af11580156113ae573d5f803e3d5ffd5b505050505f826001600160a01b031666038d7ea4c680006040515b5f6040518083038185875af1925050503d805f8114611403576040519150601f19603f3d011682016040523d82523d5f602084013e611408565b606091505b50509050806114535760405162461bcd60e51b815260206004820152601760248201527611d0d68e8814d95b991a5b99c81155120819985a5b1959604a1b6044820152606401610607565b5050505050565b6040516331a9108f60e11b8152600481018490525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156114bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114e39190613930565b90505f6114f085836129dc565b90506114fb85612a6e565b60408051608081018252868152602081018690529081018490526001600160a01b038216606082015261152c613542565b80516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811690915281517f0000000000000000000000000000000000000000000000000000000000000000909116602091909101526115938184612f82565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635fa54dd27f00000000000000000000000000000000000000000000000000000000000000008860018660405160200161162691908151815260208083015190820152604080830151908201526060918201516001600160a01b03169181019190915260800190565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016116549493929190613998565b5f604051808303815f87803b15801561166b575f80fd5b505af115801561167d573d5f803e3d5ffd5b5050505061168a81612b88565b50505050505050565b5f6116a6670de0b6b3a764000083613b1c565b6116b8670de0b6b3a764000084613b2f565b6116c29190613b46565b92915050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146117105760405162461bcd60e51b8152600401610607906138b7565b60408051636cd87ab760e11b81525f916001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169163d9b0f56e9161176391869188013590600401613922565b6020604051808303815f875af115801561177f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117a39190613b65565b604051632139494f60e21b81529091506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906384e5253c90611801908635906020880135905f908790829081906004016138f8565b5f604051808303815f87803b158015611818575f80fd5b505af115801561182a573d5f803e3d5ffd5b506118889250506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690507f00000000000000000000000000000000000000000000000000000000000000006020860135612986565b505050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146119105760405162461bcd60e51b815260206004820152602260248201527f47435a3a2043616c6c6572206e6f7420466c6173684c6f616e2070726f76696460448201526132b960f11b6064820152608401610607565b604051632ab4fd0160e21b8152823560048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063aad3f4049060240161014060405180830381865afa158015611976573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a9190613a6f565b90505f836020013582602001516119b19190613b1c565b90508360400135811015611a135760405162461bcd60e51b815260206004820152602360248201527f47435a3a204e6f7420656e6f75676820636f6c6c61746572616c2072656365696044820152621d995960ea1b6064820152608401610607565b8151604051636cd87ab760e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169163d9b0f56e91611a61918791600401613922565b6020604051808303815f875af1158015611a7d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611aa19190613b65565b50604051635aa6d46160e01b8152843560048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690635aa6d461906024015f604051808303815f87803b158015611b01575f80fd5b505af1158015611b13573d5f803e3d5ffd5b50611b719250506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690507f00000000000000000000000000000000000000000000000000000000000000006020870135612986565b611bb5611b846080860160608701613b7c565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169083612986565b604051632e1a7d4d60e01b815266038d7ea4c6800060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015611c1a575f80fd5b505af1158015611c2c573d5f803e3d5ffd5b505f9250611c439150506080860160608701613b7c565b6001600160a01b031666038d7ea4c680006040516113c9565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611ca45760405162461bcd60e51b8152600401610607906138b7565b5f611cb3826040850135613b97565b90505f80611cc586866020013561306c565b90505f611cda61012087016101008801613b7c565b6001600160a01b031603611db0576001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016639cb90ba6611d246020880188613b7c565b838689608001358a60a001358b60c001358c60e001358d61012001353030306040518c63ffffffff1660e01b8152600401611d699b9a99989796959493929190613baa565b6020604051808303815f875af1158015611d85573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611da99190613b65565b9150611ed0565b6040805161016081019091525f9080611dcc6020890189613b7c565b6001600160a01b03168152602001838152602001858152602001876080013581526020018760a0013581526020018760c00135815260200187610100016020810190611e189190613b7c565b6001600160a01b039081168252610120890135602083015230604080840182905260608401829052608090930152905163c440844f60e01b81529192507f0000000000000000000000000000000000000000000000000000000000000000169063c440844f90611e8c908490600401613c09565b6020604051808303815f875af1158015611ea8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ecc9190613b65565b9250505b611eeb82611ee661016088016101408901613b7c565b61309f565b611f1882611f0161018088016101608901613b7c565b611f136101a089016101808a01613b7c565b613103565b604051637d2976c160e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063fa52ed8290611f6e9060808901359060608a013590600401613922565b5f604051808303815f87803b158015611f85575f80fd5b505af1158015611f97573d5f803e3d5ffd5b506110c09250506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690507f00000000000000000000000000000000000000000000000000000000000000006060880135612986565b611ffe82613189565b610779828261309f565b61201183613189565b611888838383613103565b6040516331a9108f60e11b8152813560048201525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015612081573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120a59190613930565b90505f6120b38335836129dc565b90506120bf8335612a6e565b6120c7613542565b6121137f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000008385612b63565b6040805185356020828101919091528601358183018190529186013560608201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691635fa54dd2917f00000000000000000000000000000000000000000000000000000000000000009190600390608001610994565b61219b613542565b5f6121aa8a8a8a8a8a87612d72565b60405163dcfbd29360e01b8152600481018c9052602481018b9052891515604482015260648101899052871515608482015260a4810187905260c4810186905260e481018590529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063dcfbd29390610104015f604051808303815f87803b158015612240575f80fd5b505af1158015612252573d5f803e3d5ffd5b50505050612264898989898587612eaa565b50505050505050505050565b5f66038d7ea4c6800034146122b85760405162461bcd60e51b815260206004820152600e60248201526d08e86b47440aee4dedcce408aa8960931b6044820152606401610607565b5f6122ca610100840160e08501613b7c565b6001600160a01b031614806122e1575060c0820135155b6123445760405162461bcd60e51b815260206004820152602e60248201527f47435a3a2043616e6e6f742063686f6f736520696e746572657374206966206a60448201526d0ded2dcd2dcce40c240c4c2e8c6d60931b6064820152608401610607565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b15801561239d575f80fd5b505af11580156123af573d5f803e3d5ffd5b506123f09350506001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169150339050306040860135612d45565b5f806123ff8460200135613244565b90505f612413610100860160e08701613b7c565b6001600160a01b0316036124ed576001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016639cb90ba661245d6020870187613b7c565b838760400135886060013589608001358a60a001358b60c001358c61010001353030306040518c63ffffffff1660e01b81526004016124a69b9a99989796959493929190613baa565b6020604051808303815f875af11580156124c2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124e69190613b65565b9150612610565b6040805161016081019091525f90806125096020880188613b7c565b6001600160a01b031681526020018381526020018660400135815260200186606001358152602001866080013581526020018660a0013581526020018660e00160208101906125589190613b7c565b6001600160a01b039081168252610100880135602083015230604080840182905260608401829052608090930152905163c440844f60e01b81529192507f0000000000000000000000000000000000000000000000000000000000000000169063c440844f906125cc908490600401613c09565b6020604051808303815f875af11580156125e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061260c9190613b65565b9250505b60405163a9059cbb60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb90612662903390606089013590600401613a21565b6020604051808303815f875af115801561267e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126a29190613a06565b506126b982611ee661014087016101208801613b7c565b6126e1826126cf61016087016101408801613b7c565b611f1361018088016101608901613b7c565b5092915050565b66038d7ea4c68000341461272e5760405162461bcd60e51b815260206004820152600d60248201526c098b47440aee4dedcce408aa89609b1b6044820152606401610607565b5f61274161012083016101008401613b7c565b6001600160a01b03161480612758575060e0810135155b6127ba5760405162461bcd60e51b815260206004820152602d60248201527f4c5a3a2043616e6e6f742063686f6f736520696e746572657374206966206a6f60448201526c0d2dcd2dcce40c240c4c2e8c6d609b1b6064820152608401610607565b6127c2613542565b61280d7f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000083612d66565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b158015612866575f80fd5b505af1158015612878573d5f803e3d5ffd5b506128b99350506001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169150339050306040860135612d45565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316635fa54dd27f000000000000000000000000000000000000000000000000000000000000000084606001355f3387604051602001612922929190613cb0565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016129509493929190613998565b5f604051808303815f87803b158015612967575f80fd5b505af1158015612979573d5f803e3d5ffd5b5050505061077981612b88565b6118888363a9059cbb60e01b84846040516024016129a5929190613a21565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261324f565b5f828152600160208190526040822080549101546001600160a01b03918216919081169084163314801590612a1a5750336001600160a01b03831614155b15612a38576040516310bb5c9d60e31b815260040160405180910390fd5b6001600160a01b0381161580612a575750336001600160a01b03831614155b15612a665783925050506116c2565b949350505050565b604051630380585f60e21b8152600481018290525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690630e01617c906024016040805180830381865afa158015612ad2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612af69190613da5565b9150506001600160a01b03811630146107795760405162461bcd60e51b815260206004820152602960248201527f425a3a205a6170706572206973206e6f7420726563656976657220666f7220746044820152686869732074726f766560b81b6064820152608401610607565b81516001600160a01b0385811690915282519084166020909101526109f88282612f82565b5f5b60048110156107795781515f908260048110612ba857612ba8613af4565b60200201516001600160a01b0316146107795781515f908260048110612bd057612bd0613af4565b60200201516001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401612c00919061367c565b602060405180830381865afa158015612c1b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c3f9190613b65565b905082602001518260048110612c5757612c57613af4565b6020020151811115612cb857612cb8836040015184602001518460048110612c8157612c81613af4565b6020020151612c909084613b1c565b85518560048110612ca357612ca3613af4565b60200201516001600160a01b03169190612986565b50600101612b8a565b5f828152602081905260409020546001600160a01b039081169082163314801590612cf457506001600160a01b03811615155b8015612d095750336001600160a01b03821614155b15611888575f838152600160205260409020546001600160a01b03163381146109f857604051636522e96960e01b815260040160405180910390fd5b6109f8846323b872dd60e01b8585856040516024016129a5939291906139e2565b61188883838333612b63565b5f80612d8088888887613322565b9050612dcd7f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000085612d66565b8515612e0857612e086001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633308a612d45565b83612e9f576040516323b872dd60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906323b872dd90612e5d90339030908a906004016139e2565b6020604051808303815f875af1158015612e79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e9d9190613a06565b505b979650505050505050565b84612ee357612ee36001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168388612986565b8215612f795760405163a9059cbb60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063a9059cbb90612f379085908890600401613a21565b6020604051808303815f875af1158015612f53573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f779190613a06565b505b6110c081612b88565b5f5b600481101561305a5782515f908260048110612fa257612fa2613af4565b60200201516001600160a01b03161461305a5782518160048110612fc857612fc8613af4565b60200201516001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401612ff8919061367c565b602060405180830381865afa158015613013573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130379190613b65565b8360200151826004811061304d5761304d613af4565b6020020152600101612f84565b506001600160a01b0316604090910152565b5f8282604051602001613080929190613a21565b60408051601f1981840301815291905280516020909101209392505050565b5f828152602081905260409081902080546001600160a01b0319166001600160a01b0384161790555182907f3942babd464ceb1c7d319f75245a8cd41334592b45507f072e7020e63c22a8dc906130f790849061367c565b60405180910390a25050565b61310d82826133f8565b5f8381526001602081905260409182902080546001600160a01b038087166001600160a01b0319928316178355919092018054918516919092161790555183907f649442545e0f313a6d8087b19bc47bd2bd9b63f79d23a773446e00d2ea01d1699061317c90859085906135b0565b60405180910390a2505050565b6040516331a9108f60e11b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156131ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132109190613930565b6001600160a01b0316336001600160a01b03161461324157604051631963d1e760e31b815260040160405180910390fd5b50565b5f6116c2338361306c565b5f6132a3826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166134359092919063ffffffff16565b905080515f14806132c35750808060200190518101906132c39190613a06565b6118885760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610607565b6040516331a9108f60e11b8152600481018590525f9081906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636352211e90602401602060405180830381865afa158015613389573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133ad9190613930565b905080841580156133bd57505f86115b806133c55750835b156133e4576133d487836129dc565b90506133df87612a6e565b6133ee565b6133ee8783612cc1565b9695505050505050565b6001600160a01b03821615801561341757506001600160a01b03811615155b1561077957604051632235921760e01b815260040160405180910390fd5b6060612a6684845f85855f80866001600160a01b0316858760405161345a9190613dd2565b5f6040518083038185875af1925050503d805f8114613494576040519150601f19603f3d011682016040523d82523d5f602084013e613499565b606091505b5091509150612e9f87838387606083156135135782515f0361350c576001600160a01b0385163b61350c5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610607565b5081612a66565b612a6683838151156135285781518083602001fd5b8060405162461bcd60e51b81526004016106079190613ded565b604051806060016040528061355561356e565b815260200161356261356e565b81525f60209091015290565b60405180608001604052806004906020820280368337509192915050565b5f6020828403121561359c575f80fd5b5035919050565b6001600160a01b03169052565b6001600160a01b0392831681529116602082015260400190565b5f608082840312156135da575f80fd5b50919050565b5f8060a083850312156135f1575f80fd5b6135fb84846135ca565b946080939093013593505050565b6001600160a01b0381168114613241575f80fd5b803561362881613609565b919050565b5f806040838503121561363e575f80fd5b82359150602083013561365081613609565b809150509250929050565b5f6080828403121561366b575f80fd5b61367583836135ca565b9392505050565b6001600160a01b0391909116815260200190565b5f80604083850312156136a1575f80fd5b50508035926020909101359150565b8015158114613241575f80fd5b5f805f805f8060c087890312156136d2575f80fd5b863595506020870135945060408701356136eb816136b0565b9350606087013592506080870135613702816136b0565b8092505060a087013590509295509295509295565b5f805f60608486031215613729575f80fd5b505081359360208301359350604090920135919050565b5f606082840312156135da575f80fd5b5f8060808385031215613761575f80fd5b61376b8484613740565b946060939093013593505050565b5f6101a082840312156135da575f80fd5b5f805f6101e0848603121561379d575f80fd5b83356137a881613609565b92506137b78560208601613779565b91506101c084013590509250925092565b5f805f606084860312156137da575f80fd5b8335925060208401356137ec81613609565b915060408401356137fc81613609565b809150509250925092565b5f60608284031215613817575f80fd5b6136758383613740565b5f805f805f805f80610100898b031215613839575f80fd5b88359750602089013596506040890135613852816136b0565b9550606089013594506080890135613869816136b0565b979a969950949793969560a0850135955060c08501359460e001359350915050565b5f61018082840312156135da575f80fd5b5f6101a082840312156138ad575f80fd5b6136758383613779565b60208082526021908201527f4c5a3a2043616c6c6572206e6f7420466c6173684c6f616e2070726f766964656040820152603960f91b606082015260800190565b9586526020860194909452911515604085015260608401521515608083015260a082015260c00190565b918252602082015260400190565b5f60208284031215613940575f80fd5b815161367581613609565b5f5b8381101561396557818101518382015260200161394d565b50505f910152565b5f815180845261398481602086016020860161394b565b601f01601f19169290920160200192915050565b6001600160a01b0385168152602081018490525f600484106139c857634e487b7160e01b5f52602160045260245ffd5b836040830152608060608301526133ee608083018461396d565b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f60208284031215613a16575f80fd5b8151613675816136b0565b6001600160a01b03929092168252602082015260400190565b60405161014081016001600160401b0381118282101715613a6957634e487b7160e01b5f52604160045260245ffd5b60405290565b5f6101408284031215613a80575f80fd5b613a88613a3a565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e08201526101008084015181830152506101208084015181830152508091505092915050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b818103818111156116c2576116c2613b08565b80820281158282048414176116c2576116c2613b08565b5f82613b6057634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215613b75575f80fd5b5051919050565b5f60208284031215613b8c575f80fd5b813561367581613609565b808201808211156116c2576116c2613b08565b6001600160a01b039b8c168152602081019a909a5260408a01989098526060890196909652608088019490945260a087019290925260c086015260e0850152841661010084015283166101208301529091166101408201526101600190565b5f61016082019050613c1c8284516135a3565b6020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c0830151613c6060c08401826135a3565b5060e083015160e083015261010080840151613c7e828501826135a3565b505061012080840151613c93828501826135a3565b505061014080840151613ca8828501826135a3565b505092915050565b6001600160a01b03831681526101c08101613cd660208301613cd18561361d565b6135a3565b602083013560408301526040830135606083015260608301356080830152608083013560a083015260a083013560c083015260c083013560e083015261010060e084013581840152613d2981850161361d565b9050610120613d3a818501836135a3565b6101409150808501358285015250613d5381850161361d565b9050610160613d64818501836135a3565b613d6f81860161361d565b915050610180613d81818501836135a3565b613d8c81860161361d565b915050613d9d6101a08401826135a3565b509392505050565b5f8060408385031215613db6575f80fd5b8251613dc181613609565b602084015190925061365081613609565b5f8251613de381846020870161394b565b9190910192915050565b602081525f613675602083018461396d56fea2646970667358221220a198ae59c81de3326634581c57af9df24e4f3f9cc7d0f603f14061e75f2a80c764736f6c63430008180033000000000000000000000000f329fb0e818bd92395785a4f863636bc0d85e1df000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e0000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf

Deployed Bytecode

0x608060405260043610610154575f3560e01c80630e01617c1461015f5780631d02c42e146101b5578063292a3f0b146101d65780632e59d86b146101f557806331b8c946146102145780633d83908a14610254578063580de3601461028757806359f54f40146102a65780635cd067cf146102c5578063630afce5146102e4578063639af6d01461031757806370986fe11461034a57806377553ad41461037e57806384e5253c146103b157806390de348a146103d0578063a89efd8c146103ef578063ad5c46481461040e578063ade8971a14610441578063b6ce0cc514610460578063bcc9e60e1461048d578063ce525841146104ac578063d2f7265a146104cb578063d30c4419146104fe578063d3695fa51461051d578063d6491eaf1461053c578063d7cf1f241461055b578063dcfbd2931461057a578063f926c2d214610599578063facb886f146105ac575f80fd5b3661015b57005b5f80fd5b34801561016a575f80fd5b5061019e61017936600461358c565b600160208190525f918252604090912080549101546001600160a01b03918216911682565b6040516101ac9291906135b0565b60405180910390f35b3480156101c0575f80fd5b506101d46101cf3660046135e0565b6105bf565b005b3480156101e1575f80fd5b506101d46101f036600461362d565b61077d565b348015610200575f80fd5b506101d461020f36600461365b565b61080f565b34801561021f575f80fd5b506102477f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de4081565b6040516101ac919061367c565b34801561025f575f80fd5b506102477f000000000000000000000000285b3d3813d7a132d3f1ab48bb5a585e1363cdeb81565b348015610292575f80fd5b506101d46102a1366004613690565b6109fe565b3480156102b1575f80fd5b506101d46102c0366004613690565b610b50565b3480156102d0575f80fd5b506101d46102df366004613690565b610c9c565b3480156102ef575f80fd5b506102477f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4981565b348015610322575f80fd5b506102477f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e081565b348015610355575f80fd5b5061024761036436600461358c565b5f602081905290815260409020546001600160a01b031681565b348015610389575f80fd5b506102477f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f81565b3480156103bc575f80fd5b506101d46103cb3660046136bd565b610e63565b3480156103db575f80fd5b506101d46103ea366004613717565b610f0e565b3480156103fa575f80fd5b506101d461040936600461358c565b6110c8565b348015610419575f80fd5b506102477f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab181565b34801561044c575f80fd5b506101d461045b366004613717565b61145a565b34801561046b575f80fd5b5061047f61047a36600461358c565b611693565b6040519081526020016101ac565b348015610498575f80fd5b506101d46104a7366004613750565b6116c8565b3480156104b7575f80fd5b506101d46104c63660046135e0565b61188d565b3480156104d6575f80fd5b506102477f000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf81565b348015610509575f80fd5b506101d461051836600461378a565b611c5c565b348015610528575f80fd5b506101d461053736600461362d565b611ff5565b348015610547575f80fd5b506101d46105563660046137c8565b612008565b348015610566575f80fd5b506101d4610575366004613807565b61201c565b348015610585575f80fd5b506101d4610594366004613821565b612193565b61047f6105a736600461388b565b612270565b6101d46105ba36600461389c565b6126e8565b336001600160a01b037f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e016146106105760405162461bcd60e51b8152600401610607906138b7565b60405180910390fd5b60408051632139494f60e21b81526001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f16916384e5253c916106709186359186916001919089013590829060608b0135906004016138f8565b5f604051808303815f87803b158015610687575f80fd5b505af1158015610699573d5f803e3d5ffd5b505060408051637d2976c160e11b81526001600160a01b037f000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf16935063fa52ed8292506106f29186013590602087013590600401613922565b5f604051808303815f87803b158015610709575f80fd5b505af115801561071b573d5f803e3d5ffd5b506107799250506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de401690507f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06020850135612986565b5050565b61077982827f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b0316636352211e866040518263ffffffff1660e01b81526004016107d091815260200190565b602060405180830381865afa1580156107eb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105569190613930565b6040516331a9108f60e11b8152813560048201525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa158015610874573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108989190613930565b90505f6108a68335836129dc565b90506108b28335612a6e565b6108ba613542565b6109067f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de407f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d498385612b63565b7f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06001600160a01b0316635fa54dd27f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de40866020013560028860405160200161099491908135815260208083013590820152604080830135908201526060918201359181019190915260800190565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016109c29493929190613998565b5f604051808303815f87803b1580156109d9575f80fd5b505af11580156109eb573d5f803e3d5ffd5b505050506109f881612b88565b50505050565b6040516331a9108f60e11b8152600481018390525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa158015610a63573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a879190613930565b90505f610a9484836129dc565b9050610a9f84612a6e565b6040516302c06f1b60e51b81526001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f169063580de36090610aed9087908790600401613922565b5f604051808303815f87803b158015610b04575f80fd5b505af1158015610b16573d5f803e3d5ffd5b506109f89250506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de401690508285612986565b6040516331a9108f60e11b8152600481018390525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa158015610bb5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bd99190613930565b9050610be58382612cc1565b7f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f610c3b6001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de4016333086612d45565b604051630167d53d60e61b81526001600160a01b038216906359f54f4090610c699087908790600401613922565b5f604051808303815f87803b158015610c80575f80fd5b505af1158015610c92573d5f803e3d5ffd5b5050505050505050565b6040516331a9108f60e11b8152600481018390525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa158015610d01573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d259190613930565b9050610d318382612cc1565b610d39613542565b610d847f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de407f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4983612d66565b6040516323b872dd60e01b81526001600160a01b037f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4916906323b872dd90610dd4903390309088906004016139e2565b6020604051808303815f875af1158015610df0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e149190613a06565b50604051635cd067cf60e01b81526001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f1690635cd067cf906109c29087908790600401613922565b610e6b613542565b5f610e7a888888888887612d72565b604051632139494f60e21b81529091506001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f16906384e5253c90610ed3908b908b908b908b908b908b906004016138f8565b5f604051808303815f87803b158015610eea575f80fd5b505af1158015610efc573d5f803e3d5ffd5b50505050610c92878787878587612eaa565b6040516331a9108f60e11b8152600481018490525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa158015610f73573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f979190613930565b90505f610fa485836129dc565b9050610faf85612a6e565b60405163486f1a4560e11b81526004810186905260248101859052604481018490527f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f6001600160a01b0316906390de348a906064015f604051808303815f87803b15801561101c575f80fd5b505af115801561102e573d5f803e3d5ffd5b505060405163a9059cbb60e01b81526001600160a01b037f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4916925063a9059cbb91506110809084908890600401613a21565b6020604051808303815f875af115801561109c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110c09190613a06565b505050505050565b6040516331a9108f60e11b8152600481018290525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa15801561112d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111519190613930565b90505f61115e83836129dc565b905061116983612a6e565b604051632ab4fd0160e21b8152600481018490525f907f000000000000000000000000285b3d3813d7a132d3f1ab48bb5a585e1363cdeb6001600160a01b03169063aad3f4049060240161014060405180830381865afa1580156111cf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111f39190613a6f565b80516040516323b872dd60e01b81529192506001600160a01b037f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4916916323b872dd9161124691339130916004016139e2565b6020604051808303815f875af1158015611262573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112869190613a06565b50604051635aa6d46160e01b8152600481018590527f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f6001600160a01b031690635aa6d461906024015f604051808303815f87803b1580156112e6575f80fd5b505af11580156112f8573d5f803e3d5ffd5b505050602082015161133791506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de4016908490612986565b604051632e1a7d4d60e01b815266038d7ea4c6800060048201527f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031690632e1a7d4d906024015f604051808303815f87803b15801561139c575f80fd5b505af11580156113ae573d5f803e3d5ffd5b505050505f826001600160a01b031666038d7ea4c680006040515b5f6040518083038185875af1925050503d805f8114611403576040519150601f19603f3d011682016040523d82523d5f602084013e611408565b606091505b50509050806114535760405162461bcd60e51b815260206004820152601760248201527611d0d68e8814d95b991a5b99c81155120819985a5b1959604a1b6044820152606401610607565b5050505050565b6040516331a9108f60e11b8152600481018490525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa1580156114bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114e39190613930565b90505f6114f085836129dc565b90506114fb85612a6e565b60408051608081018252868152602081018690529081018490526001600160a01b038216606082015261152c613542565b80516001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de40811690915281517f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d49909116602091909101526115938184612f82565b7f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06001600160a01b0316635fa54dd27f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de408860018660405160200161162691908151815260208083015190820152604080830151908201526060918201516001600160a01b03169181019190915260800190565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016116549493929190613998565b5f604051808303815f87803b15801561166b575f80fd5b505af115801561167d573d5f803e3d5ffd5b5050505061168a81612b88565b50505050505050565b5f6116a6670de0b6b3a764000083613b1c565b6116b8670de0b6b3a764000084613b2f565b6116c29190613b46565b92915050565b336001600160a01b037f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e016146117105760405162461bcd60e51b8152600401610607906138b7565b60408051636cd87ab760e11b81525f916001600160a01b037f000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf169163d9b0f56e9161176391869188013590600401613922565b6020604051808303815f875af115801561177f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117a39190613b65565b604051632139494f60e21b81529091506001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f16906384e5253c90611801908635906020880135905f908790829081906004016138f8565b5f604051808303815f87803b158015611818575f80fd5b505af115801561182a573d5f803e3d5ffd5b506118889250506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de401690507f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06020860135612986565b505050565b336001600160a01b037f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e016146119105760405162461bcd60e51b815260206004820152602260248201527f47435a3a2043616c6c6572206e6f7420466c6173684c6f616e2070726f76696460448201526132b960f11b6064820152608401610607565b604051632ab4fd0160e21b8152823560048201525f907f000000000000000000000000285b3d3813d7a132d3f1ab48bb5a585e1363cdeb6001600160a01b03169063aad3f4049060240161014060405180830381865afa158015611976573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a9190613a6f565b90505f836020013582602001516119b19190613b1c565b90508360400135811015611a135760405162461bcd60e51b815260206004820152602360248201527f47435a3a204e6f7420656e6f75676820636f6c6c61746572616c2072656365696044820152621d995960ea1b6064820152608401610607565b8151604051636cd87ab760e11b81526001600160a01b037f000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf169163d9b0f56e91611a61918791600401613922565b6020604051808303815f875af1158015611a7d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611aa19190613b65565b50604051635aa6d46160e01b8152843560048201527f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f6001600160a01b031690635aa6d461906024015f604051808303815f87803b158015611b01575f80fd5b505af1158015611b13573d5f803e3d5ffd5b50611b719250506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de401690507f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06020870135612986565b611bb5611b846080860160608701613b7c565b6001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de40169083612986565b604051632e1a7d4d60e01b815266038d7ea4c6800060048201527f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015611c1a575f80fd5b505af1158015611c2c573d5f803e3d5ffd5b505f9250611c439150506080860160608701613b7c565b6001600160a01b031666038d7ea4c680006040516113c9565b336001600160a01b037f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e01614611ca45760405162461bcd60e51b8152600401610607906138b7565b5f611cb3826040850135613b97565b90505f80611cc586866020013561306c565b90505f611cda61012087016101008801613b7c565b6001600160a01b031603611db0576001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f16639cb90ba6611d246020880188613b7c565b838689608001358a60a001358b60c001358c60e001358d61012001353030306040518c63ffffffff1660e01b8152600401611d699b9a99989796959493929190613baa565b6020604051808303815f875af1158015611d85573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611da99190613b65565b9150611ed0565b6040805161016081019091525f9080611dcc6020890189613b7c565b6001600160a01b03168152602001838152602001858152602001876080013581526020018760a0013581526020018760c00135815260200187610100016020810190611e189190613b7c565b6001600160a01b039081168252610120890135602083015230604080840182905260608401829052608090930152905163c440844f60e01b81529192507f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f169063c440844f90611e8c908490600401613c09565b6020604051808303815f875af1158015611ea8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ecc9190613b65565b9250505b611eeb82611ee661016088016101408901613b7c565b61309f565b611f1882611f0161018088016101608901613b7c565b611f136101a089016101808a01613b7c565b613103565b604051637d2976c160e11b81526001600160a01b037f000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf169063fa52ed8290611f6e9060808901359060608a013590600401613922565b5f604051808303815f87803b158015611f85575f80fd5b505af1158015611f97573d5f803e3d5ffd5b506110c09250506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de401690507f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06060880135612986565b611ffe82613189565b610779828261309f565b61201183613189565b611888838383613103565b6040516331a9108f60e11b8152813560048201525f907f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa158015612081573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120a59190613930565b90505f6120b38335836129dc565b90506120bf8335612a6e565b6120c7613542565b6121137f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de407f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d498385612b63565b6040805185356020828101919091528601358183018190529186013560608201526001600160a01b037f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e01691635fa54dd2917f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de409190600390608001610994565b61219b613542565b5f6121aa8a8a8a8a8a87612d72565b60405163dcfbd29360e01b8152600481018c9052602481018b9052891515604482015260648101899052871515608482015260a4810187905260c4810186905260e481018590529091507f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f6001600160a01b03169063dcfbd29390610104015f604051808303815f87803b158015612240575f80fd5b505af1158015612252573d5f803e3d5ffd5b50505050612264898989898587612eaa565b50505050505050505050565b5f66038d7ea4c6800034146122b85760405162461bcd60e51b815260206004820152600e60248201526d08e86b47440aee4dedcce408aa8960931b6044820152606401610607565b5f6122ca610100840160e08501613b7c565b6001600160a01b031614806122e1575060c0820135155b6123445760405162461bcd60e51b815260206004820152602e60248201527f47435a3a2043616e6e6f742063686f6f736520696e746572657374206966206a60448201526d0ded2dcd2dcce40c240c4c2e8c6d60931b6064820152608401610607565b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b15801561239d575f80fd5b505af11580156123af573d5f803e3d5ffd5b506123f09350506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de40169150339050306040860135612d45565b5f806123ff8460200135613244565b90505f612413610100860160e08701613b7c565b6001600160a01b0316036124ed576001600160a01b037f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f16639cb90ba661245d6020870187613b7c565b838760400135886060013589608001358a60a001358b60c001358c61010001353030306040518c63ffffffff1660e01b81526004016124a69b9a99989796959493929190613baa565b6020604051808303815f875af11580156124c2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124e69190613b65565b9150612610565b6040805161016081019091525f90806125096020880188613b7c565b6001600160a01b031681526020018381526020018660400135815260200186606001358152602001866080013581526020018660a0013581526020018660e00160208101906125589190613b7c565b6001600160a01b039081168252610100880135602083015230604080840182905260608401829052608090930152905163c440844f60e01b81529192507f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f169063c440844f906125cc908490600401613c09565b6020604051808303815f875af11580156125e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061260c9190613b65565b9250505b60405163a9059cbb60e01b81526001600160a01b037f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d49169063a9059cbb90612662903390606089013590600401613a21565b6020604051808303815f875af115801561267e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906126a29190613a06565b506126b982611ee661014087016101208801613b7c565b6126e1826126cf61016087016101408801613b7c565b611f1361018088016101608901613b7c565b5092915050565b66038d7ea4c68000341461272e5760405162461bcd60e51b815260206004820152600d60248201526c098b47440aee4dedcce408aa89609b1b6044820152606401610607565b5f61274161012083016101008401613b7c565b6001600160a01b03161480612758575060e0810135155b6127ba5760405162461bcd60e51b815260206004820152602d60248201527f4c5a3a2043616e6e6f742063686f6f736520696e746572657374206966206a6f60448201526c0d2dcd2dcce40c240c4c2e8c6d609b1b6064820152608401610607565b6127c2613542565b61280d7f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de407f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4983612d66565b7f00000000000000000000000082af49447d8a07e3bd95bd0d56f35241523fbab16001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004015f604051808303818588803b158015612866575f80fd5b505af1158015612878573d5f803e3d5ffd5b506128b99350506001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de40169150339050306040860135612d45565b7f000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e06001600160a01b0316635fa54dd27f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de4084606001355f3387604051602001612922929190613cb0565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016129509493929190613998565b5f604051808303815f87803b158015612967575f80fd5b505af1158015612979573d5f803e3d5ffd5b5050505061077981612b88565b6118888363a9059cbb60e01b84846040516024016129a5929190613a21565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261324f565b5f828152600160208190526040822080549101546001600160a01b03918216919081169084163314801590612a1a5750336001600160a01b03831614155b15612a38576040516310bb5c9d60e31b815260040160405180910390fd5b6001600160a01b0381161580612a575750336001600160a01b03831614155b15612a665783925050506116c2565b949350505050565b604051630380585f60e21b8152600481018290525f907f0000000000000000000000005dd68bcd530eacad631734132574587aed25eb4f6001600160a01b031690630e01617c906024016040805180830381865afa158015612ad2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612af69190613da5565b9150506001600160a01b03811630146107795760405162461bcd60e51b815260206004820152602960248201527f425a3a205a6170706572206973206e6f7420726563656976657220666f7220746044820152686869732074726f766560b81b6064820152608401610607565b81516001600160a01b0385811690915282519084166020909101526109f88282612f82565b5f5b60048110156107795781515f908260048110612ba857612ba8613af4565b60200201516001600160a01b0316146107795781515f908260048110612bd057612bd0613af4565b60200201516001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401612c00919061367c565b602060405180830381865afa158015612c1b573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c3f9190613b65565b905082602001518260048110612c5757612c57613af4565b6020020151811115612cb857612cb8836040015184602001518460048110612c8157612c81613af4565b6020020151612c909084613b1c565b85518560048110612ca357612ca3613af4565b60200201516001600160a01b03169190612986565b50600101612b8a565b5f828152602081905260409020546001600160a01b039081169082163314801590612cf457506001600160a01b03811615155b8015612d095750336001600160a01b03821614155b15611888575f838152600160205260409020546001600160a01b03163381146109f857604051636522e96960e01b815260040160405180910390fd5b6109f8846323b872dd60e01b8585856040516024016129a5939291906139e2565b61188883838333612b63565b5f80612d8088888887613322565b9050612dcd7f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de407f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4985612d66565b8515612e0857612e086001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de401633308a612d45565b83612e9f576040516323b872dd60e01b81526001600160a01b037f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d4916906323b872dd90612e5d90339030908a906004016139e2565b6020604051808303815f875af1158015612e79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e9d9190613a06565b505b979650505050505050565b84612ee357612ee36001600160a01b037f0000000000000000000000006c84a8f1c29108f47a79964b5fe888d4f4d0de40168388612986565b8215612f795760405163a9059cbb60e01b81526001600160a01b037f0000000000000000000000004ecf61a6c2fab8a047ceb3b3b263b401763e9d49169063a9059cbb90612f379085908890600401613a21565b6020604051808303815f875af1158015612f53573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f779190613a06565b505b6110c081612b88565b5f5b600481101561305a5782515f908260048110612fa257612fa2613af4565b60200201516001600160a01b03161461305a5782518160048110612fc857612fc8613af4565b60200201516001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401612ff8919061367c565b602060405180830381865afa158015613013573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130379190613b65565b8360200151826004811061304d5761304d613af4565b6020020152600101612f84565b506001600160a01b0316604090910152565b5f8282604051602001613080929190613a21565b60408051601f1981840301815291905280516020909101209392505050565b5f828152602081905260409081902080546001600160a01b0319166001600160a01b0384161790555182907f3942babd464ceb1c7d319f75245a8cd41334592b45507f072e7020e63c22a8dc906130f790849061367c565b60405180910390a25050565b61310d82826133f8565b5f8381526001602081905260409182902080546001600160a01b038087166001600160a01b0319928316178355919092018054918516919092161790555183907f649442545e0f313a6d8087b19bc47bd2bd9b63f79d23a773446e00d2ea01d1699061317c90859085906135b0565b60405180910390a2505050565b6040516331a9108f60e11b8152600481018290527f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee56001600160a01b031690636352211e90602401602060405180830381865afa1580156131ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906132109190613930565b6001600160a01b0316336001600160a01b03161461324157604051631963d1e760e31b815260040160405180910390fd5b50565b5f6116c2338361306c565b5f6132a3826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166134359092919063ffffffff16565b905080515f14806132c35750808060200190518101906132c39190613a06565b6118885760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610607565b6040516331a9108f60e11b8152600481018590525f9081906001600160a01b037f00000000000000000000000018b91eff8f65c6ed0bfe22003b4e239310108ee51690636352211e90602401602060405180830381865afa158015613389573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906133ad9190613930565b905080841580156133bd57505f86115b806133c55750835b156133e4576133d487836129dc565b90506133df87612a6e565b6133ee565b6133ee8783612cc1565b9695505050505050565b6001600160a01b03821615801561341757506001600160a01b03811615155b1561077957604051632235921760e01b815260040160405180910390fd5b6060612a6684845f85855f80866001600160a01b0316858760405161345a9190613dd2565b5f6040518083038185875af1925050503d805f8114613494576040519150601f19603f3d011682016040523d82523d5f602084013e613499565b606091505b5091509150612e9f87838387606083156135135782515f0361350c576001600160a01b0385163b61350c5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610607565b5081612a66565b612a6683838151156135285781518083602001fd5b8060405162461bcd60e51b81526004016106079190613ded565b604051806060016040528061355561356e565b815260200161356261356e565b81525f60209091015290565b60405180608001604052806004906020820280368337509192915050565b5f6020828403121561359c575f80fd5b5035919050565b6001600160a01b03169052565b6001600160a01b0392831681529116602082015260400190565b5f608082840312156135da575f80fd5b50919050565b5f8060a083850312156135f1575f80fd5b6135fb84846135ca565b946080939093013593505050565b6001600160a01b0381168114613241575f80fd5b803561362881613609565b919050565b5f806040838503121561363e575f80fd5b82359150602083013561365081613609565b809150509250929050565b5f6080828403121561366b575f80fd5b61367583836135ca565b9392505050565b6001600160a01b0391909116815260200190565b5f80604083850312156136a1575f80fd5b50508035926020909101359150565b8015158114613241575f80fd5b5f805f805f8060c087890312156136d2575f80fd5b863595506020870135945060408701356136eb816136b0565b9350606087013592506080870135613702816136b0565b8092505060a087013590509295509295509295565b5f805f60608486031215613729575f80fd5b505081359360208301359350604090920135919050565b5f606082840312156135da575f80fd5b5f8060808385031215613761575f80fd5b61376b8484613740565b946060939093013593505050565b5f6101a082840312156135da575f80fd5b5f805f6101e0848603121561379d575f80fd5b83356137a881613609565b92506137b78560208601613779565b91506101c084013590509250925092565b5f805f606084860312156137da575f80fd5b8335925060208401356137ec81613609565b915060408401356137fc81613609565b809150509250925092565b5f60608284031215613817575f80fd5b6136758383613740565b5f805f805f805f80610100898b031215613839575f80fd5b88359750602089013596506040890135613852816136b0565b9550606089013594506080890135613869816136b0565b979a969950949793969560a0850135955060c08501359460e001359350915050565b5f61018082840312156135da575f80fd5b5f6101a082840312156138ad575f80fd5b6136758383613779565b60208082526021908201527f4c5a3a2043616c6c6572206e6f7420466c6173684c6f616e2070726f766964656040820152603960f91b606082015260800190565b9586526020860194909452911515604085015260608401521515608083015260a082015260c00190565b918252602082015260400190565b5f60208284031215613940575f80fd5b815161367581613609565b5f5b8381101561396557818101518382015260200161394d565b50505f910152565b5f815180845261398481602086016020860161394b565b601f01601f19169290920160200192915050565b6001600160a01b0385168152602081018490525f600484106139c857634e487b7160e01b5f52602160045260245ffd5b836040830152608060608301526133ee608083018461396d565b6001600160a01b039384168152919092166020820152604081019190915260600190565b5f60208284031215613a16575f80fd5b8151613675816136b0565b6001600160a01b03929092168252602082015260400190565b60405161014081016001600160401b0381118282101715613a6957634e487b7160e01b5f52604160045260245ffd5b60405290565b5f6101408284031215613a80575f80fd5b613a88613a3a565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e08201526101008084015181830152506101208084015181830152508091505092915050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b818103818111156116c2576116c2613b08565b80820281158282048414176116c2576116c2613b08565b5f82613b6057634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215613b75575f80fd5b5051919050565b5f60208284031215613b8c575f80fd5b813561367581613609565b808201808211156116c2576116c2613b08565b6001600160a01b039b8c168152602081019a909a5260408a01989098526060890196909652608088019490945260a087019290925260c086015260e0850152841661010084015283166101208301529091166101408201526101600190565b5f61016082019050613c1c8284516135a3565b6020830151602083015260408301516040830152606083015160608301526080830151608083015260a083015160a083015260c0830151613c6060c08401826135a3565b5060e083015160e083015261010080840151613c7e828501826135a3565b505061012080840151613c93828501826135a3565b505061014080840151613ca8828501826135a3565b505092915050565b6001600160a01b03831681526101c08101613cd660208301613cd18561361d565b6135a3565b602083013560408301526040830135606083015260608301356080830152608083013560a083015260a083013560c083015260c083013560e083015261010060e084013581840152613d2981850161361d565b9050610120613d3a818501836135a3565b6101409150808501358285015250613d5381850161361d565b9050610160613d64818501836135a3565b613d6f81860161361d565b915050610180613d81818501836135a3565b613d8c81860161361d565b915050613d9d6101a08401826135a3565b509392505050565b5f8060408385031215613db6575f80fd5b8251613dc181613609565b602084015190925061365081613609565b5f8251613de381846020870161394b565b9190910192915050565b602081525f613675602083018461396d56fea2646970667358221220a198ae59c81de3326634581c57af9df24e4f3f9cc7d0f603f14061e75f2a80c764736f6c63430008180033

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

000000000000000000000000f329fb0e818bd92395785a4f863636bc0d85e1df000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e0000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf

-----Decoded View---------------
Arg [0] : _addressesRegistry (address): 0xF329FB0E818bD92395785a4f863636bC0D85e1DF
Arg [1] : _flashLoanProvider (address): 0xF21C6A21D9Dc40a85A9C11a6a565fd07E972F2E0
Arg [2] : _exchange (address): 0x560E516a8cA0a740Af966482cbC46587144f54cf

-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 000000000000000000000000f329fb0e818bd92395785a4f863636bc0d85e1df
Arg [1] : 000000000000000000000000f21c6a21d9dc40a85a9c11a6a565fd07e972f2e0
Arg [2] : 000000000000000000000000560e516a8ca0a740af966482cbc46587144f54cf


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

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.