Sonic Blaze Testnet

Contract

0xC23E2887e548aa08fED067b4bCE0080fE8112992

Overview

S Balance

Sonic Blaze LogoSonic Blaze LogoSonic Blaze Logo0 S

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Latest 16 internal transactions

Parent Transaction Hash Block From To
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729
0xC23E2887...fE8112992
0 S
43734342024-12-15 20:48:493 days ago1734295729  Contract Creation0 S
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
BorrowerOperations

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 50 : BorrowerOperations.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.24;

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

import "./Interfaces/IBorrowerOperations.sol";
import "./Interfaces/IAddressesRegistry.sol";
import "./Interfaces/ITroveManager.sol";
import "./Interfaces/IBoldToken.sol";
import "./Interfaces/ICollSurplusPool.sol";
import "./Interfaces/ISortedTroves.sol";
import "./Dependencies/LiquityBase.sol";
import "./Dependencies/AddRemoveManagers.sol";
import "./Types/LatestTroveData.sol";
import "./Types/LatestBatchData.sol";

contract BorrowerOperations is LiquityBase, AddRemoveManagers, IBorrowerOperations {
    using SafeERC20 for IERC20;

    // --- Connected contract declarations ---

    IERC20 internal immutable collToken;
    ITroveManager internal troveManager;
    address internal gasPoolAddress;
    ICollSurplusPool internal collSurplusPool;
    IBoldToken internal boldToken;
    // A doubly linked list of Troves, sorted by their collateral ratios
    ISortedTroves internal sortedTroves;
    // Wrapped ETH for liquidation reserve (gas compensation)
    IWETH internal immutable WETH;

    // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, some borrowing operation restrictions are applied
    uint256 public immutable CCR;

    // Shutdown system collateral ratio. If the system's total collateral ratio (TCR) for a given collateral falls below the SCR,
    // the protocol triggers the shutdown of the borrow market and permanently disables all borrowing operations except for closing Troves.
    uint256 public immutable SCR;
    bool public hasBeenShutDown;

    // Minimum collateral ratio for individual troves
    uint256 public immutable MCR;

    /*
    * Mapping from TroveId to individual delegate for interest rate setting.
    *
    * This address then has the ability to update the borrower’s interest rate, but not change its debt or collateral.
    * Useful for instance for cold/hot wallet setups.
    */
    mapping(uint256 => InterestIndividualDelegate) private interestIndividualDelegateOf;

    /*
     * Mapping from TroveId to granted address for interest rate setting (batch manager).
     *
     * Batch managers set the interest rate for every Trove in the batch. The interest rate is the same for all Troves in the batch.
     */
    mapping(uint256 => address) public interestBatchManagerOf;

    // List of registered Interest Batch Managers
    mapping(address => InterestBatchManager) private interestBatchManagers;

    /* --- Variable container structs  ---

    Used to hold, return and assign variables inside a function, in order to avoid the error:
    "CompilerError: Stack too deep". */

    struct OpenTroveVars {
        ITroveManager troveManager;
        uint256 troveId;
        TroveChange change;
        LatestBatchData batch;
    }

    struct LocalVariables_openTrove {
        ITroveManager troveManager;
        IActivePool activePool;
        IBoldToken boldToken;
        uint256 troveId;
        uint256 price;
        uint256 avgInterestRate;
        uint256 entireDebt;
        uint256 ICR;
        uint256 newTCR;
        bool newOracleFailureDetected;
    }

    struct LocalVariables_adjustTrove {
        IActivePool activePool;
        IBoldToken boldToken;
        LatestTroveData trove;
        uint256 price;
        bool isBelowCriticalThreshold;
        uint256 newICR;
        uint256 newDebt;
        uint256 newColl;
        bool newOracleFailureDetected;
    }

    struct LocalVariables_setInterestBatchManager {
        ITroveManager troveManager;
        IActivePool activePool;
        ISortedTroves sortedTroves;
        address oldBatchManager;
        LatestTroveData trove;
        LatestBatchData oldBatch;
        LatestBatchData newBatch;
    }

    struct LocalVariables_removeFromBatch {
        ITroveManager troveManager;
        ISortedTroves sortedTroves;
        address batchManager;
        LatestTroveData trove;
        LatestBatchData batch;
        uint256 newBatchDebt;
    }

    error IsShutDown();
    error TCRNotBelowSCR();
    error ZeroAdjustment();
    error NotOwnerNorInterestManager();
    error TroveInBatch();
    error TroveNotInBatch();
    error InterestNotInRange();
    error BatchInterestRateChangePeriodNotPassed();
    error DelegateInterestRateChangePeriodNotPassed();
    error TroveExists();
    error TroveNotOpen();
    error TroveNotActive();
    error TroveNotZombie();
    error TroveWithZeroDebt();
    error UpfrontFeeTooHigh();
    error ICRBelowMCR();
    error RepaymentNotMatchingCollWithdrawal();
    error TCRBelowCCR();
    error DebtBelowMin();
    error CollWithdrawalTooHigh();
    error NotEnoughBoldBalance();
    error InterestRateTooLow();
    error InterestRateTooHigh();
    error InterestRateNotNew();
    error InvalidInterestBatchManager();
    error BatchManagerExists();
    error BatchManagerNotNew();
    error NewFeeNotLower();
    error CallerNotTroveManager();
    error CallerNotPriceFeed();
    error MinGeMax();
    error AnnualManagementFeeTooHigh();
    error MinInterestRateChangePeriodTooLow();
    error NewOracleFailureDetected();

    event TroveManagerAddressChanged(address _newTroveManagerAddress);
    event GasPoolAddressChanged(address _gasPoolAddress);
    event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
    event SortedTrovesAddressChanged(address _sortedTrovesAddress);
    event BoldTokenAddressChanged(address _boldTokenAddress);

    event ShutDown(uint256 _tcr);

    constructor(IAddressesRegistry _addressesRegistry)
        AddRemoveManagers(_addressesRegistry)
        LiquityBase(_addressesRegistry)
    {
        // This makes impossible to open a trove with zero withdrawn Bold
        assert(MIN_DEBT > 0);

        collToken = _addressesRegistry.collToken();

        WETH = _addressesRegistry.WETH();

        CCR = _addressesRegistry.CCR();
        SCR = _addressesRegistry.SCR();
        MCR = _addressesRegistry.MCR();

        troveManager = _addressesRegistry.troveManager();
        gasPoolAddress = _addressesRegistry.gasPoolAddress();
        collSurplusPool = _addressesRegistry.collSurplusPool();
        sortedTroves = _addressesRegistry.sortedTroves();
        boldToken = _addressesRegistry.boldToken();

        emit TroveManagerAddressChanged(address(troveManager));
        emit GasPoolAddressChanged(gasPoolAddress);
        emit CollSurplusPoolAddressChanged(address(collSurplusPool));
        emit SortedTrovesAddressChanged(address(sortedTroves));
        emit BoldTokenAddressChanged(address(boldToken));

        // Allow funds movements between Liquity contracts
        collToken.approve(address(activePool), type(uint256).max);
    }

    // --- Borrower Trove Operations ---

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

        OpenTroveVars memory vars;

        vars.troveId = _openTrove(
            _owner,
            _ownerIndex,
            _collAmount,
            _boldAmount,
            _annualInterestRate,
            address(0),
            0,
            0,
            _maxUpfrontFee,
            _addManager,
            _removeManager,
            _receiver,
            vars.change
        );

        // Set the stored Trove properties and mint the NFT
        troveManager.onOpenTrove(_owner, vars.troveId, vars.change, _annualInterestRate);

        sortedTroves.insert(vars.troveId, _annualInterestRate, _upperHint, _lowerHint);

        return vars.troveId;
    }

    function openTroveAndJoinInterestBatchManager(OpenTroveAndJoinInterestBatchManagerParams calldata _params)
        external
        override
        returns (uint256)
    {
        _requireValidInterestBatchManager(_params.interestBatchManager);

        OpenTroveVars memory vars;
        vars.troveManager = troveManager;

        vars.batch = vars.troveManager.getLatestBatchData(_params.interestBatchManager);

        // We set old weighted values here, as it’s only necessary for batches, so we don’t need to pass them to _openTrove func
        vars.change.batchAccruedManagementFee = vars.batch.accruedManagementFee;
        vars.change.oldWeightedRecordedDebt = vars.batch.weightedRecordedDebt;
        vars.change.oldWeightedRecordedBatchManagementFee = vars.batch.weightedRecordedBatchManagementFee;
        vars.troveId = _openTrove(
            _params.owner,
            _params.ownerIndex,
            _params.collAmount,
            _params.boldAmount,
            vars.batch.annualInterestRate,
            _params.interestBatchManager,
            vars.batch.entireDebtWithoutRedistribution,
            vars.batch.annualManagementFee,
            _params.maxUpfrontFee,
            _params.addManager,
            _params.removeManager,
            _params.receiver,
            vars.change
        );

        interestBatchManagerOf[vars.troveId] = _params.interestBatchManager;

        // Set the stored Trove properties and mint the NFT
        vars.troveManager.onOpenTroveAndJoinBatch(
            _params.owner,
            vars.troveId,
            vars.change,
            _params.interestBatchManager,
            vars.batch.entireCollWithoutRedistribution,
            vars.batch.entireDebtWithoutRedistribution
        );

        sortedTroves.insertIntoBatch(
            vars.troveId,
            BatchId.wrap(_params.interestBatchManager),
            vars.batch.annualInterestRate,
            _params.upperHint,
            _params.lowerHint
        );

        return vars.troveId;
    }

    function _openTrove(
        address _owner,
        uint256 _ownerIndex,
        uint256 _collAmount,
        uint256 _boldAmount,
        uint256 _annualInterestRate,
        address _interestBatchManager,
        uint256 _batchEntireDebt,
        uint256 _batchManagementAnnualFee,
        uint256 _maxUpfrontFee,
        address _addManager,
        address _removeManager,
        address _receiver,
        TroveChange memory _change
    ) internal returns (uint256) {
        _requireIsNotShutDown();

        LocalVariables_openTrove memory vars;

        // stack too deep not allowing to reuse troveManager from outer functions
        vars.troveManager = troveManager;
        vars.activePool = activePool;
        vars.boldToken = boldToken;

        vars.price = _requireOraclesLive();

        // --- Checks ---

        vars.troveId = uint256(keccak256(abi.encode(_owner, _ownerIndex)));
        _requireTroveDoesNotExists(vars.troveManager, vars.troveId);

        _change.collIncrease = _collAmount;
        _change.debtIncrease = _boldAmount;

        // For simplicity, we ignore the fee when calculating the approx. interest rate
        _change.newWeightedRecordedDebt = (_batchEntireDebt + _change.debtIncrease) * _annualInterestRate;

        vars.avgInterestRate = vars.activePool.getNewApproxAvgInterestRateFromTroveChange(_change);
        _change.upfrontFee = _calcUpfrontFee(_change.debtIncrease, vars.avgInterestRate);
        _requireUserAcceptsUpfrontFee(_change.upfrontFee, _maxUpfrontFee);

        vars.entireDebt = _change.debtIncrease + _change.upfrontFee;
        _requireAtLeastMinDebt(vars.entireDebt);

        // Recalculate newWeightedRecordedDebt, now taking into account the upfront fee, and the batch fee if needed
        if (_interestBatchManager == address(0)) {
            _change.newWeightedRecordedDebt = vars.entireDebt * _annualInterestRate;
        } else {
            // old values have been set outside, before calling this function
            _change.newWeightedRecordedDebt = (_batchEntireDebt + vars.entireDebt) * _annualInterestRate;
            _change.newWeightedRecordedBatchManagementFee =
                (_batchEntireDebt + vars.entireDebt) * _batchManagementAnnualFee;
        }

        // ICR is based on the requested Bold amount + upfront fee.
        vars.ICR = LiquityMath._computeCR(_collAmount, vars.entireDebt, vars.price);
        _requireICRisAboveMCR(vars.ICR);

        vars.newTCR = _getNewTCRFromTroveChange(_change, vars.price);
        _requireNewTCRisAboveCCR(vars.newTCR);

        // --- Effects & interactions ---

        // Set add/remove managers
        _setAddManager(vars.troveId, _addManager);
        _setRemoveManagerAndReceiver(vars.troveId, _removeManager, _receiver);

        vars.activePool.mintAggInterestAndAccountForTroveChange(_change, _interestBatchManager);

        // Pull coll tokens from sender and move them to the Active Pool
        _pullCollAndSendToActivePool(vars.activePool, _collAmount);

        // Mint the requested _boldAmount to the borrower and mint the gas comp to the GasPool
        vars.boldToken.mint(msg.sender, _boldAmount);
        WETH.transferFrom(msg.sender, gasPoolAddress, ETH_GAS_COMPENSATION);

        return vars.troveId;
    }

    // Send collateral to a trove
    function addColl(uint256 _troveId, uint256 _collAmount) external override {
        ITroveManager troveManagerCached = troveManager;
        _requireTroveIsActive(troveManagerCached, _troveId);

        TroveChange memory troveChange;
        troveChange.collIncrease = _collAmount;

        _adjustTrove(
            troveManagerCached,
            _troveId,
            troveChange,
            0 // _maxUpfrontFee
        );
    }

    // Withdraw collateral from a trove
    function withdrawColl(uint256 _troveId, uint256 _collWithdrawal) external override {
        ITroveManager troveManagerCached = troveManager;
        _requireTroveIsActive(troveManagerCached, _troveId);

        TroveChange memory troveChange;
        troveChange.collDecrease = _collWithdrawal;

        _adjustTrove(
            troveManagerCached,
            _troveId,
            troveChange,
            0 // _maxUpfrontFee
        );
    }

    // Withdraw Bold tokens from a trove: mint new Bold tokens to the owner, and increase the trove's debt accordingly
    function withdrawBold(uint256 _troveId, uint256 _boldAmount, uint256 _maxUpfrontFee) external override {
        ITroveManager troveManagerCached = troveManager;
        _requireTroveIsActive(troveManagerCached, _troveId);

        TroveChange memory troveChange;
        troveChange.debtIncrease = _boldAmount;
        _adjustTrove(troveManagerCached, _troveId, troveChange, _maxUpfrontFee);
    }

    // Repay Bold tokens to a Trove: Burn the repaid Bold tokens, and reduce the trove's debt accordingly
    function repayBold(uint256 _troveId, uint256 _boldAmount) external override {
        ITroveManager troveManagerCached = troveManager;
        _requireTroveIsActive(troveManagerCached, _troveId);

        TroveChange memory troveChange;
        troveChange.debtDecrease = _boldAmount;

        _adjustTrove(
            troveManagerCached,
            _troveId,
            troveChange,
            0 // _maxUpfrontFee
        );
    }

    function _initTroveChange(
        TroveChange memory _troveChange,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease
    ) internal pure {
        if (_isCollIncrease) {
            _troveChange.collIncrease = _collChange;
        } else {
            _troveChange.collDecrease = _collChange;
        }

        if (_isDebtIncrease) {
            _troveChange.debtIncrease = _boldChange;
        } else {
            _troveChange.debtDecrease = _boldChange;
        }
    }

    function adjustTrove(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        uint256 _maxUpfrontFee
    ) external override {
        ITroveManager troveManagerCached = troveManager;
        _requireTroveIsActive(troveManagerCached, _troveId);

        TroveChange memory troveChange;
        _initTroveChange(troveChange, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease);
        _adjustTrove(troveManagerCached, _troveId, troveChange, _maxUpfrontFee);
    }

    function adjustZombieTrove(
        uint256 _troveId,
        uint256 _collChange,
        bool _isCollIncrease,
        uint256 _boldChange,
        bool _isDebtIncrease,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external override {
        ITroveManager troveManagerCached = troveManager;
        _requireTroveIsZombie(troveManagerCached, _troveId);

        TroveChange memory troveChange;
        _initTroveChange(troveChange, _collChange, _isCollIncrease, _boldChange, _isDebtIncrease);
        _adjustTrove(troveManagerCached, _troveId, troveChange, _maxUpfrontFee);

        troveManagerCached.setTroveStatusToActive(_troveId);

        address batchManager = interestBatchManagerOf[_troveId];
        uint256 batchAnnualInterestRate;
        if (batchManager != address(0)) {
            LatestBatchData memory batch = troveManagerCached.getLatestBatchData(batchManager);
            batchAnnualInterestRate = batch.annualInterestRate;
        }
        _reInsertIntoSortedTroves(
            _troveId,
            troveManagerCached.getTroveAnnualInterestRate(_troveId),
            _upperHint,
            _lowerHint,
            batchManager,
            batchAnnualInterestRate
        );
    }

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

        ITroveManager troveManagerCached = troveManager;

        _requireValidAnnualInterestRate(_newAnnualInterestRate);
        _requireIsNotInBatch(_troveId);
        _requireSenderIsOwnerOrInterestManager(_troveId);
        _requireTroveIsActive(troveManagerCached, _troveId);

        LatestTroveData memory trove = troveManagerCached.getLatestTroveData(_troveId);
        _requireValidDelegateAdustment(_troveId, trove.lastInterestRateAdjTime, _newAnnualInterestRate);
        _requireAnnualInterestRateIsNew(trove.annualInterestRate, _newAnnualInterestRate);

        uint256 newDebt = trove.entireDebt;

        TroveChange memory troveChange;
        troveChange.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
        troveChange.appliedRedistCollGain = trove.redistCollGain;
        troveChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
        troveChange.oldWeightedRecordedDebt = trove.weightedRecordedDebt;

        // Apply upfront fee on premature adjustments
        if (
            trove.annualInterestRate != _newAnnualInterestRate
                && block.timestamp < trove.lastInterestRateAdjTime + INTEREST_RATE_ADJ_COOLDOWN
        ) {
            newDebt = _applyUpfrontFee(trove.entireColl, newDebt, troveChange, _maxUpfrontFee);
        }

        // Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
        troveChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;

        activePool.mintAggInterestAndAccountForTroveChange(troveChange, address(0));

        sortedTroves.reInsert(_troveId, _newAnnualInterestRate, _upperHint, _lowerHint);
        troveManagerCached.onAdjustTroveInterestRate(
            _troveId, trove.entireColl, newDebt, _newAnnualInterestRate, troveChange
        );
    }

    /*
    * _adjustTrove(): Alongside a debt change, this function can perform either a collateral top-up or a collateral withdrawal.
    */
    function _adjustTrove(
        ITroveManager _troveManager,
        uint256 _troveId,
        TroveChange memory _troveChange,
        uint256 _maxUpfrontFee
    ) internal {
        _requireIsNotShutDown();

        LocalVariables_adjustTrove memory vars;
        vars.activePool = activePool;
        vars.boldToken = boldToken;

        vars.price = _requireOraclesLive();
        vars.isBelowCriticalThreshold = _checkBelowCriticalThreshold(vars.price, CCR);

        // --- Checks ---

        _requireTroveIsOpen(_troveManager, _troveId);

        address owner = troveNFT.ownerOf(_troveId);
        address receiver = owner; // If it’s a withdrawal, and manager has receive privilege, manager would be the receiver

        if (_troveChange.collDecrease > 0 || _troveChange.debtIncrease > 0) {
            receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
        }

        if (_troveChange.collIncrease > 0 || _troveChange.debtDecrease > 0) {
            _requireSenderIsOwnerOrAddManager(_troveId, owner);
        }

        vars.trove = _troveManager.getLatestTroveData(_troveId);

        // When the adjustment is a debt repayment, check it's a valid amount and that the caller has enough Bold
        if (_troveChange.debtDecrease > 0) {
            uint256 maxRepayment = vars.trove.entireDebt > MIN_DEBT ? vars.trove.entireDebt - MIN_DEBT : 0;
            if (_troveChange.debtDecrease > maxRepayment) {
                _troveChange.debtDecrease = maxRepayment;
            }
            _requireSufficientBoldBalance(vars.boldToken, msg.sender, _troveChange.debtDecrease);
        }

        _requireNonZeroAdjustment(_troveChange);

        // When the adjustment is a collateral withdrawal, check that it's no more than the Trove's entire collateral
        if (_troveChange.collDecrease > 0) {
            _requireValidCollWithdrawal(vars.trove.entireColl, _troveChange.collDecrease);
        }

        vars.newColl = vars.trove.entireColl + _troveChange.collIncrease - _troveChange.collDecrease;
        vars.newDebt = vars.trove.entireDebt + _troveChange.debtIncrease - _troveChange.debtDecrease;

        address batchManager = interestBatchManagerOf[_troveId];
        bool isTroveInBatch = batchManager != address(0);
        LatestBatchData memory batch;
        uint256 batchFutureDebt;
        if (isTroveInBatch) {
            batch = _troveManager.getLatestBatchData(batchManager);

            batchFutureDebt = batch.entireDebtWithoutRedistribution + vars.trove.redistBoldDebtGain
                + _troveChange.debtIncrease - _troveChange.debtDecrease;

            _troveChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
            _troveChange.appliedRedistCollGain = vars.trove.redistCollGain;
            _troveChange.batchAccruedManagementFee = batch.accruedManagementFee;
            _troveChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
            _troveChange.newWeightedRecordedDebt = batchFutureDebt * batch.annualInterestRate;
            _troveChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
            _troveChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * batch.annualManagementFee;
        } else {
            _troveChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
            _troveChange.appliedRedistCollGain = vars.trove.redistCollGain;
            _troveChange.oldWeightedRecordedDebt = vars.trove.weightedRecordedDebt;
            _troveChange.newWeightedRecordedDebt = vars.newDebt * vars.trove.annualInterestRate;
        }

        // Pay an upfront fee on debt increases
        if (_troveChange.debtIncrease > 0) {
            uint256 avgInterestRate = vars.activePool.getNewApproxAvgInterestRateFromTroveChange(_troveChange);
            _troveChange.upfrontFee = _calcUpfrontFee(_troveChange.debtIncrease, avgInterestRate);
            _requireUserAcceptsUpfrontFee(_troveChange.upfrontFee, _maxUpfrontFee);

            vars.newDebt += _troveChange.upfrontFee;
            if (isTroveInBatch) {
                batchFutureDebt += _troveChange.upfrontFee;
                // Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
                _troveChange.newWeightedRecordedDebt = batchFutureDebt * batch.annualInterestRate;
                _troveChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * batch.annualManagementFee;
            } else {
                // Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
                _troveChange.newWeightedRecordedDebt = vars.newDebt * vars.trove.annualInterestRate;
            }
        }

        // Make sure the Trove doesn't end up zombie
        // Now the max repayment is capped to stay above MIN_DEBT, so this only applies to adjustZombieTrove
        _requireAtLeastMinDebt(vars.newDebt);

        vars.newICR = LiquityMath._computeCR(vars.newColl, vars.newDebt, vars.price);

        // Check the adjustment satisfies all conditions for the current system mode
        _requireValidAdjustmentInCurrentMode(_troveChange, vars);

        // --- Effects and interactions ---

        if (isTroveInBatch) {
            _troveManager.onAdjustTroveInsideBatch(
                _troveId,
                vars.newColl,
                vars.newDebt,
                _troveChange,
                batchManager,
                batch.entireCollWithoutRedistribution,
                batch.entireDebtWithoutRedistribution
            );
        } else {
            _troveManager.onAdjustTrove(_troveId, vars.newColl, vars.newDebt, _troveChange);
        }

        vars.activePool.mintAggInterestAndAccountForTroveChange(_troveChange, batchManager);
        _moveTokensFromAdjustment(receiver, _troveChange, vars.boldToken, vars.activePool);
    }

    function closeTrove(uint256 _troveId) external override {
        ITroveManager troveManagerCached = troveManager;
        IActivePool activePoolCached = activePool;
        IBoldToken boldTokenCached = boldToken;

        // --- Checks ---

        address owner = troveNFT.ownerOf(_troveId);
        address receiver = _requireSenderIsOwnerOrRemoveManagerAndGetReceiver(_troveId, owner);
        _requireTroveIsOpen(troveManagerCached, _troveId);

        LatestTroveData memory trove = troveManagerCached.getLatestTroveData(_troveId);

        // The borrower must repay their entire debt including accrued interest, batch fee and redist. gains
        _requireSufficientBoldBalance(boldTokenCached, msg.sender, trove.entireDebt);

        TroveChange memory troveChange;
        troveChange.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
        troveChange.appliedRedistCollGain = trove.redistCollGain;
        troveChange.collDecrease = trove.entireColl;
        troveChange.debtDecrease = trove.entireDebt;

        address batchManager = interestBatchManagerOf[_troveId];
        LatestBatchData memory batch;
        if (batchManager != address(0)) {
            batch = troveManagerCached.getLatestBatchData(batchManager);
            uint256 batchFutureDebt =
                batch.entireDebtWithoutRedistribution - (trove.entireDebt - trove.redistBoldDebtGain);
            troveChange.batchAccruedManagementFee = batch.accruedManagementFee;
            troveChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
            troveChange.newWeightedRecordedDebt = batchFutureDebt * batch.annualInterestRate;
            troveChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
            troveChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * batch.annualManagementFee;
        } else {
            troveChange.oldWeightedRecordedDebt = trove.weightedRecordedDebt;
            // troveChange.newWeightedRecordedDebt = 0;
        }

        (uint256 price,) = priceFeed.fetchPrice();
        uint256 newTCR = _getNewTCRFromTroveChange(troveChange, price);
        if (!hasBeenShutDown) _requireNewTCRisAboveCCR(newTCR);

        troveManagerCached.onCloseTrove(
            _troveId,
            troveChange,
            batchManager,
            batch.entireCollWithoutRedistribution,
            batch.entireDebtWithoutRedistribution
        );

        // If trove is in batch
        if (batchManager != address(0)) {
            // Unlink here in BorrowerOperations
            interestBatchManagerOf[_troveId] = address(0);
        }

        activePoolCached.mintAggInterestAndAccountForTroveChange(troveChange, batchManager);

        // Return ETH gas compensation
        WETH.transferFrom(gasPoolAddress, receiver, ETH_GAS_COMPENSATION);
        // Burn the remainder of the Trove's entire debt from the user
        boldTokenCached.burn(msg.sender, trove.entireDebt);

        // Send the collateral back to the user
        activePoolCached.sendColl(receiver, trove.entireColl);

        _wipeTroveMappings(_troveId);
    }

    function applyPendingDebt(uint256 _troveId, uint256 _lowerHint, uint256 _upperHint) public {
        _requireIsNotShutDown();

        ITroveManager troveManagerCached = troveManager;

        _requireTroveIsOpen(troveManagerCached, _troveId);

        LatestTroveData memory trove = troveManagerCached.getLatestTroveData(_troveId);
        _requireNonZeroDebt(trove.entireDebt);

        TroveChange memory change;
        change.appliedRedistBoldDebtGain = trove.redistBoldDebtGain;
        change.appliedRedistCollGain = trove.redistCollGain;

        address batchManager = interestBatchManagerOf[_troveId];
        LatestBatchData memory batch;

        if (batchManager == address(0)) {
            change.oldWeightedRecordedDebt = trove.weightedRecordedDebt;
            change.newWeightedRecordedDebt = trove.entireDebt * trove.annualInterestRate;
        } else {
            batch = troveManagerCached.getLatestBatchData(batchManager);
            change.batchAccruedManagementFee = batch.accruedManagementFee;
            change.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
            change.newWeightedRecordedDebt =
                (batch.entireDebtWithoutRedistribution + trove.redistBoldDebtGain) * batch.annualInterestRate;
            change.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
            change.newWeightedRecordedBatchManagementFee =
                (batch.entireDebtWithoutRedistribution + trove.redistBoldDebtGain) * batch.annualManagementFee;
        }

        troveManagerCached.onApplyTroveInterest(
            _troveId,
            trove.entireColl,
            trove.entireDebt,
            batchManager,
            batch.entireCollWithoutRedistribution,
            batch.entireDebtWithoutRedistribution,
            change
        );
        activePool.mintAggInterestAndAccountForTroveChange(change, batchManager);

        // If the trove was zombie, and now it’s not anymore, put it back in the list
        if (_checkTroveIsZombie(troveManagerCached, _troveId) && trove.entireDebt >= MIN_DEBT) {
            troveManagerCached.setTroveStatusToActive(_troveId);
            _reInsertIntoSortedTroves(
                _troveId, trove.annualInterestRate, _upperHint, _lowerHint, batchManager, batch.annualInterestRate
            );
        }
    }

    function getInterestIndividualDelegateOf(uint256 _troveId)
        external
        view
        returns (InterestIndividualDelegate memory)
    {
        return interestIndividualDelegateOf[_troveId];
    }

    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 {
        _requireIsNotShutDown();
        _requireTroveIsActive(troveManager, _troveId);
        _requireCallerIsBorrower(_troveId);
        _requireValidAnnualInterestRate(_minInterestRate);
        _requireValidAnnualInterestRate(_maxInterestRate);
        // With the check below, it could only be ==
        _requireOrderedRange(_minInterestRate, _maxInterestRate);

        interestIndividualDelegateOf[_troveId] =
            InterestIndividualDelegate(_delegate, _minInterestRate, _maxInterestRate, _minInterestRateChangePeriod);
        // Can’t have both individual delegation and batch manager
        if (interestBatchManagerOf[_troveId] != address(0)) {
            // Not needed, implicitly checked in removeFromBatch
            //_requireValidAnnualInterestRate(_newAnnualInterestRate);
            removeFromBatch(_troveId, _newAnnualInterestRate, _upperHint, _lowerHint, _maxUpfrontFee);
        }
    }

    function removeInterestIndividualDelegate(uint256 _troveId) external {
        _requireCallerIsBorrower(_troveId);
        delete interestIndividualDelegateOf[_troveId];
    }

    function getInterestBatchManager(address _account) external view returns (InterestBatchManager memory) {
        return interestBatchManagers[_account];
    }

    function registerBatchManager(
        uint128 _minInterestRate,
        uint128 _maxInterestRate,
        uint128 _currentInterestRate,
        uint128 _annualManagementFee,
        uint128 _minInterestRateChangePeriod
    ) external {
        _requireIsNotShutDown();
        _requireNonExistentInterestBatchManager(msg.sender);
        _requireValidAnnualInterestRate(_minInterestRate);
        _requireValidAnnualInterestRate(_maxInterestRate);
        // With the check below, it could only be ==
        _requireOrderedRange(_minInterestRate, _maxInterestRate);
        _requireInterestRateInRange(_currentInterestRate, _minInterestRate, _maxInterestRate);
        // Not needed, implicitly checked in the condition above:
        //_requireValidAnnualInterestRate(_currentInterestRate);
        if (_annualManagementFee > MAX_ANNUAL_BATCH_MANAGEMENT_FEE) revert AnnualManagementFeeTooHigh();
        if (_minInterestRateChangePeriod < MIN_INTEREST_RATE_CHANGE_PERIOD) revert MinInterestRateChangePeriodTooLow();

        interestBatchManagers[msg.sender] =
            InterestBatchManager(_minInterestRate, _maxInterestRate, _minInterestRateChangePeriod);

        troveManager.onRegisterBatchManager(msg.sender, _currentInterestRate, _annualManagementFee);
    }

    function lowerBatchManagementFee(uint256 _newAnnualManagementFee) external {
        _requireIsNotShutDown();
        _requireValidInterestBatchManager(msg.sender);

        ITroveManager troveManagerCached = troveManager;

        LatestBatchData memory batch = troveManagerCached.getLatestBatchData(msg.sender);
        if (_newAnnualManagementFee >= batch.annualManagementFee) {
            revert NewFeeNotLower();
        }

        // Lower batch fee on TM
        troveManagerCached.onLowerBatchManagerAnnualFee(
            msg.sender,
            batch.entireCollWithoutRedistribution,
            batch.entireDebtWithoutRedistribution,
            _newAnnualManagementFee
        );

        // active pool mint
        TroveChange memory batchChange;
        batchChange.batchAccruedManagementFee = batch.accruedManagementFee;
        batchChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
        batchChange.newWeightedRecordedDebt = batch.entireDebtWithoutRedistribution * batch.annualInterestRate;
        batchChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
        batchChange.newWeightedRecordedBatchManagementFee =
            batch.entireDebtWithoutRedistribution * _newAnnualManagementFee;

        activePool.mintAggInterestAndAccountForTroveChange(batchChange, msg.sender);
    }

    function setBatchManagerAnnualInterestRate(
        uint128 _newAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) external {
        _requireIsNotShutDown();
        _requireValidInterestBatchManager(msg.sender);
        _requireInterestRateInBatchManagerRange(msg.sender, _newAnnualInterestRate);
        // Not needed, implicitly checked in the condition above:
        //_requireValidAnnualInterestRate(_newAnnualInterestRate);

        ITroveManager troveManagerCached = troveManager;
        IActivePool activePoolCached = activePool;

        LatestBatchData memory batch = troveManagerCached.getLatestBatchData(msg.sender);
        _requireBatchInterestRateChangePeriodPassed(msg.sender, uint256(batch.lastInterestRateAdjTime));

        uint256 newDebt = batch.entireDebtWithoutRedistribution;

        TroveChange memory batchChange;
        batchChange.batchAccruedManagementFee = batch.accruedManagementFee;
        batchChange.oldWeightedRecordedDebt = batch.weightedRecordedDebt;
        batchChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
        batchChange.oldWeightedRecordedBatchManagementFee = batch.weightedRecordedBatchManagementFee;
        batchChange.newWeightedRecordedBatchManagementFee = newDebt * batch.annualManagementFee;

        // Apply upfront fee on premature adjustments
        if (
            batch.annualInterestRate != _newAnnualInterestRate
                && block.timestamp < batch.lastInterestRateAdjTime + INTEREST_RATE_ADJ_COOLDOWN
        ) {
            uint256 price = _requireOraclesLive();

            uint256 avgInterestRate = activePoolCached.getNewApproxAvgInterestRateFromTroveChange(batchChange);
            batchChange.upfrontFee = _calcUpfrontFee(newDebt, avgInterestRate);
            _requireUserAcceptsUpfrontFee(batchChange.upfrontFee, _maxUpfrontFee);

            newDebt += batchChange.upfrontFee;

            // Recalculate the batch's weighted terms, now taking into account the upfront fee
            batchChange.newWeightedRecordedDebt = newDebt * _newAnnualInterestRate;
            batchChange.newWeightedRecordedBatchManagementFee = newDebt * batch.annualManagementFee;

            // Disallow a premature adjustment if it would result in TCR < CCR
            // (which includes the case when TCR is already below CCR before the adjustment).
            uint256 newTCR = _getNewTCRFromTroveChange(batchChange, price);
            _requireNewTCRisAboveCCR(newTCR);
        }

        activePoolCached.mintAggInterestAndAccountForTroveChange(batchChange, msg.sender);

        // Check batch is not empty, and then reinsert in sorted list
        if (!sortedTroves.isEmptyBatch(BatchId.wrap(msg.sender))) {
            sortedTroves.reInsertBatch(BatchId.wrap(msg.sender), _newAnnualInterestRate, _upperHint, _lowerHint);
        }

        troveManagerCached.onSetBatchManagerAnnualInterestRate(
            msg.sender, batch.entireCollWithoutRedistribution, newDebt, _newAnnualInterestRate, batchChange.upfrontFee
        );
    }

    function setInterestBatchManager(
        uint256 _troveId,
        address _newBatchManager,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) public override {
        _requireIsNotShutDown();
        LocalVariables_setInterestBatchManager memory vars;
        vars.troveManager = troveManager;
        vars.activePool = activePool;
        vars.sortedTroves = sortedTroves;

        _requireTroveIsActive(vars.troveManager, _troveId);
        _requireCallerIsBorrower(_troveId);
        _requireValidInterestBatchManager(_newBatchManager);
        _requireIsNotInBatch(_troveId);

        interestBatchManagerOf[_troveId] = _newBatchManager;
        // Can’t have both individual delegation and batch manager
        if (interestIndividualDelegateOf[_troveId].account != address(0)) delete interestIndividualDelegateOf[_troveId];

        vars.trove = vars.troveManager.getLatestTroveData(_troveId);
        vars.newBatch = vars.troveManager.getLatestBatchData(_newBatchManager);

        TroveChange memory newBatchTroveChange;
        newBatchTroveChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
        newBatchTroveChange.appliedRedistCollGain = vars.trove.redistCollGain;
        newBatchTroveChange.batchAccruedManagementFee = vars.newBatch.accruedManagementFee;
        newBatchTroveChange.oldWeightedRecordedDebt =
            vars.newBatch.weightedRecordedDebt + vars.trove.weightedRecordedDebt;
        newBatchTroveChange.newWeightedRecordedDebt =
            (vars.newBatch.entireDebtWithoutRedistribution + vars.trove.entireDebt) * vars.newBatch.annualInterestRate;

        // An upfront fee is always charged upon joining a batch to ensure that borrowers can not game the fee logic
        // and gain free interest rate updates (e.g. if they also manage the batch they joined)
        vars.trove.entireDebt =
            _applyUpfrontFee(vars.trove.entireColl, vars.trove.entireDebt, newBatchTroveChange, _maxUpfrontFee);

        // Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
        newBatchTroveChange.newWeightedRecordedDebt =
            (vars.newBatch.entireDebtWithoutRedistribution + vars.trove.entireDebt) * vars.newBatch.annualInterestRate;

        // Add batch fees
        newBatchTroveChange.oldWeightedRecordedBatchManagementFee = vars.newBatch.weightedRecordedBatchManagementFee;
        newBatchTroveChange.newWeightedRecordedBatchManagementFee =
            (vars.newBatch.entireDebtWithoutRedistribution + vars.trove.entireDebt) * vars.newBatch.annualManagementFee;
        vars.activePool.mintAggInterestAndAccountForTroveChange(newBatchTroveChange, _newBatchManager);

        vars.troveManager.onSetInterestBatchManager(
            ITroveManager.OnSetInterestBatchManagerParams({
                troveId: _troveId,
                troveColl: vars.trove.entireColl,
                troveDebt: vars.trove.entireDebt,
                troveChange: newBatchTroveChange,
                newBatchAddress: _newBatchManager,
                newBatchColl: vars.newBatch.entireCollWithoutRedistribution,
                newBatchDebt: vars.newBatch.entireDebtWithoutRedistribution
            })
        );

        vars.sortedTroves.remove(_troveId);
        vars.sortedTroves.insertIntoBatch(
            _troveId, BatchId.wrap(_newBatchManager), vars.newBatch.annualInterestRate, _upperHint, _lowerHint
        );
    }

    function removeFromBatch(
        uint256 _troveId,
        uint256 _newAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        uint256 _maxUpfrontFee
    ) public override {
        _requireIsNotShutDown();

        LocalVariables_removeFromBatch memory vars;
        vars.troveManager = troveManager;
        vars.sortedTroves = sortedTroves;

        _requireTroveIsActive(vars.troveManager, _troveId);
        _requireCallerIsBorrower(_troveId);
        _requireValidAnnualInterestRate(_newAnnualInterestRate);

        vars.batchManager = _requireIsInBatch(_troveId);
        delete interestBatchManagerOf[_troveId];

        // Remove trove from Batch in SortedTroves
        vars.sortedTroves.removeFromBatch(_troveId);
        // Reinsert as single trove
        vars.sortedTroves.insert(_troveId, _newAnnualInterestRate, _upperHint, _lowerHint);

        vars.trove = vars.troveManager.getLatestTroveData(_troveId);
        vars.batch = vars.troveManager.getLatestBatchData(vars.batchManager);

        uint256 batchFutureDebt =
            vars.batch.entireDebtWithoutRedistribution - (vars.trove.entireDebt - vars.trove.redistBoldDebtGain);

        TroveChange memory batchChange;
        batchChange.appliedRedistBoldDebtGain = vars.trove.redistBoldDebtGain;
        batchChange.appliedRedistCollGain = vars.trove.redistCollGain;
        batchChange.batchAccruedManagementFee = vars.batch.accruedManagementFee;
        batchChange.oldWeightedRecordedDebt = vars.batch.weightedRecordedDebt;
        batchChange.newWeightedRecordedDebt =
            batchFutureDebt * vars.batch.annualInterestRate + vars.trove.entireDebt * _newAnnualInterestRate;

        // Apply upfront fee on premature adjustments
        if (
            vars.batch.annualInterestRate != _newAnnualInterestRate
                && block.timestamp < vars.trove.lastInterestRateAdjTime + INTEREST_RATE_ADJ_COOLDOWN
        ) {
            vars.trove.entireDebt =
                _applyUpfrontFee(vars.trove.entireColl, vars.trove.entireDebt, batchChange, _maxUpfrontFee);
        }

        // Recalculate newWeightedRecordedDebt, now taking into account the upfront fee
        batchChange.newWeightedRecordedDebt =
            batchFutureDebt * vars.batch.annualInterestRate + vars.trove.entireDebt * _newAnnualInterestRate;
        // Add batch fees
        batchChange.oldWeightedRecordedBatchManagementFee = vars.batch.weightedRecordedBatchManagementFee;
        batchChange.newWeightedRecordedBatchManagementFee = batchFutureDebt * vars.batch.annualManagementFee;

        activePool.mintAggInterestAndAccountForTroveChange(batchChange, vars.batchManager);

        vars.troveManager.onRemoveFromBatch(
            _troveId,
            vars.trove.entireColl,
            vars.trove.entireDebt,
            batchChange,
            vars.batchManager,
            vars.batch.entireCollWithoutRedistribution,
            vars.batch.entireDebtWithoutRedistribution,
            _newAnnualInterestRate
        );
    }

    function switchBatchManager(
        uint256 _troveId,
        uint256 _removeUpperHint,
        uint256 _removeLowerHint,
        address _newBatchManager,
        uint256 _addUpperHint,
        uint256 _addLowerHint,
        uint256 _maxUpfrontFee
    ) external override {
        address oldBatchManager = _requireIsInBatch(_troveId);
        _requireNewInterestBatchManager(oldBatchManager, _newBatchManager);

        LatestBatchData memory oldBatch = troveManager.getLatestBatchData(oldBatchManager);

        removeFromBatch(_troveId, oldBatch.annualInterestRate, _removeUpperHint, _removeLowerHint, 0);
        setInterestBatchManager(_troveId, _newBatchManager, _addUpperHint, _addLowerHint, _maxUpfrontFee);
    }

    function _applyUpfrontFee(
        uint256 _troveEntireColl,
        uint256 _troveEntireDebt,
        TroveChange memory _troveChange,
        uint256 _maxUpfrontFee
    ) internal returns (uint256) {
        uint256 price = _requireOraclesLive();

        uint256 avgInterestRate = activePool.getNewApproxAvgInterestRateFromTroveChange(_troveChange);
        _troveChange.upfrontFee = _calcUpfrontFee(_troveEntireDebt, avgInterestRate);
        _requireUserAcceptsUpfrontFee(_troveChange.upfrontFee, _maxUpfrontFee);

        _troveEntireDebt += _troveChange.upfrontFee;

        // ICR is based on the requested Bold amount + upfront fee.
        uint256 newICR = LiquityMath._computeCR(_troveEntireColl, _troveEntireDebt, price);
        _requireICRisAboveMCR(newICR);

        // Disallow a premature adjustment if it would result in TCR < CCR
        // (which includes the case when TCR is already below CCR before the adjustment).
        uint256 newTCR = _getNewTCRFromTroveChange(_troveChange, price);
        _requireNewTCRisAboveCCR(newTCR);

        return _troveEntireDebt;
    }

    function _calcUpfrontFee(uint256 _debt, uint256 _avgInterestRate) internal pure returns (uint256) {
        return _calcInterest(_debt * _avgInterestRate, UPFRONT_INTEREST_PERIOD);
    }

    // Call from TM to clean state here
    function onLiquidateTrove(uint256 _troveId) external {
        _requireCallerIsTroveManager();

        _wipeTroveMappings(_troveId);
    }

    function _wipeTroveMappings(uint256 _troveId) internal {
        delete interestIndividualDelegateOf[_troveId];
        delete interestBatchManagerOf[_troveId];
        _wipeAddRemoveManagers(_troveId);
    }

    /**
     * Claim remaining collateral from a liquidation with ICR exceeding the liquidation penalty
     */
    function claimCollateral() external override {
        // send coll from CollSurplus Pool to owner
        collSurplusPool.claimColl(msg.sender);
    }

    function shutdown() external {
        if (hasBeenShutDown) revert IsShutDown();

        uint256 totalColl = getEntireSystemColl();
        uint256 totalDebt = getEntireSystemDebt();
        (uint256 price, bool newOracleFailureDetected) = priceFeed.fetchPrice();
        // If the oracle failed, the above call to PriceFeed will have shut this branch down
        if (newOracleFailureDetected) return;

        // Otherwise, proceed with the TCR check:
        uint256 TCR = LiquityMath._computeCR(totalColl, totalDebt, price);
        if (TCR >= SCR) revert TCRNotBelowSCR();

        _applyShutdown();

        emit ShutDown(TCR);
    }

    // Not technically a "Borrower op", but seems best placed here given current shutdown logic.
    function shutdownFromOracleFailure() external {
        _requireCallerIsPriceFeed();

        // No-op rather than revert here, so that the outer function call which fetches the price does not revert
        // if the system is already shut down.
        if (hasBeenShutDown) return;

        _applyShutdown();
    }

    function _applyShutdown() internal {
        activePool.mintAggInterest();
        hasBeenShutDown = true;
        troveManager.shutdown();
    }

    // --- Helper functions ---

    function _reInsertIntoSortedTroves(
        uint256 _troveId,
        uint256 _troveAnnualInterestRate,
        uint256 _upperHint,
        uint256 _lowerHint,
        address _batchManager,
        uint256 _batchAnnualInterestRate
    ) internal {
        // If it was in a batch, we need to put it back, otherwise we insert it normally
        if (_batchManager == address(0)) {
            sortedTroves.insert(_troveId, _troveAnnualInterestRate, _upperHint, _lowerHint);
        } else {
            sortedTroves.insertIntoBatch(
                _troveId, BatchId.wrap(_batchManager), _batchAnnualInterestRate, _upperHint, _lowerHint
            );
        }
    }

    // This function mints the BOLD corresponding to the borrower's chosen debt increase
    // (it does not mint the accrued interest).
    function _moveTokensFromAdjustment(
        address withdrawalReceiver,
        TroveChange memory _troveChange,
        IBoldToken _boldToken,
        IActivePool _activePool
    ) internal {
        if (_troveChange.debtIncrease > 0) {
            _boldToken.mint(withdrawalReceiver, _troveChange.debtIncrease);
        } else if (_troveChange.debtDecrease > 0) {
            _boldToken.burn(msg.sender, _troveChange.debtDecrease);
        }

        if (_troveChange.collIncrease > 0) {
            // Pull coll tokens from sender and move them to the Active Pool
            _pullCollAndSendToActivePool(_activePool, _troveChange.collIncrease);
        } else if (_troveChange.collDecrease > 0) {
            // Pull Coll from Active Pool and decrease its recorded Coll balance
            _activePool.sendColl(withdrawalReceiver, _troveChange.collDecrease);
        }
    }

    function _pullCollAndSendToActivePool(IActivePool _activePool, uint256 _amount) internal {
        // Send Coll tokens from sender to active pool
        collToken.safeTransferFrom(msg.sender, address(_activePool), _amount);
        // Make sure Active Pool accountancy is right
        _activePool.accountForReceivedColl(_amount);
    }

    function checkBatchManagerExists(address _batchManager) external view returns (bool) {
        return interestBatchManagers[_batchManager].maxInterestRate > 0;
    }

    // --- 'Require' wrapper functions ---

    function _requireIsNotShutDown() internal view {
        if (hasBeenShutDown) {
            revert IsShutDown();
        }
    }

    function _requireNonZeroAdjustment(TroveChange memory _troveChange) internal pure {
        if (
            _troveChange.collIncrease == 0 && _troveChange.collDecrease == 0 && _troveChange.debtIncrease == 0
                && _troveChange.debtDecrease == 0
        ) {
            revert ZeroAdjustment();
        }
    }

    function _requireSenderIsOwnerOrInterestManager(uint256 _troveId) internal view {
        address owner = troveNFT.ownerOf(_troveId);
        if (msg.sender != owner && msg.sender != interestIndividualDelegateOf[_troveId].account) {
            revert NotOwnerNorInterestManager();
        }
    }

    function _requireValidDelegateAdustment(
        uint256 _troveId,
        uint256 _lastInterestRateAdjTime,
        uint256 _annualInterestRate
    ) internal view {
        InterestIndividualDelegate memory individualDelegate = interestIndividualDelegateOf[_troveId];
        // We have previously checked that sender is either owner or delegate
        // If it’s owner, this restriction doesn’t apply
        if (individualDelegate.account == msg.sender) {
            _requireInterestRateInRange(
                _annualInterestRate, individualDelegate.minInterestRate, individualDelegate.maxInterestRate
            );
            _requireDelegateInterestRateChangePeriodPassed(
                _lastInterestRateAdjTime, individualDelegate.minInterestRateChangePeriod
            );
        }
    }

    function _requireIsNotInBatch(uint256 _troveId) internal view {
        if (interestBatchManagerOf[_troveId] != address(0)) {
            revert TroveInBatch();
        }
    }

    function _requireIsInBatch(uint256 _troveId) internal view returns (address) {
        address batchManager = interestBatchManagerOf[_troveId];
        if (batchManager == address(0)) {
            revert TroveNotInBatch();
        }

        return batchManager;
    }

    function _requireTroveDoesNotExists(ITroveManager _troveManager, uint256 _troveId) internal view {
        ITroveManager.Status status = _troveManager.getTroveStatus(_troveId);
        if (status != ITroveManager.Status.nonExistent) {
            revert TroveExists();
        }
    }

    function _requireTroveIsOpen(ITroveManager _troveManager, uint256 _troveId) internal view {
        ITroveManager.Status status = _troveManager.getTroveStatus(_troveId);
        if (status != ITroveManager.Status.active && status != ITroveManager.Status.zombie) {
            revert TroveNotOpen();
        }
    }

    function _requireTroveIsActive(ITroveManager _troveManager, uint256 _troveId) internal view {
        ITroveManager.Status status = _troveManager.getTroveStatus(_troveId);
        if (status != ITroveManager.Status.active) {
            revert TroveNotActive();
        }
    }

    function _requireTroveIsZombie(ITroveManager _troveManager, uint256 _troveId) internal view {
        if (!_checkTroveIsZombie(_troveManager, _troveId)) {
            revert TroveNotZombie();
        }
    }

    function _checkTroveIsZombie(ITroveManager _troveManager, uint256 _troveId) internal view returns (bool) {
        ITroveManager.Status status = _troveManager.getTroveStatus(_troveId);
        return status == ITroveManager.Status.zombie;
    }

    function _requireNonZeroDebt(uint256 _troveDebt) internal pure {
        if (_troveDebt == 0) {
            revert TroveWithZeroDebt();
        }
    }

    function _requireUserAcceptsUpfrontFee(uint256 _fee, uint256 _maxFee) internal pure {
        if (_fee > _maxFee) {
            revert UpfrontFeeTooHigh();
        }
    }

    function _requireValidAdjustmentInCurrentMode(
        TroveChange memory _troveChange,
        LocalVariables_adjustTrove memory _vars
    ) internal view {
        /*
        * Below Critical Threshold, it is not permitted:
        *
        * - Borrowing, unless it brings TCR up to CCR again
        * - Collateral withdrawal except accompanied by a debt repayment of at least the same value
        *
        * In Normal Mode, ensure:
        *
        * - The adjustment won't pull the TCR below CCR
        *
        * In Both cases:
        * - The new ICR is above MCR
        */
        _requireICRisAboveMCR(_vars.newICR);

        uint256 newTCR = _getNewTCRFromTroveChange(_troveChange, _vars.price);
        if (_vars.isBelowCriticalThreshold) {
            _requireNoBorrowingUnlessNewTCRisAboveCCR(_troveChange.debtIncrease, newTCR);
            _requireDebtRepaymentGeCollWithdrawal(_troveChange, _vars.price);
        } else {
            // if Normal Mode
            _requireNewTCRisAboveCCR(newTCR);
        }
    }

    function _requireICRisAboveMCR(uint256 _newICR) internal view {
        if (_newICR < MCR) {
            revert ICRBelowMCR();
        }
    }

    function _requireNoBorrowingUnlessNewTCRisAboveCCR(uint256 _debtIncrease, uint256 _newTCR) internal view {
        if (_debtIncrease > 0 && _newTCR < CCR) {
            revert TCRBelowCCR();
        }
    }

    function _requireDebtRepaymentGeCollWithdrawal(TroveChange memory _troveChange, uint256 _price) internal pure {
        if ((_troveChange.debtDecrease * DECIMAL_PRECISION < _troveChange.collDecrease * _price)) {
            revert RepaymentNotMatchingCollWithdrawal();
        }
    }

    function _requireNewTCRisAboveCCR(uint256 _newTCR) internal view {
        if (_newTCR < CCR) {
            revert TCRBelowCCR();
        }
    }

    function _requireAtLeastMinDebt(uint256 _debt) internal pure {
        if (_debt < MIN_DEBT) {
            revert DebtBelowMin();
        }
    }

    function _requireValidCollWithdrawal(uint256 _currentColl, uint256 _collWithdrawal) internal pure {
        if (_collWithdrawal > _currentColl) {
            revert CollWithdrawalTooHigh();
        }
    }

    function _requireSufficientBoldBalance(IBoldToken _boldToken, address _borrower, uint256 _debtRepayment)
        internal
        view
    {
        if (_boldToken.balanceOf(_borrower) < _debtRepayment) {
            revert NotEnoughBoldBalance();
        }
    }

    function _requireValidAnnualInterestRate(uint256 _annualInterestRate) internal pure {
        if (_annualInterestRate < MIN_ANNUAL_INTEREST_RATE) {
            revert InterestRateTooLow();
        }
        if (_annualInterestRate > MAX_ANNUAL_INTEREST_RATE) {
            revert InterestRateTooHigh();
        }
    }

    function _requireAnnualInterestRateIsNew(uint256 _oldAnnualInterestRate, uint256 _newAnnualInterestRate)
        internal
        pure
    {
        if (_oldAnnualInterestRate == _newAnnualInterestRate) {
            revert InterestRateNotNew();
        }
    }

    function _requireOrderedRange(uint256 _minInterestRate, uint256 _maxInterestRate) internal pure {
        if (_minInterestRate >= _maxInterestRate) revert MinGeMax();
    }

    function _requireInterestRateInBatchManagerRange(address _interestBatchManagerAddress, uint256 _annualInterestRate)
        internal
        view
    {
        InterestBatchManager memory interestBatchManager = interestBatchManagers[_interestBatchManagerAddress];
        _requireInterestRateInRange(
            _annualInterestRate, interestBatchManager.minInterestRate, interestBatchManager.maxInterestRate
        );
    }

    function _requireInterestRateInRange(
        uint256 _annualInterestRate,
        uint256 _minInterestRate,
        uint256 _maxInterestRate
    ) internal pure {
        if (_minInterestRate > _annualInterestRate || _annualInterestRate > _maxInterestRate) {
            revert InterestNotInRange();
        }
    }

    function _requireBatchInterestRateChangePeriodPassed(
        address _interestBatchManagerAddress,
        uint256 _lastInterestRateAdjTime
    ) internal view {
        InterestBatchManager memory interestBatchManager = interestBatchManagers[_interestBatchManagerAddress];
        if (block.timestamp < _lastInterestRateAdjTime + uint256(interestBatchManager.minInterestRateChangePeriod)) {
            revert BatchInterestRateChangePeriodNotPassed();
        }
    }

    function _requireDelegateInterestRateChangePeriodPassed(
        uint256 _lastInterestRateAdjTime,
        uint256 _minInterestRateChangePeriod
    ) internal view {
        if (block.timestamp < _lastInterestRateAdjTime + _minInterestRateChangePeriod) {
            revert DelegateInterestRateChangePeriodNotPassed();
        }
    }

    function _requireValidInterestBatchManager(address _interestBatchManagerAddress) internal view {
        if (interestBatchManagers[_interestBatchManagerAddress].maxInterestRate == 0) {
            revert InvalidInterestBatchManager();
        }
    }

    function _requireNonExistentInterestBatchManager(address _interestBatchManagerAddress) internal view {
        if (interestBatchManagers[_interestBatchManagerAddress].maxInterestRate > 0) {
            revert BatchManagerExists();
        }
    }

    function _requireNewInterestBatchManager(address _oldBatchManagerAddress, address _newBatchManagerAddress)
        internal
        pure
    {
        if (_oldBatchManagerAddress == _newBatchManagerAddress) {
            revert BatchManagerNotNew();
        }
    }

    function _requireCallerIsTroveManager() internal view {
        if (msg.sender != address(troveManager)) {
            revert CallerNotTroveManager();
        }
    }

    function _requireCallerIsPriceFeed() internal view {
        if (msg.sender != address(priceFeed)) {
            revert CallerNotPriceFeed();
        }
    }

    function _requireOraclesLive() internal returns (uint256) {
        (uint256 price, bool newOracleFailureDetected) = priceFeed.fetchPrice();
        if (newOracleFailureDetected) {
            revert NewOracleFailureDetected();
        }

        return price;
    }

    // --- ICR and TCR getters ---

    function _getNewTCRFromTroveChange(TroveChange memory _troveChange, uint256 _price)
        internal
        view
        returns (uint256 newTCR)
    {
        uint256 totalColl = getEntireSystemColl();
        totalColl += _troveChange.collIncrease;
        totalColl -= _troveChange.collDecrease;

        uint256 totalDebt = getEntireSystemDebt();
        totalDebt += _troveChange.debtIncrease;
        totalDebt += _troveChange.upfrontFee;
        totalDebt -= _troveChange.debtDecrease;

        newTCR = LiquityMath._computeCR(totalColl, totalDebt, _price);
    }
}

File 2 of 50 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

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

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

File 3 of 50 : IBorrowerOperations.sol
// 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 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;
}

File 4 of 50 : IAddressesRegistry.sol
// 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 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;
}

File 5 of 50 : 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;

    // -- end of permissioned functions --
}

File 6 of 50 : IBoldToken.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import {IERC20Metadata} from "openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC5267} from "openzeppelin-contracts/contracts/interfaces/IERC5267.sol";

interface IBoldToken is IERC20Metadata, IERC5267 {
    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;
}

File 7 of 50 : ICollSurplusPool.sol
// 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;
}

File 8 of 50 : ISortedTroves.sol
// 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);
}

File 9 of 50 : LiquityBase.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.24;

import "./Constants.sol";
import "./LiquityMath.sol";
import "../Interfaces/IAddressesRegistry.sol";
import "../Interfaces/IActivePool.sol";
import "../Interfaces/IDefaultPool.sol";
import "../Interfaces/IPriceFeed.sol";
import "../Interfaces/ILiquityBase.sol";

/*
* Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and
* common functions.
*/
contract LiquityBase is ILiquityBase {
    IActivePool public activePool;
    IDefaultPool internal defaultPool;
    IPriceFeed internal priceFeed;

    event ActivePoolAddressChanged(address _newActivePoolAddress);
    event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
    event PriceFeedAddressChanged(address _newPriceFeedAddress);

    constructor(IAddressesRegistry _addressesRegistry) {
        activePool = _addressesRegistry.activePool();
        defaultPool = _addressesRegistry.defaultPool();
        priceFeed = _addressesRegistry.priceFeed();

        emit ActivePoolAddressChanged(address(activePool));
        emit DefaultPoolAddressChanged(address(defaultPool));
        emit PriceFeedAddressChanged(address(priceFeed));
    }
    // --- Gas compensation functions ---

    function getEntireSystemColl() public view returns (uint256 entireSystemColl) {
        uint256 activeColl = activePool.getCollBalance();
        uint256 liquidatedColl = defaultPool.getCollBalance();

        return activeColl + liquidatedColl;
    }

    function getEntireSystemDebt() public view returns (uint256 entireSystemDebt) {
        uint256 activeDebt = activePool.getBoldDebt();
        uint256 closedDebt = defaultPool.getBoldDebt();

        return activeDebt + closedDebt;
    }

    function _getTCR(uint256 _price) internal view returns (uint256 TCR) {
        uint256 entireSystemColl = getEntireSystemColl();
        uint256 entireSystemDebt = getEntireSystemDebt();

        TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price);

        return TCR;
    }

    function _checkBelowCriticalThreshold(uint256 _price, uint256 _CCR) internal view returns (bool) {
        uint256 TCR = _getTCR(_price);

        return TCR < _CCR;
    }

    function _calcInterest(uint256 _weightedDebt, uint256 _period) internal pure returns (uint256) {
        return _weightedDebt * _period / ONE_YEAR / DECIMAL_PRECISION;
    }
}

File 10 of 50 : AddRemoveManagers.sol
// 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.
     */
    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) {
            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)) {
            return _owner;
        }
        return receiver;
    }
}

File 11 of 50 : 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 12 of 50 : LatestBatchData.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

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

File 13 of 50 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

File 14 of 50 : IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

File 15 of 50 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) 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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

File 16 of 50 : ILiquityBase.sol
// 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 getEntireSystemDebt() external view returns (uint256);
    function getEntireSystemColl() external view returns (uint256);
}

File 17 of 50 : IAddRemoveManagers.sol
// 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);
}

File 18 of 50 : IPriceFeed.sol
// 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;
}

File 19 of 50 : IWETH.sol
// 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;
}

File 20 of 50 : IActivePool.sol
// 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);
    function interestRouter() external view returns (IInterestRouter);
    // 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;
}

File 21 of 50 : IDefaultPool.sol
// 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;
}

File 22 of 50 : IHintHelpers.sol
// 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);
}

File 23 of 50 : IMultiTroveGetter.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IMultiTroveGetter {
    struct CombinedTroveData {
        uint256 id;
        uint256 debt;
        uint256 coll;
        uint256 stake;
        uint256 annualInterestRate;
        uint256 lastDebtUpdateTime;
        uint256 lastInterestRateAdjTime;
        address interestBatchManager;
        uint256 batchDebtShares;
        uint256 batchCollShares;
        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);
}

File 24 of 50 : IStabilityPool.sol
// 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 epochToScaleToS(uint128 _epoch, uint128 _scale) external view returns (uint256);

    function epochToScaleToB(uint128 _epoch, uint128 _scale) external view returns (uint256);

    function P() external view returns (uint256);
    function currentScale() external view returns (uint128);
    function currentEpoch() external view returns (uint128);
}

File 25 of 50 : ITroveNFT.sol
// 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;
}

File 26 of 50 : MetadataNFT.sol
//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;

    string public constant name = "Liquity V2 Trove";
    string public constant description = "Liquity V2 Trove position";

    constructor(FixedAssetReader _assetReader) {
        assetReader = _assetReader;
    }

    function uri(TroveData memory _troveData) public view returns (string memory) {
        string memory attr = attributes(_troveData);
        return json.formattedMetadata(name, description, 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 "";
    }
}

File 27 of 50 : ICollateralRegistry.sol
// 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);
}

File 28 of 50 : IInterestRouter.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

File 29 of 50 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
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);
}

File 30 of 50 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

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 31 of 50 : BatchId.sol
// 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 32 of 50 : 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.0375 ether;

// Fraction of collateral awarded to liquidator
uint256 constant COLL_GAS_COMPENSATION_DIVISOR = 200; // dividing by 200 yields 0.5%
uint256 constant COLL_GAS_COMPENSATION_CAP = 2 ether; // Max coll gas compensation capped at 2 ETH

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

uint256 constant MIN_ANNUAL_INTEREST_RATE = _1pct / 2; // 0.5%
uint256 constant MAX_ANNUAL_INTEREST_RATE = _100pct;

// Batch management params
uint128 constant MAX_ANNUAL_BATCH_MANAGEMENT_FEE = uint128(_100pct);
uint128 constant MIN_INTEREST_RATE_CHANGE_PERIOD = 1 seconds; // prevents more than one adjustment per block

uint256 constant REDEMPTION_FEE_FLOOR = _1pct / 2; // 0.5%

// 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 12h. 12h = 720 min
// (1/2) = d^720 => d = (1/2)^(1/720)
uint256 constant REDEMPTION_MINUTE_DECAY_FACTOR = 999037758833783000;

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

// To prevent redemptions unless Bold depegs below 0.95 and allow the system to take off
uint256 constant INITIAL_BASE_RATE = 5 * _1pct - REDEMPTION_FEE_FLOOR; // 5% initial redemption rate

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

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 = 3 days;

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

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

File 33 of 50 : LiquityMath.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.24;

import {DECIMAL_PRECISION} from "./Constants.sol";

library LiquityMath {
    function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a < _b) ? _a : _b;
    }

    function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a >= _b) ? _a : _b;
    }

    function _sub_min_0(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a > _b) ? _a - _b : 0;
    }

    /* 
    * Multiply two decimal numbers and use normal rounding rules:
    * -round product up if 19'th mantissa digit >= 5
    * -round product down if 19'th mantissa digit < 5
    *
    * Used only inside the exponentiation, _decPow().
    */
    function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {
        uint256 prod_xy = x * y;

        decProd = (prod_xy + DECIMAL_PRECISION / 2) / DECIMAL_PRECISION;
    }

    /* 
    * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
    * 
    * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. 
    * 
    * Called by function CollateralRegistry._calcDecayedBaseRate, that represent time in units of minutes
    *
    * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
    * "minutes in 1000 years": 60 * 24 * 365 * 1000
    * 
    * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
    * negligibly different from just passing the cap, since: 
    *
    * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
    * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
    */
    function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {
        if (_minutes > 525600000) _minutes = 525600000; // cap to avoid overflow

        if (_minutes == 0) return DECIMAL_PRECISION;

        uint256 y = DECIMAL_PRECISION;
        uint256 x = _base;
        uint256 n = _minutes;

        // Exponentiation-by-squaring
        while (n > 1) {
            if (n % 2 == 0) {
                x = decMul(x, x);
                n = n / 2;
            } else {
                // if (n % 2 != 0)
                y = decMul(x, y);
                x = decMul(x, x);
                n = (n - 1) / 2;
            }
        }

        return decMul(x, y);
    }

    function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {
        return (_a >= _b) ? _a - _b : _b - _a;
    }

    function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {
        if (_debt > 0) {
            uint256 newCollRatio = _coll * _price / _debt;

            return newCollRatio;
        }
        // Return the maximal value for uint256 if the debt is 0. Represents "infinite" CR.
        else {
            // if (_debt == 0)
            return 2 ** 256 - 1;
        }
    }
}

File 34 of 50 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

File 35 of 50 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

File 36 of 50 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

File 37 of 50 : IBoldRewardsReceiver.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

File 38 of 50 : 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 39 of 50 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

import {IERC721} from "../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);
}

File 40 of 50 : SSTORE2.sol
// 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(0xffffffffff, sub(extcodesize(pointer), 0x01))
            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(0xffffffffff, sub(extcodesize(pointer), 0x01))
            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(40, 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.
        }
    }
}

File 41 of 50 : JSON.sol
//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;
    }
}

File 42 of 50 : baseSVG.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

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

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

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

    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",
                    string.concat("data:image/svg+xml;base64,", _assetReader.readAsset(bytes4(keccak256("BOLD"))))
                )
            )
        );
    }

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

File 43 of 50 : bauhaus.sol
//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))
            )
        );
    }
}

File 44 of 50 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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 45 of 50 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 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 ERC-721 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 ERC-721
     * 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 address zero.
     *
     * 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 46 of 50 : 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, '" ');
        }
    }
}

File 47 of 50 : Utils.sol
//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);
    }
}

File 48 of 50 : FixedAssets.sol
//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 49 of 50 : LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

/// @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 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Goated string storage struct that totally MOGs, no cap, fr.
    /// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
    /// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
    struct StringStorage {
        bytes32 _spacer;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        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;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                 STRING STORAGE OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sets the value of the string storage `$` to `s`.
    function set(StringStorage storage $, string memory s) internal {
        LibBytes.set(bytesStorage($), bytes(s));
    }

    /// @dev Sets the value of the string storage `$` to `s`.
    function setCalldata(StringStorage storage $, string calldata s) internal {
        LibBytes.setCalldata(bytesStorage($), bytes(s));
    }

    /// @dev Sets the value of the string storage `$` to the empty string.
    function clear(StringStorage storage $) internal {
        delete $._spacer;
    }

    /// @dev Returns whether the value stored is `$` is the empty string "".
    function isEmpty(StringStorage storage $) internal view returns (bool) {
        return uint256($._spacer) & 0xff == uint256(0);
    }

    /// @dev Returns the length of the value stored in `$`.
    function length(StringStorage storage $) internal view returns (uint256) {
        return LibBytes.length(bytesStorage($));
    }

    /// @dev Returns the value stored in `$`.
    function get(StringStorage storage $) internal view returns (string memory) {
        return string(LibBytes.get(bytesStorage($)));
    }

    /// @dev Helper to cast `$` to a `BytesStorage`.
    function bytesStorage(StringStorage storage $)
        internal
        pure
        returns (LibBytes.BytesStorage storage casted)
    {
        /// @solidity memory-safe-assembly
        assembly {
            casted.slot := $.slot
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     DECIMAL OPERATIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the base 10 decimal representation of `value`.
    function toString(uint256 value) internal pure returns (string memory result) {
        /// @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.
            result := add(mload(0x40), 0x80)
            mstore(0x40, add(result, 0x20)) // Allocate memory.
            mstore(result, 0) // Zeroize the slot after the string.

            let end := result // 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 {} {
                result := add(result, w) // `sub(result, 1)`.
                // Store the character to the pointer.
                // The ASCII index of the '0' character is 48.
                mstore8(result, add(48, mod(temp, 10)))
                temp := div(temp, 10) // Keep dividing `temp` until zero.
                if iszero(temp) { break }
            }
            let n := sub(end, result)
            result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the base 10 decimal representation of `value`.
    function toString(int256 value) internal pure returns (string memory result) {
        if (value >= 0) return toString(uint256(value));
        unchecked {
            result = 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 n := mload(result) // Load the string length.
            mstore(result, 0x2d) // Store the '-' character.
            result := sub(result, 1) // Move back the string pointer by a byte.
            mstore(result, add(n, 1)) // Update the string length.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   HEXADECIMAL OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the hexadecimal representation of `value`,
    /// left-padded to an input length of `byteCount` bytes.
    /// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
    /// giving a total length of `byteCount * 2 + 2` bytes.
    /// Reverts if `byteCount` is too small for the output to contain all the digits.
    function toHexString(uint256 value, uint256 byteCount)
        internal
        pure
        returns (string memory result)
    {
        result = toHexStringNoPrefix(value, byteCount);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`,
    /// left-padded to an input length of `byteCount` bytes.
    /// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
    /// giving a total length of `byteCount * 2` bytes.
    /// Reverts if `byteCount` is too small for the output to contain all the digits.
    function toHexStringNoPrefix(uint256 value, uint256 byteCount)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // We need 0x20 bytes for the trailing zeros padding, `byteCount * 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.
            result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
            mstore(0x40, add(result, 0x20)) // Allocate memory.
            mstore(result, 0) // Zeroize the slot after the string.

            let end := result // Cache the end to calculate the length later.
            // Store "0123456789abcdef" in scratch space.
            mstore(0x0f, 0x30313233343536373839616263646566)

            let start := sub(result, add(byteCount, byteCount))
            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 {} {
                result := add(result, w) // `sub(result, 2)`.
                mstore8(add(result, 1), mload(and(temp, 15)))
                mstore8(result, mload(and(shr(4, temp), 15)))
                temp := shr(8, temp)
                if iszero(xor(result, start)) { break }
            }
            if temp {
                mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
                revert(0x1c, 0x04)
            }
            let n := sub(end, result)
            result := sub(result, 0x20)
            mstore(result, n) // 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 result) {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // 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 result) {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
            let n := add(mload(result), 2) // Compute the length.
            mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
            result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
            mstore(result, sub(n, 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 result)
    {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
            let n := mload(result) // Get the length.
            result := add(result, o) // Move the pointer, accounting for leading zero.
            mstore(result, sub(n, 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 result) {
        /// @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.
            result := add(mload(0x40), 0x80)
            mstore(0x40, add(result, 0x20)) // Allocate memory.
            mstore(result, 0) // Zeroize the slot after the string.

            let end := result // 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 {} {
                result := add(result, w) // `sub(result, 2)`.
                mstore8(add(result, 1), mload(and(temp, 15)))
                mstore8(result, mload(and(shr(4, temp), 15)))
                temp := shr(8, temp)
                if iszero(temp) { break }
            }
            let n := sub(end, result)
            result := sub(result, 0x20)
            mstore(result, n) // 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 result) {
        result = toHexString(value);
        /// @solidity memory-safe-assembly
        assembly {
            let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
            let o := add(result, 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 result) {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // 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 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            // Allocate 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(result, 0x80))
            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.

            result := add(result, 2)
            mstore(result, 40) // Store the length.
            let o := add(result, 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 result) {
        result = toHexStringNoPrefix(raw);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // 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 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(raw)
            result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
            mstore(result, add(n, n)) // Store the length of the output.

            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
            let o := add(result, 0x20)
            let end := add(raw, n)
            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 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 {
            result := 1
            let mask := shl(7, div(not(0), 255))
            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)
                for { let end := add(o, mload(s)) } 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)
                for { let end := add(o, mload(s)) } 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 `needle` replaced with `replacement`.
    function replace(string memory subject, string memory needle, string memory replacement)
        internal
        pure
        returns (string memory)
    {
        return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(string memory subject, string memory needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return LibBytes.indexOf(bytes(subject), bytes(needle), from);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
        return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(string memory subject, string memory needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(string memory subject, string memory needle)
        internal
        pure
        returns (uint256)
    {
        return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
    }

    /// @dev Returns true if `needle` is found in `subject`, false otherwise.
    function contains(string memory subject, string memory needle) internal pure returns (bool) {
        return LibBytes.contains(bytes(subject), bytes(needle));
    }

    /// @dev Returns whether `subject` starts with `needle`.
    function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
        return LibBytes.startsWith(bytes(subject), bytes(needle));
    }

    /// @dev Returns whether `subject` ends with `needle`.
    function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
        return LibBytes.endsWith(bytes(subject), bytes(needle));
    }

    /// @dev Returns `subject` repeated `times`.
    function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
        return string(LibBytes.repeat(bytes(subject), times));
    }

    /// @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)
    {
        return string(LibBytes.slice(bytes(subject), start, end));
    }

    /// @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) {
        return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
    }

    /// @dev Returns all the indices of `needle` in `subject`.
    /// The indices are byte offsets.
    function indicesOf(string memory subject, string memory needle)
        internal
        pure
        returns (uint256[] memory)
    {
        return LibBytes.indicesOf(bytes(subject), bytes(needle));
    }

    /// @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)
    {
        bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @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) {
        return string(LibBytes.concat(bytes(a), bytes(b)));
    }

    /// @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 n := mload(subject)
            if n {
                result := mload(0x40)
                let o := add(result, 0x20)
                let d := sub(subject, result)
                let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
                for { let end := add(o, n) } 1 {} {
                    let b := byte(0, mload(add(d, o)))
                    mstore8(o, xor(and(shr(b, flags), 0x20), b))
                    o := add(o, 1)
                    if eq(o, end) { break }
                }
                mstore(result, n) // Store the length.
                mstore(o, 0) // Zeroize the slot after the string.
                mstore(0x40, add(o, 0x20)) // Allocate 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 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 {
            result := mload(0x40)
            let end := add(s, mload(s))
            let o := add(result, 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(o, c)
                    o := add(o, 1)
                    continue
                }
                let t := shr(248, mload(c))
                mstore(o, mload(and(t, 0x1f)))
                o := add(o, shr(5, t))
            }
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(result, sub(o, add(result, 0x20))) // Store the length.
            mstore(0x40, add(o, 0x20)) // Allocate 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 {
            result := mload(0x40)
            let o := add(result, 0x20)
            if addDoubleQuotes {
                mstore8(o, 34)
                o := add(1, o)
            }
            // 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 { let end := add(s, mload(s)) } 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(o, c)
                        o := add(o, 1)
                        continue
                    }
                    mstore8(o, 0x5c) // "\\".
                    mstore8(add(o, 1), c)
                    o := add(o, 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(o, mload(0x19)) // "\\u00XX".
                    o := add(o, 6)
                    continue
                }
                mstore8(o, 0x5c) // "\\".
                mstore8(add(o, 1), mload(add(c, 8)))
                o := add(o, 2)
            }
            if addDoubleQuotes {
                mstore8(o, 34)
                o := add(1, o)
            }
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(result, sub(o, add(result, 0x20))) // Store the length.
            mstore(0x40, add(o, 0x20)) // Allocate 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 Encodes `s` so that it can be safely used in a URI,
    /// just like `encodeURIComponent` in JavaScript.
    /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
    /// See: https://datatracker.ietf.org/doc/html/rfc2396
    /// See: https://datatracker.ietf.org/doc/html/rfc3986
    function encodeURIComponent(string memory s) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            // Store "0123456789ABCDEF" in scratch space.
            // Uppercased to be consistent with JavaScript's implementation.
            mstore(0x0f, 0x30313233343536373839414243444546)
            let o := add(result, 0x20)
            for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
                s := add(s, 1)
                let c := and(mload(s), 0xff)
                // If not in `[0-9A-Z-a-z-_.!~*'()]`.
                if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
                    mstore8(o, 0x25) // '%'.
                    mstore8(add(o, 1), mload(and(shr(4, c), 15)))
                    mstore8(add(o, 2), mload(and(c, 15)))
                    o := add(o, 3)
                    continue
                }
                mstore8(o, c)
                o := add(o, 1)
            }
            mstore(result, sub(o, add(result, 0x20))) // Store the length.
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
        }
    }

    /// @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 aLen := 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, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
                    // `totalLen != 0 && totalLen < 31`. Abuses underflow.
                    // Assumes that the lengths are valid and within the block gas limit.
                    lt(sub(add(aLen, 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)))
        }
    }
}

File 50 of 50 : LibBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
    /// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
    /// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
    struct BytesStorage {
        bytes32 _spacer;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The constant returned when the `search` is not found in the bytes.
    uint256 internal constant NOT_FOUND = type(uint256).max;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  BYTE STORAGE OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sets the value of the bytes storage `$` to `s`.
    function set(BytesStorage storage $, bytes memory s) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(s)
            let packed := or(0xff, shl(8, n))
            for { let i := 0 } 1 {} {
                if iszero(gt(n, 0xfe)) {
                    i := 0x1f
                    packed := or(n, shl(8, mload(add(s, i))))
                    if iszero(gt(n, i)) { break }
                }
                let o := add(s, 0x20)
                mstore(0x00, $.slot)
                for { let p := keccak256(0x00, 0x20) } 1 {} {
                    sstore(add(p, shr(5, i)), mload(add(o, i)))
                    i := add(i, 0x20)
                    if iszero(lt(i, n)) { break }
                }
                break
            }
            sstore($.slot, packed)
        }
    }

    /// @dev Sets the value of the bytes storage `$` to `s`.
    function setCalldata(BytesStorage storage $, bytes calldata s) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let packed := or(0xff, shl(8, s.length))
            for { let i := 0 } 1 {} {
                if iszero(gt(s.length, 0xfe)) {
                    i := 0x1f
                    packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
                    if iszero(gt(s.length, i)) { break }
                }
                mstore(0x00, $.slot)
                for { let p := keccak256(0x00, 0x20) } 1 {} {
                    sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
                    i := add(i, 0x20)
                    if iszero(lt(i, s.length)) { break }
                }
                break
            }
            sstore($.slot, packed)
        }
    }

    /// @dev Sets the value of the bytes storage `$` to the empty bytes.
    function clear(BytesStorage storage $) internal {
        delete $._spacer;
    }

    /// @dev Returns whether the value stored is `$` is the empty bytes "".
    function isEmpty(BytesStorage storage $) internal view returns (bool) {
        return uint256($._spacer) & 0xff == uint256(0);
    }

    /// @dev Returns the length of the value stored in `$`.
    function length(BytesStorage storage $) internal view returns (uint256 result) {
        result = uint256($._spacer);
        /// @solidity memory-safe-assembly
        assembly {
            let n := and(0xff, result)
            result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
        }
    }

    /// @dev Returns the value stored in `$`.
    function get(BytesStorage storage $) internal view returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let o := add(result, 0x20)
            let packed := sload($.slot)
            let n := shr(8, packed)
            for { let i := 0 } 1 {} {
                if iszero(eq(and(packed, 0xff), 0xff)) {
                    mstore(o, packed)
                    n := and(0xff, packed)
                    i := 0x1f
                    if iszero(gt(n, i)) { break }
                }
                mstore(0x00, $.slot)
                for { let p := keccak256(0x00, 0x20) } 1 {} {
                    mstore(add(o, i), sload(add(p, shr(5, i))))
                    i := add(i, 0x20)
                    if iszero(lt(i, n)) { break }
                }
                break
            }
            mstore(result, n) // Store the length of the memory.
            mstore(add(o, n), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      BYTES OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
    function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let needleLen := mload(needle)
            let replacementLen := mload(replacement)
            let d := sub(result, subject) // Memory difference.
            let i := add(subject, 0x20) // Subject bytes pointer.
            mstore(0x00, add(i, mload(subject))) // End of subject.
            if iszero(gt(needleLen, mload(subject))) {
                let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
                let h := 0 // The hash of `needle`.
                if iszero(lt(needleLen, 0x20)) { h := keccak256(add(needle, 0x20), needleLen) }
                let s := mload(add(needle, 0x20))
                for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
                    let t := mload(i)
                    // Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
                    if iszero(shr(m, xor(t, s))) {
                        if h {
                            if iszero(eq(keccak256(i, needleLen), h)) {
                                mstore(add(i, d), t)
                                i := add(i, 1)
                                if iszero(lt(i, subjectSearchEnd)) { break }
                                continue
                            }
                        }
                        // Copy the `replacement` one word at a time.
                        for { let j := 0 } 1 {} {
                            mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
                            j := add(j, 0x20)
                            if iszero(lt(j, replacementLen)) { break }
                        }
                        d := sub(add(d, replacementLen), needleLen)
                        if needleLen {
                            i := add(i, needleLen)
                            if iszero(lt(i, subjectSearchEnd)) { break }
                            continue
                        }
                    }
                    mstore(add(i, d), t)
                    i := add(i, 1)
                    if iszero(lt(i, subjectSearchEnd)) { break }
                }
            }
            let end := mload(0x00)
            let n := add(sub(d, add(result, 0x20)), end)
            // Copy the rest of the bytes one word at a time.
            for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
            let o := add(i, d)
            mstore(o, 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(bytes memory subject, bytes memory needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := not(0) // Initialize to `NOT_FOUND`.
            for { let subjectLen := mload(subject) } 1 {} {
                if iszero(mload(needle)) {
                    result := from
                    if iszero(gt(from, subjectLen)) { break }
                    result := subjectLen
                    break
                }
                let needleLen := mload(needle)
                let subjectStart := add(subject, 0x20)

                subject := add(subjectStart, from)
                let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
                let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
                let s := mload(add(needle, 0x20))

                if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }

                if iszero(lt(needleLen, 0x20)) {
                    for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
                        if iszero(shr(m, xor(mload(subject), s))) {
                            if eq(keccak256(subject, needleLen), 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 `needle` in `subject`,
    /// needleing from left to right.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
        return indexOf(subject, needle, 0);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                result := not(0) // Initialize to `NOT_FOUND`.
                let needleLen := mload(needle)
                if gt(needleLen, mload(subject)) { break }
                let w := result

                let fromMax := sub(mload(subject), needleLen)
                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(needle, 0x20), needleLen) } 1 {} {
                    if eq(keccak256(subject, needleLen), 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 `needle` in `subject`,
    /// needleing from right to left.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (uint256)
    {
        return lastIndexOf(subject, needle, type(uint256).max);
    }

    /// @dev Returns true if `needle` is found in `subject`, false otherwise.
    function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
        return indexOf(subject, needle) != NOT_FOUND;
    }

    /// @dev Returns whether `subject` starts with `needle`.
    function startsWith(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(needle)
            // Just using keccak256 directly is actually cheaper.
            let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
            result := lt(gt(n, mload(subject)), t)
        }
    }

    /// @dev Returns whether `subject` ends with `needle`.
    function endsWith(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(needle)
            let notInRange := gt(n, mload(subject))
            // `subject + 0x20 + max(subject.length - needle.length, 0)`.
            let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
            // Just using keccak256 directly is actually cheaper.
            result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
        }
    }

    /// @dev Returns `subject` repeated `times`.
    function repeat(bytes memory subject, uint256 times)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := mload(subject) // Subject length.
            if iszero(or(iszero(times), iszero(l))) {
                result := mload(0x40)
                subject := add(subject, 0x20)
                let o := add(result, 0x20)
                for {} 1 {} {
                    // Copy the `subject` one word at a time.
                    for { let j := 0 } 1 {} {
                        mstore(add(o, j), mload(add(subject, j)))
                        j := add(j, 0x20)
                        if iszero(lt(j, l)) { break }
                    }
                    o := add(o, l)
                    times := sub(times, 1)
                    if iszero(times) { break }
                }
                mstore(o, 0) // Zeroize the slot after the bytes.
                mstore(0x40, add(o, 0x20)) // Allocate memory.
                mstore(result, sub(o, add(result, 0x20))) // Store the length.
            }
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
    /// `start` and `end` are byte offsets.
    function slice(bytes memory subject, uint256 start, uint256 end)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := mload(subject) // Subject length.
            if iszero(gt(l, end)) { end := l }
            if iszero(gt(l, start)) { start := l }
            if lt(start, end) {
                result := mload(0x40)
                let n := sub(end, start)
                let i := add(subject, start)
                let w := not(0x1f)
                // Copy the `subject` one word at a time, backwards.
                for { let j := and(add(n, 0x1f), w) } 1 {} {
                    mstore(add(result, j), mload(add(i, j)))
                    j := add(j, w) // `sub(j, 0x20)`.
                    if iszero(j) { break }
                }
                let o := add(add(result, 0x20), n)
                mstore(o, 0) // Zeroize the slot after the bytes.
                mstore(0x40, add(o, 0x20)) // Allocate memory.
                mstore(result, n) // Store the length.
            }
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
    /// `start` is a byte offset.
    function slice(bytes memory subject, uint256 start)
        internal
        pure
        returns (bytes memory result)
    {
        result = slice(subject, start, type(uint256).max);
    }

    /// @dev Reduces the size of `subject` to `n`.
    /// If `n` is greater than the size of `subject`, this will be a no-op.
    function truncate(bytes memory subject, uint256 n)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := subject
            mstore(mul(lt(n, mload(result)), result), n)
        }
    }

    /// @dev Returns a copy of `subject`, with the length reduced to `n`.
    /// If `n` is greater than the size of `subject`, this will be a no-op.
    function truncatedCalldata(bytes calldata subject, uint256 n)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result.offset := subject.offset
            result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
        }
    }

    /// @dev Returns all the indices of `needle` in `subject`.
    /// The indices are byte offsets.
    function indicesOf(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (uint256[] memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let searchLen := mload(needle)
            if iszero(gt(searchLen, mload(subject))) {
                result := mload(0x40)
                let i := add(subject, 0x20)
                let o := add(result, 0x20)
                let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
                let h := 0 // The hash of `needle`.
                if iszero(lt(searchLen, 0x20)) { h := keccak256(add(needle, 0x20), searchLen) }
                let s := mload(add(needle, 0x20))
                for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
                    let t := mload(i)
                    // Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
                    if iszero(shr(m, xor(t, s))) {
                        if h {
                            if iszero(eq(keccak256(i, searchLen), h)) {
                                i := add(i, 1)
                                if iszero(lt(i, subjectSearchEnd)) { break }
                                continue
                            }
                        }
                        mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
                        o := add(o, 0x20)
                        i := add(i, searchLen) // Advance `i` by `searchLen`.
                        if searchLen {
                            if iszero(lt(i, subjectSearchEnd)) { break }
                            continue
                        }
                    }
                    i := add(i, 1)
                    if iszero(lt(i, subjectSearchEnd)) { break }
                }
                mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
                // Allocate memory for result.
                // We allocate one more word, so this array can be recycled for {split}.
                mstore(0x40, add(o, 0x20))
            }
        }
    }

    /// @dev Returns a arrays of bytess based on the `delimiter` inside of the `subject` bytes.
    function split(bytes memory subject, bytes memory delimiter)
        internal
        pure
        returns (bytes[] 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))
            for { let prevIndex := 0 } 1 {} {
                let index := mload(indexPtr)
                mstore(indexPtr, 0x60)
                if iszero(eq(index, prevIndex)) {
                    let element := mload(0x40)
                    let l := sub(index, prevIndex)
                    mstore(element, l) // Store the length of the element.
                    // Copy the `subject` one word at a time, backwards.
                    for { let o := and(add(l, 0x1f), w) } 1 {} {
                        mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
                        o := add(o, w) // `sub(o, 0x20)`.
                        if iszero(o) { break }
                    }
                    mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
                    // Allocate memory for the length and the bytes, rounded up to a multiple of 32.
                    mstore(0x40, add(element, and(add(l, 0x3f), w)))
                    mstore(indexPtr, element) // Store the `element` into the array.
                }
                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 bytes of `a` and `b`.
    /// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
    function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let w := not(0x1f)
            let aLen := mload(a)
            // Copy `a` one word at a time, backwards.
            for { let o := and(add(aLen, 0x20), w) } 1 {} {
                mstore(add(result, o), mload(add(a, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            let bLen := mload(b)
            let output := add(result, aLen)
            // Copy `b` one word at a time, backwards.
            for { let o := and(add(bLen, 0x20), w) } 1 {} {
                mstore(add(output, o), mload(add(b, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            let totalLen := add(aLen, bLen)
            let last := add(add(result, 0x20), totalLen)
            mstore(last, 0) // Zeroize the slot after the bytes.
            mstore(result, totalLen) // Store the length.
            mstore(0x40, add(last, 0x20)) // Allocate memory.
        }
    }

    /// @dev Returns whether `a` equals `b`.
    function eq(bytes memory a, bytes 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 bytes.
    function eqs(bytes 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 Directly returns `a` without copying.
    function directReturn(bytes memory a) internal pure {
        assembly {
            // Assumes that the bytes 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 bytes 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 bytes.
            return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
        }
    }

    /// @dev Returns the word at `offset`, without any bounds checks.
    /// To load an address, you can use `address(bytes20(load(a, offset)))`.
    function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), offset))
        }
    }

    /// @dev Returns the word at `offset`, without any bounds checks.
    /// To load an address, you can use `address(bytes20(loadCalldata(a, offset)))`.
    function loadCalldata(bytes calldata a, uint256 offset)
        internal
        pure
        returns (bytes32 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := calldataload(add(a.offset, offset))
        }
    }
}

Settings
{
  "remappings": [
    "@chimera/=lib/V2-gov/lib/chimera/src/",
    "@ensdomains/=lib/V2-gov/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/V2-gov/lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "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-gas-snapshot/=lib/V2-gov/lib/v4-core/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/V2-gov/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/V2-gov/lib/openzeppelin-contracts/",
    "solmate/=lib/V2-gov/lib/v4-core/lib/solmate/src/",
    "v4-core/=lib/V2-gov/lib/v4-core/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false,
  "libraries": {}
}

Contract ABI

[{"inputs":[{"internalType":"contract IAddressesRegistry","name":"_addressesRegistry","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AnnualManagementFeeTooHigh","type":"error"},{"inputs":[],"name":"BatchInterestRateChangePeriodNotPassed","type":"error"},{"inputs":[],"name":"BatchManagerExists","type":"error"},{"inputs":[],"name":"BatchManagerNotNew","type":"error"},{"inputs":[],"name":"CallerNotPriceFeed","type":"error"},{"inputs":[],"name":"CallerNotTroveManager","type":"error"},{"inputs":[],"name":"CollWithdrawalTooHigh","type":"error"},{"inputs":[],"name":"DebtBelowMin","type":"error"},{"inputs":[],"name":"DelegateInterestRateChangePeriodNotPassed","type":"error"},{"inputs":[],"name":"EmptyManager","type":"error"},{"inputs":[],"name":"ICRBelowMCR","type":"error"},{"inputs":[],"name":"InterestNotInRange","type":"error"},{"inputs":[],"name":"InterestRateNotNew","type":"error"},{"inputs":[],"name":"InterestRateTooHigh","type":"error"},{"inputs":[],"name":"InterestRateTooLow","type":"error"},{"inputs":[],"name":"InvalidInterestBatchManager","type":"error"},{"inputs":[],"name":"IsShutDown","type":"error"},{"inputs":[],"name":"MinGeMax","type":"error"},{"inputs":[],"name":"MinInterestRateChangePeriodTooLow","type":"error"},{"inputs":[],"name":"NewFeeNotLower","type":"error"},{"inputs":[],"name":"NewOracleFailureDetected","type":"error"},{"inputs":[],"name":"NotBorrower","type":"error"},{"inputs":[],"name":"NotEnoughBoldBalance","type":"error"},{"inputs":[],"name":"NotOwnerNorAddManager","type":"error"},{"inputs":[],"name":"NotOwnerNorInterestManager","type":"error"},{"inputs":[],"name":"NotOwnerNorRemoveManager","type":"error"},{"inputs":[],"name":"RepaymentNotMatchingCollWithdrawal","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"TCRBelowCCR","type":"error"},{"inputs":[],"name":"TCRNotBelowSCR","type":"error"},{"inputs":[],"name":"TroveExists","type":"error"},{"inputs":[],"name":"TroveInBatch","type":"error"},{"inputs":[],"name":"TroveNotActive","type":"error"},{"inputs":[],"name":"TroveNotInBatch","type":"error"},{"inputs":[],"name":"TroveNotOpen","type":"error"},{"inputs":[],"name":"TroveNotZombie","type":"error"},{"inputs":[],"name":"TroveWithZeroDebt","type":"error"},{"inputs":[],"name":"UpfrontFeeTooHigh","type":"error"},{"inputs":[],"name":"ZeroAdjustment","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newActivePoolAddress","type":"address"}],"name":"ActivePoolAddressChanged","type":"event"},{"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":false,"internalType":"address","name":"_boldTokenAddress","type":"address"}],"name":"BoldTokenAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_collSurplusPoolAddress","type":"address"}],"name":"CollSurplusPoolAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newDefaultPoolAddress","type":"address"}],"name":"DefaultPoolAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_gasPoolAddress","type":"address"}],"name":"GasPoolAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newPriceFeedAddress","type":"address"}],"name":"PriceFeedAddressChanged","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":"uint256","name":"_tcr","type":"uint256"}],"name":"ShutDown","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_sortedTrovesAddress","type":"address"}],"name":"SortedTrovesAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newTroveManagerAddress","type":"address"}],"name":"TroveManagerAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newTroveNFTAddress","type":"address"}],"name":"TroveNFTAddressChanged","type":"event"},{"inputs":[],"name":"CCR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MCR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SCR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"activePool","outputs":[{"internalType":"contract IActivePool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_collAmount","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":"_newAnnualInterestRate","type":"uint256"},{"internalType":"uint256","name":"_upperHint","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"adjustTroveInterestRate","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":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_upperHint","type":"uint256"}],"name":"applyPendingDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_batchManager","type":"address"}],"name":"checkBatchManagerExists","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claimCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"}],"name":"closeTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getEntireSystemColl","outputs":[{"internalType":"uint256","name":"entireSystemColl","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEntireSystemDebt","outputs":[{"internalType":"uint256","name":"entireSystemDebt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"getInterestBatchManager","outputs":[{"components":[{"internalType":"uint128","name":"minInterestRate","type":"uint128"},{"internalType":"uint128","name":"maxInterestRate","type":"uint128"},{"internalType":"uint256","name":"minInterestRateChangePeriod","type":"uint256"}],"internalType":"struct IBorrowerOperations.InterestBatchManager","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"}],"name":"getInterestIndividualDelegateOf","outputs":[{"components":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint128","name":"minInterestRate","type":"uint128"},{"internalType":"uint128","name":"maxInterestRate","type":"uint128"},{"internalType":"uint256","name":"minInterestRateChangePeriod","type":"uint256"}],"internalType":"struct IBorrowerOperations.InterestIndividualDelegate","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hasBeenShutDown","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"interestBatchManagerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_newAnnualManagementFee","type":"uint256"}],"name":"lowerBatchManagementFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"}],"name":"onLiquidateTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"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":"uint256","name":"_maxUpfrontFee","type":"uint256"},{"internalType":"address","name":"_addManager","type":"address"},{"internalType":"address","name":"_removeManager","type":"address"},{"internalType":"address","name":"_receiver","type":"address"}],"name":"openTrove","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","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":"address","name":"interestBatchManager","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 IBorrowerOperations.OpenTroveAndJoinInterestBatchManagerParams","name":"_params","type":"tuple"}],"name":"openTroveAndJoinInterestBatchManager","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"_minInterestRate","type":"uint128"},{"internalType":"uint128","name":"_maxInterestRate","type":"uint128"},{"internalType":"uint128","name":"_currentInterestRate","type":"uint128"},{"internalType":"uint128","name":"_annualManagementFee","type":"uint128"},{"internalType":"uint128","name":"_minInterestRateChangePeriod","type":"uint128"}],"name":"registerBatchManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_newAnnualInterestRate","type":"uint256"},{"internalType":"uint256","name":"_upperHint","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"removeFromBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"}],"name":"removeInterestIndividualDelegate","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":"uint128","name":"_newAnnualInterestRate","type":"uint128"},{"internalType":"uint256","name":"_upperHint","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"setBatchManagerAnnualInterestRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"address","name":"_newBatchManager","type":"address"},{"internalType":"uint256","name":"_upperHint","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"setInterestBatchManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"address","name":"_delegate","type":"address"},{"internalType":"uint128","name":"_minInterestRate","type":"uint128"},{"internalType":"uint128","name":"_maxInterestRate","type":"uint128"},{"internalType":"uint256","name":"_newAnnualInterestRate","type":"uint256"},{"internalType":"uint256","name":"_upperHint","type":"uint256"},{"internalType":"uint256","name":"_lowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"},{"internalType":"uint256","name":"_minInterestRateChangePeriod","type":"uint256"}],"name":"setInterestIndividualDelegate","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":"shutdown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"shutdownFromOracleFailure","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_troveId","type":"uint256"},{"internalType":"uint256","name":"_removeUpperHint","type":"uint256"},{"internalType":"uint256","name":"_removeLowerHint","type":"uint256"},{"internalType":"address","name":"_newBatchManager","type":"address"},{"internalType":"uint256","name":"_addUpperHint","type":"uint256"},{"internalType":"uint256","name":"_addLowerHint","type":"uint256"},{"internalType":"uint256","name":"_maxUpfrontFee","type":"uint256"}],"name":"switchBatchManager","outputs":[],"stateMutability":"nonpayable","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":"_collWithdrawal","type":"uint256"}],"name":"withdrawColl","outputs":[],"stateMutability":"nonpayable","type":"function"}]

61014060405234801562000011575f80fd5b50604051620066f3380380620066f38339810160408190526200003491620009ca565b8081806001600160a01b0316637f7dde4a6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000073573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620000999190620009ca565b5f806101000a8154816001600160a01b0302191690836001600160a01b03160217905550806001600160a01b0316633cc742256040518163ffffffff1660e01b8152600401602060405180830381865afa158015620000fa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620001209190620009ca565b60015f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550806001600160a01b031663741bef1a6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000182573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620001a89190620009ca565b600280546001600160a01b0319166001600160a01b039283161790555f54604051911681527f78f058b189175430c48dc02699e3a0031ea4ff781536dc2fab847de4babdd8829060200160405180910390a16001546040516001600160a01b0390911681527f5ee0cae2f063ed938bb55046f6a932fb6ae792bf43624806bb90abe68a50be9b9060200160405180910390a16002546040516001600160a01b0390911681527f8c537274438aa850a330284665d81a85dd38267d09e4050d416bfc94142db2649060200160405180910390a150806001600160a01b031663059e01136040518163ffffffff1660e01b8152600401602060405180830381865afa158015620002b8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620002de9190620009ca565b6001600160a01b031660808190526040519081527f39b3d3f08f5292d52497444fc183b3915a339c0b41fb021bf52ae59505e455b29060200160405180910390a150806001600160a01b03166331b8c9466040518163ffffffff1660e01b8152600401602060405180830381865afa1580156200035d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620003839190620009ca565b6001600160a01b031660a0816001600160a01b031681525050806001600160a01b031663ad5c46486040518163ffffffff1660e01b81526004016020604051808303815f875af1158015620003da573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620004009190620009ca565b6001600160a01b031660c0816001600160a01b031681525050806001600160a01b0316635733d58f6040518163ffffffff1660e01b81526004016020604051808303815f875af115801562000457573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200047d9190620009ef565b60e08181525050806001600160a01b03166358d5a9616040518163ffffffff1660e01b81526004016020604051808303815f875af1158015620004c2573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620004e89190620009ef565b6101008181525050806001600160a01b031663794e57246040518163ffffffff1660e01b81526004016020604051808303815f875af11580156200052e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620005549190620009ef565b6101208181525050806001600160a01b0316633d83908a6040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000599573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620005bf9190620009ca565b60055f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550806001600160a01b031663fe9d03236040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000621573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620006479190620009ca565b60065f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550806001600160a01b031663cda775f96040518163ffffffff1660e01b8152600401602060405180830381865afa158015620006a9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620006cf9190620009ca565b60075f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550806001600160a01b031663ae9187546040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000731573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620007579190620009ca565b60095f6101000a8154816001600160a01b0302191690836001600160a01b03160217905550806001600160a01b031663630afce56040518163ffffffff1660e01b8152600401602060405180830381865afa158015620007b9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620007df9190620009ca565b600880546001600160a01b0319166001600160a01b03928316179055600554604051911681527f143219c9e69b09e07e095fcc889b43d8f46ca892bba65f08dc3a0050869a56789060200160405180910390a16006546040516001600160a01b0390911681527fcfb07d791fcafc032b35837b50eb84b74df518cf4cc287e8084f47630fa70fa09060200160405180910390a16007546040516001600160a01b0390911681527fe67f36a6e961157d6eff83b91f3af5a62131ceb6f04954ef74f51c1c05e7f88d9060200160405180910390a16009546040516001600160a01b0390911681527f65f4cf077bc01e4742eb5ad98326f6e95b63548ea24b17f8d5e823111fe788009060200160405180910390a16008546040516001600160a01b0390911681527f28fe9b1bb8b27b863bb5635cb5bbd4e1beb7af490191ba03efe587680895b4fd9060200160405180910390a160a0515f5460405163095ea7b360e01b81526001600160a01b0391821660048201525f19602482015291169063095ea7b3906044016020604051808303815f875af115801562000984573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620009aa919062000a07565b505062000a28565b6001600160a01b0381168114620009c7575f80fd5b50565b5f60208284031215620009db575f80fd5b8151620009e881620009b2565b9392505050565b5f6020828403121562000a00575f80fd5b5051919050565b5f6020828403121562000a18575f80fd5b81518015158114620009e8575f80fd5b60805160a05160c05160e0516101005161012051615c3d62000ab65f395f818161056c015261494801525f81816104c40152612f4901525f818161047c015281816136da015281816137560152614e8a01525f81816112da01526144c401525f614da601525f81816109c601528181610ee1015281816130a9015281816133b601526137a30152615c3d5ff3fe608060405234801561000f575f80fd5b5060043610610234575f3560e01c806382e43a4911610135578063ba5f47a6116100b4578063d5479cd411610079578063d5479cd4146106eb578063d6491eaf146106fe578063dcfbd29314610711578063f9ef19ca14610724578063fc0e74d114610737575f80fd5b8063ba5f47a61461068c578063bcb266c01461069f578063c440844f146106b2578063c6ac2465146106c5578063d3695fa5146106d8575f80fd5b806390de348a116100fa57806390de348a146106185780639537f0011461062b5780639cb90ba61461063e578063a0df5cd514610651578063ad9be12714610679575f80fd5b806382e43a49146105a857806384e5253c146105b057806385c44a1a146105c3578063887105d3146105fd5780638fef27ab14610605575f80fd5b8063580de360116101c15780636f0b0c1c116101865780636f0b0c1c1461051f57806370986fe114610527578063794e572414610567578063795d26c31461058e5780637f7dde4a14610596575f80fd5b8063580de360146104ac57806358d5a961146104bf57806359f54f40146104e65780635aa6d461146104f95780635cd067cf1461050c575f80fd5b80634c1306b3116102075780634c1306b3146102dc5780634ed1bd5d146103af57806353eb288514610451578063570fb750146104645780635733d58f14610477575f80fd5b806306ff8dfb146102385780630e01617c1461026157806326f4e252146102b4578063292a3f0b146102c9575b5f80fd5b60095461024c90600160a01b900460ff1681565b60405190151581526020015b60405180910390f35b61029461026f3660046151bf565b60046020525f9081526040902080546001909101546001600160a01b03918216911682565b604080516001600160a01b03938416815292909116602083015201610258565b6102c76102c23660046151d6565b61073f565b005b6102c76102d7366004615221565b6109bf565b6103656102ea3660046151bf565b60408051608080820183525f80835260208084018290528385018290526060938401829052948152600a85528390208351918201845280546001600160a01b0316825260018101546001600160801b0380821696840196909652600160801b9004909416928101929092526002909201549181019190915290565b6040805182516001600160a01b031681526020808401516001600160801b039081169183019190915283830151169181019190915260609182015191810191909152608001610258565b6104216103bd36600461524f565b60408051606080820183525f80835260208084018290529284018190526001600160a01b03949094168452600c8252928290208251938401835280546001600160801b038082168652600160801b9091041691840191909152600101549082015290565b6040805182516001600160801b039081168252602080850151909116908201529181015190820152606001610258565b6102c761045f3660046151bf565b610a55565b6102c7610472366004615285565b610a86565b61049e7f000000000000000000000000000000000000000000000000000000000000000081565b604051908152602001610258565b6102c76104ba3660046152bb565b610e46565b61049e7f000000000000000000000000000000000000000000000000000000000000000081565b6102c76104f43660046152bb565b610e7d565b6102c76105073660046151bf565b610eae565b6102c761051a3660046152bb565b611422565b6102c7611453565b61054f6105353660046151bf565b60036020525f90815260409020546001600160a01b031681565b6040516001600160a01b039091168152602001610258565b61049e7f000000000000000000000000000000000000000000000000000000000000000081565b61049e6114a7565b5f5461054f906001600160a01b031681565b6102c761159c565b6102c76105be3660046152e8565b6115c2565b61024c6105d136600461524f565b6001600160a01b03165f908152600c6020526040902054600160801b90046001600160801b0316151590565b61049e611603565b6102c76106133660046151bf565b6116c1565b6102c7610626366004615342565b6116d5565b6102c761063936600461536b565b61170d565b61049e61064c3660046153af565b611b95565b61054f61065f3660046151bf565b600b6020525f90815260409020546001600160a01b031681565b6102c76106873660046151bf565b611ccc565b6102c761069a366004615342565b611e8d565b6102c76106ad36600461544d565b6121c9565b61049e6106c03660046154ae565b612365565b6102c76106d33660046154bf565b61263f565b6102c76106e6366004615221565b6127cc565b6102c76106f9366004615536565b6127df565b6102c761070c36600461558d565b612882565b6102c761071f3660046155cc565b61289b565b6102c76107323660046151d6565b612a2f565b6102c7612e7d565b610747612fc9565b6005546001600160a01b031661075c85612ff4565b6107658661305c565b61076e86613091565b6107788187613169565b604051632ab4fd0160e21b8152600481018790525f906001600160a01b0383169063aad3f4049060240161014060405180830381865afa1580156107be573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e2919061569c565b90506107f48782610120015188613206565b6108028160c0015187613298565b805161080c614fd8565b60408301518152606083015160208201526108278883615735565b60c08083019190915260e08085015190830152830151881480159061085e57506203f48083610120015161085b919061574c565b42105b156108765761087383602001518383886132b8565b91505b6108808883615735565b60c08201525f80546040516371d4eb2160e01b81526001600160a01b03909116916371d4eb21916108b59185916004016157dd565b5f604051808303815f87803b1580156108cc575f80fd5b505af11580156108de573d5f803e3d5ffd5b5050600954604051634a2c35a760e11b8152600481018d9052602481018c9052604481018b9052606481018a90526001600160a01b0390911692506394586b4e91506084015f604051808303815f87803b15801561093a575f80fd5b505af115801561094c573d5f803e3d5ffd5b505050506020830151604051630f83069360e01b81526001600160a01b03861691630f83069391610987918d9187908e908890600401615805565b5f604051808303815f87803b15801561099e575f80fd5b505af11580156109b0573d5f803e3d5ffd5b50505050505050505050505050565b610a5182827f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316636352211e866040518263ffffffff1660e01b8152600401610a1291815260200190565b602060405180830381865afa158015610a2d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061070c9190615839565b5050565b610a5e816133a0565b5f908152600a6020526040812080546001600160a01b03191681556001810182905560020155565b610a8e612fc9565b610a9733613458565b610aaa33856001600160801b031661349f565b6005545f805460405163309e565760e11b81523360048201526001600160a01b03938416939091169190839063613cacae9060240161016060405180830381865afa158015610afb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b1f9190615854565b9050610b30338261014001516134fa565b8051610b3a614fd8565b60e08084015161012083015260a084015190820152610b626001600160801b038a1683615735565b60c080830191909152610100840151610160830152830151610b849083615735565b61014082015260808301516001600160801b038a1614801590610bb957506203f480836101400151610bb6919061574c565b42105b15610cae575f610bc7613571565b90505f856001600160a01b03166385fe37a3846040518263ffffffff1660e01b8152600401610bf691906158e5565b602060405180830381865afa158015610c11573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c3591906158f4565b9050610c418482613611565b6101008401819052610c539089613631565b610100830151610c63908561574c565b9350610c786001600160801b038c1685615735565b60c080850191909152850151610c8e9085615735565b6101408401525f610c9f8484613652565b9050610caa816136d8565b5050505b6040516371d4eb2160e01b81526001600160a01b038516906371d4eb2190610cdc90849033906004016157dd565b5f604051808303815f87803b158015610cf3575f80fd5b505af1158015610d05573d5f803e3d5ffd5b5050600954604051630364aefb60e01b81523360048201526001600160a01b039091169250630364aefb9150602401602060405180830381865afa158015610d4f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d73919061590b565b610ded57600954604051631c403f5960e01b81523360048201526001600160801b038b166024820152604481018a9052606481018990526001600160a01b0390911690631c403f59906084015f604051808303815f87803b158015610dd6575f80fd5b505af1158015610de8573d5f803e3d5ffd5b505050505b60208301516101008201516040516206daed60ec1b81523360048201526024810192909252604482018490526001600160801b038b16606483015260848201526001600160a01b03861690636daed0009060a401610987565b6005546001600160a01b0316610e5c8184613169565b610e64614fd8565b60608101839052610e778285835f613719565b50505050565b6005546001600160a01b0316610e938184613169565b610e9b614fd8565b60408101839052610e778285835f613719565b6005545f80546008546040516331a9108f60e11b8152600481018690526001600160a01b039485169492831693918316927f00000000000000000000000000000000000000000000000000000000000000001690636352211e90602401602060405180830381865afa158015610f26573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f4a9190615839565b90505f610f578683613dd6565b9050610f638587613e53565b604051632ab4fd0160e21b8152600481018790525f906001600160a01b0387169063aad3f4049060240161014060405180830381865afa158015610fa9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fcd919061569c565b9050610fdd8433835f0151613f10565b610fe5614fd8565b60408083015182526060808401516020808501919091528085015191840191909152835160a08401525f8a8152600b90915220546001600160a01b031661102a61502d565b6001600160a01b038216156111195760405163309e565760e11b81526001600160a01b0383811660048301528a169063613cacae9060240161016060405180830381865afa15801561107e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110a29190615854565b90505f8460400151855f01516110b89190615926565b82516110c49190615926565b60e08084015161012087015260a08401519086015260808301519091506110eb9082615735565b60c08086019190915261010083015161016086015282015161110d9082615735565b61014085015250611124565b60e080850151908401525b60025460408051630fdb11cf60e01b815281515f936001600160a01b031692630fdb11cf9260048082019391829003018187875af1158015611168573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118c9190615939565b5090505f61119a8583613652565b600954909150600160a01b900460ff166111b7576111b7816136d8565b8a6001600160a01b031663735ab2a48d87878760200151885f01516040518663ffffffff1660e01b81526004016111f295949392919061595c565b5f604051808303815f87803b158015611209575f80fd5b505af115801561121b573d5f803e3d5ffd5b505050506001600160a01b0384161561124a575f8c8152600b6020526040902080546001600160a01b03191690555b6040516371d4eb2160e01b81526001600160a01b038b16906371d4eb219061127890889088906004016157dd565b5f604051808303815f87803b15801561128f575f80fd5b505af11580156112a1573d5f803e3d5ffd5b50506006546040516323b872dd60e01b81526001600160a01b0391821660048201528a8216602482015266853a0d2313c00060448201527f000000000000000000000000000000000000000000000000000000000000000090911692506323b872dd91506064016020604051808303815f875af1158015611324573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611348919061590b565b508551604051632770a7eb60e21b815233600482015260248101919091526001600160a01b038a1690639dc29fac906044015f604051808303815f87803b158015611391575f80fd5b505af11580156113a3573d5f803e3d5ffd5b505050506020860151604051634fa7288f60e11b81526001600160a01b0389811660048301526024820192909252908b1690639f4e511e906044015f604051808303815f87803b1580156113f5575f80fd5b505af1158015611407573d5f803e3d5ffd5b505050506114148c613f9a565b505050505050505050505050565b6005546001600160a01b03166114388184613169565b611440614fd8565b60a08101839052610e778285835f613719565b60075460405163b32beb5b60e01b81523360048201526001600160a01b039091169063b32beb5b906024015f604051808303815f87803b158015611495575f80fd5b505af1158015610e77573d5f803e3d5ffd5b5f8054604080516308aa0f3360e31b8152905183926001600160a01b03169163455079989160048083019260209291908290030181865afa1580156114ee573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061151291906158f4565b90505f60015f9054906101000a90046001600160a01b03166001600160a01b031663455079986040518163ffffffff1660e01b8152600401602060405180830381865afa158015611565573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158991906158f4565b9050611595818361574c565b9250505090565b6115a4613fe1565b600954600160a01b900460ff16156115b857565b6115c061400c565b565b6005546001600160a01b03166115d88188613169565b6115e0614fd8565b6115ed81888888886140b8565b6115f982898386613719565b5050505050505050565b5f8054604080516301b3d98160e11b8152905183926001600160a01b031691630367b3029160048083019260209291908290030181865afa15801561164a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061166e91906158f4565b90505f60015f9054906101000a90046001600160a01b03166001600160a01b0316630367b3026040518163ffffffff1660e01b8152600401602060405180830381865afa158015611565573d5f803e3d5ffd5b6116c96140f2565b6116d281613f9a565b50565b6005546001600160a01b03166116eb8185613169565b6116f3614fd8565b6080810184905261170682868386613719565b5050505050565b611715612fc9565b61171d61507c565b6005546001600160a01b039081168083525f5482166020840152600954909116604083015261174c9087613169565b611755866133a0565b61175e85613458565b6117678661305c565b5f868152600b6020908152604080832080546001600160a01b0319166001600160a01b038a811691909117909155600a9092529091205416156117cb575f868152600a6020526040812080546001600160a01b031916815560018101829055600201555b8051604051632ab4fd0160e21b8152600481018890526001600160a01b039091169063aad3f4049060240161014060405180830381865afa158015611812573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611836919061569c565b6080820152805160405163309e565760e11b81526001600160a01b0387811660048301529091169063613cacae9060240161016060405180830381865afa158015611883573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118a79190615854565b60c08201526118b4614fd8565b608082018051604001518252805160600151602083015260c08301805160e090810151610120850152915190910151905160a001516118f3919061574c565b60e082015260c08201516080808201519084015151915190916119159161574c565b61191f9190615735565b60c082015260808201516020810151905161193c919083866132b8565b608080840180519290925260c084015190810151915151905161195f919061574c565b6119699190615735565b60c0808301919091528281018051610100015161016084015251908101516080840151519151909161199a9161574c565b6119a49190615735565b61014082015260208201516040516371d4eb2160e01b81526001600160a01b03909116906371d4eb21906119de9084908a906004016157dd565b5f604051808303815f87803b1580156119f5575f80fd5b505af1158015611a07573d5f803e3d5ffd5b50505050815f01516001600160a01b031663b3e16c306040518060e001604052808a8152602001856080015160200151815260200185608001515f01518152602001848152602001896001600160a01b031681526020018560c001516020015181526020018560c001515f01518152506040518263ffffffff1660e01b8152600401611a939190615999565b5f604051808303815f87803b158015611aaa575f80fd5b505af1158015611abc573d5f803e3d5ffd5b5050505081604001516001600160a01b0316634cc82215886040518263ffffffff1660e01b8152600401611af291815260200190565b5f604051808303815f87803b158015611b09575f80fd5b505af1158015611b1b573d5f803e3d5ffd5b5050505081604001516001600160a01b03166336aa4c6a88888560c001516080015189896040518663ffffffff1660e01b8152600401611b5f9594939291906159fb565b5f604051808303815f87803b158015611b76575f80fd5b505af1158015611b88573d5f803e3d5ffd5b5050505050505050505050565b5f611b9f86612ff4565b611ba76150ca565b611bc08d8d8d8d8b5f805f8e8e8e8e8d6040015161411d565b81602001818152505060055f9054906101000a90046001600160a01b03166001600160a01b031663b01417758e836020015184604001518b6040518563ffffffff1660e01b8152600401611c179493929190615a27565b5f604051808303815f87803b158015611c2e575f80fd5b505af1158015611c40573d5f803e3d5ffd5b5050600954602084015160405163843aa0db60e01b81526004810191909152602481018b9052604481018d9052606481018c90526001600160a01b03909116925063843aa0db91506084015f604051808303815f87803b158015611ca2575f80fd5b505af1158015611cb4573d5f803e3d5ffd5b50505050602001519c9b505050505050505050505050565b611cd4612fc9565b611cdd33613458565b60055460405163309e565760e11b81523360048201526001600160a01b03909116905f90829063613cacae9060240161016060405180830381865afa158015611d28573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d4c9190615854565b90508060c001518310611d72576040516333c8dc3560e21b815260040160405180910390fd5b60208101518151604051636506546960e11b815233600482015260248101929092526044820152606481018490526001600160a01b0383169063ca0ca8d2906084015f604051808303815f87803b158015611dcb575f80fd5b505af1158015611ddd573d5f803e3d5ffd5b50505050611de9614fd8565b60e08083015161012083015260a08301519082015260808201518251611e0f9190615735565b60c08201526101008201516101608201528151611e2d908590615735565b6101408201525f546040516371d4eb2160e01b81526001600160a01b03909116906371d4eb2190611e6490849033906004016157dd565b5f604051808303815f87803b158015611e7b575f80fd5b505af11580156115f9573d5f803e3d5ffd5b611e95612fc9565b6005546001600160a01b0316611eab8185613e53565b604051632ab4fd0160e21b8152600481018590525f906001600160a01b0383169063aad3f4049060240161014060405180830381865afa158015611ef1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f15919061569c565b9050611f23815f0151614549565b611f2b614fd8565b604080830151825260608301516020808401919091525f888152600b90915220546001600160a01b0316611f5d61502d565b6001600160a01b038216611f905760e0808501519084015260c08401518451611f869190615735565b60c084015261206d565b60405163309e565760e11b81526001600160a01b03838116600483015286169063613cacae9060240161016060405180830381865afa158015611fd5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ff99190615854565b60e08082015161012086015260a0820151908501526080810151604086015182519293509091612029919061574c565b6120339190615735565b60c0808501919091526101008201516101608501528101516040850151825161205c919061574c565b6120669190615735565b6101408401525b6020808501518551918301518351604051635ad3396160e11b81526001600160a01b038a169463b5a672c2946120ae948f9491938a92908c90600401615a5c565b5f604051808303815f87803b1580156120c5575f80fd5b505af11580156120d7573d5f803e3d5ffd5b50505f546040516371d4eb2160e01b81526001600160a01b0390911692506371d4eb21915061210c90869086906004016157dd565b5f604051808303815f87803b158015612123575f80fd5b505af1158015612135573d5f803e3d5ffd5b505050506121438589614569565b801561215957508351686c6b935b8bbd40000011155b156115f9576040516338116fa360e01b8152600481018990526001600160a01b038616906338116fa3906024015f604051808303815f87803b15801561219d575f80fd5b505af11580156121af573d5f803e3d5ffd5b505050506115f9888560c00151888a8686608001516145f3565b6121d1612fc9565b6121da336146e2565b6121ec856001600160801b0316612ff4565b6121fe846001600160801b0316612ff4565b61221a856001600160801b0316856001600160801b0316614728565b612240836001600160801b0316866001600160801b0316866001600160801b0316614748565b670de0b6b3a76400006001600160801b03831611156122725760405163177c1b6360e31b815260040160405180910390fd5b60016001600160801b038216101561229d57604051631cbb7eed60e01b815260040160405180910390fd5b604080516060810182526001600160801b0387811682528681166020808401918252858316848601908152335f818152600c90935291869020945192518416600160801b029284169290921784559051600190930192909255600554925163499b069f60e01b815260048101929092528581166024830152841660448201526001600160a01b039091169063499b069f906064015f604051808303815f87803b158015612348575f80fd5b505af115801561235a573d5f803e3d5ffd5b505050505050505050565b5f61237e61237960e0840160c0850161524f565b613458565b6123866150ca565b6005546001600160a01b031680825263613cacae6123aa60e0860160c0870161524f565b6040516001600160e01b031960e084901b1681526001600160a01b03909116600482015260240161016060405180830381865afa1580156123ed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124119190615854565b6060820181815260e0918201516040840180516101200191909152815160a00151815190930192909252516101000151905161016001526124d9612458602085018561524f565b8460200135856040013586606001358560600151608001518860c0016020810190612483919061524f565b6060880151805160c09091015160e08c01356124a76101208e016101008f0161524f565b8d6101200160208101906124bb919061524f565b8e6101400160208101906124cf919061524f565b8d6040015161411d565b60208201526124ee60e0840160c0850161524f565b6020828101515f908152600b82526040902080546001600160a01b0319166001600160a01b03938416179055825190911690631ca2d7d9906125329086018661524f565b6020840151604085015161254c60e0890160c08a0161524f565b6060870151602081015190516040516001600160e01b031960e089901b16815261257e96959493929190600401615aa8565b5f604051808303815f87803b158015612595575f80fd5b505af11580156125a7573d5f803e3d5ffd5b505060095460208401516001600160a01b0390911692506336aa4c6a91506125d560e0870160c0880161524f565b84606001516080015187608001358860a001356040518663ffffffff1660e01b81526004016126089594939291906159fb565b5f604051808303815f87803b15801561261f575f80fd5b505af1158015612631573d5f803e3d5ffd5b505050506020015192915050565b612647612fc9565b60055461265d906001600160a01b03168a613169565b612666896133a0565b612678876001600160801b0316612ff4565b61268a866001600160801b0316612ff4565b6126a6876001600160801b0316876001600160801b0316614728565b6040518060800160405280896001600160a01b03168152602001886001600160801b03168152602001876001600160801b0316815260200182815250600a5f8b81526020019081526020015f205f820151815f015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506020820151816001015f6101000a8154816001600160801b0302191690836001600160801b0316021790555060408201518160010160106101000a8154816001600160801b0302191690836001600160801b03160217905550606082015181600201559050505f6001600160a01b0316600b5f8b81526020019081526020015f205f9054906101000a90046001600160a01b03166001600160a01b03161461235a5761235a8986868686612a2f565b6127d5826133a0565b610a518282614773565b5f6127e9886147d6565b90506127f5818661480b565b60055460405163309e565760e11b81526001600160a01b0383811660048301525f92169063613cacae9060240161016060405180830381865afa15801561283e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128629190615854565b90506128758982608001518a8a5f612a2f565b61235a898787878761170d565b61288b836133a0565b61289683838361483d565b505050565b6005546001600160a01b03166128b1818a6148c4565b6128b9614fd8565b6128c6818a8a8a8a6140b8565b6128d2828b8386613719565b6040516338116fa360e01b8152600481018b90526001600160a01b038316906338116fa3906024015f604051808303815f87803b158015612911575f80fd5b505af1158015612923573d5f803e3d5ffd5b5050505f8b8152600b60205260408120546001600160a01b0316915081156129b95760405163309e565760e11b81526001600160a01b0383811660048301525f919086169063613cacae9060240161016060405180830381865afa15801561298d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129b19190615854565b608001519150505b604051635ef3b8bf60e01b8152600481018d9052611414908d906001600160a01b03871690635ef3b8bf90602401602060405180830381865afa158015612a02573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a2691906158f4565b898986866145f3565b612a37612fc9565b612a3f6150e8565b6005546001600160a01b039081168083526009549091166020830152612a659087613169565b612a6e866133a0565b612a7785612ff4565b612a80866147d6565b6001600160a01b039081166040838101919091525f888152600b60209081529082902080546001600160a01b0319169055830151905163f476125960e01b81526004810189905291169063f4761259906024015f604051808303815f87803b158015612aea575f80fd5b505af1158015612afc573d5f803e3d5ffd5b505050602082015160405163843aa0db60e01b8152600481018990526024810188905260448101879052606481018690526001600160a01b03909116915063843aa0db906084015f604051808303815f87803b158015612b5a575f80fd5b505af1158015612b6c573d5f803e3d5ffd5b50508251604051632ab4fd0160e21b8152600481018a90526001600160a01b03909116925063aad3f404915060240161014060405180830381865afa158015612bb7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bdb919061569c565b60608201528051604080830151905163309e565760e11b81526001600160a01b03918216600482015291169063613cacae9060240161016060405180830381865afa158015612c2c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c509190615854565b60808201526060810151604081015190515f91612c6c91615926565b608083015151612c7c9190615926565b9050612c86614fd8565b60608084018051604001518352805190910151602083015260808401805160e090810151610120850152905160a00151908301525151612cc7908890615735565b6080808501510151612cd99084615735565b612ce3919061574c565b60c082015260808084015101518714801590612d1557506203f48083606001516101200151612d12919061574c565b42105b15612d3957606083015160208101519051612d32919083876132b8565b6060840151525b606083015151612d4a908890615735565b6080808501510151612d5c9084615735565b612d66919061574c565b60c0808301919091526080840180516101000151610160840152510151612d8d9083615735565b6101408201525f5460408085015190516371d4eb2160e01b81526001600160a01b03909216916371d4eb2191612dc8918591906004016157dd565b5f604051808303815f87803b158015612ddf575f80fd5b505af1158015612df1573d5f803e3d5ffd5b50505050825f01516001600160a01b031663bf49e6498985606001516020015186606001515f01518588604001518960800151602001518a608001515f01518f6040518963ffffffff1660e01b8152600401612e54989796959493929190615af0565b5f604051808303815f87803b158015612e6b575f80fd5b505af1158015611414573d5f803e3d5ffd5b600954600160a01b900460ff1615612ea857604051631de951a160e31b815260040160405180910390fd5b5f612eb1611603565b90505f612ebc6114a7565b60025460408051630fdb11cf60e01b815281519394505f9384936001600160a01b031692630fdb11cf9260048082019391829003018187875af1158015612f05573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f299190615939565b915091508015612f395750505050565b5f612f458585856148eb565b90507f00000000000000000000000000000000000000000000000000000000000000008110612f87576040516372f2224f60e01b815260040160405180910390fd5b612f8f61400c565b6040518181527f3ea78f7c2d896613dfa93eea56016064d98758df2a799e6eb38ce050c9f9c10e9060200160405180910390a15050505050565b600954600160a01b900460ff16156115c057604051631de951a160e31b815260040160405180910390fd5b60026130096064670de0b6b3a7640000615b46565b6130139190615b46565b81101561303357604051630d2693ab60e41b815260040160405180910390fd5b670de0b6b3a76400008111156116d257604051631030bfe960e21b815260040160405180910390fd5b5f818152600b60205260409020546001600160a01b0316156116d257604051634742bbb360e01b815260040160405180910390fd5b6040516331a9108f60e11b8152600481018290525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156130f6573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061311a9190615839565b9050336001600160a01b0382161480159061314b57505f828152600a60205260409020546001600160a01b03163314155b15610a51576040516334044c8d60e01b815260040160405180910390fd5b60405163e47bfaf160e01b8152600481018290525f906001600160a01b0384169063e47bfaf190602401602060405180830381865afa1580156131ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131d29190615b65565b905060018160048111156131e8576131e8615b83565b146128965760405163f1669c3d60e01b815260040160405180910390fd5b5f838152600a6020908152604091829020825160808101845281546001600160a01b031680825260018301546001600160801b0380821695840195909552600160801b900490931693810193909352600201546060830152339003610e775761328a8282602001516001600160801b031683604001516001600160801b0316614748565b610e7783826060015161491c565b808203610a51576040516322803e4960e21b815260040160405180910390fd5b5f806132c2613571565b5f80546040516385fe37a360e01b815292935090916001600160a01b03909116906385fe37a3906132f79088906004016158e5565b602060405180830381865afa158015613312573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061333691906158f4565b90506133428682613611565b61010086018190526133549085613631565b610100850151613364908761574c565b95505f6133728888856148eb565b905061337d81614946565b5f6133888785613652565b9050613393816136d8565b5095979650505050505050565b6040516331a9108f60e11b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa158015613403573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134279190615839565b6001600160a01b0316336001600160a01b0316146116d257604051631963d1e760e31b815260040160405180910390fd5b6001600160a01b0381165f908152600c6020526040812054600160801b90046001600160801b031690036116d25760405163de5a928160e01b815260040160405180910390fd5b6001600160a01b0382165f908152600c6020908152604091829020825160608101845281546001600160801b03808216808452600160801b909204169382018490526001909201549381019390935261289691849190614748565b6001600160a01b0382165f908152600c6020908152604091829020825160608101845281546001600160801b038082168352600160801b90910416928101929092526001015491810182905290613551908361574c565b4210156128965760405163dce1ae8b60e01b815260040160405180910390fd5b5f805f60025f9054906101000a90046001600160a01b03166001600160a01b0316630fdb11cf6040518163ffffffff1660e01b815260040160408051808303815f875af11580156135c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135e89190615939565b91509150801561360b576040516311b2b23360e11b815260040160405180910390fd5b50919050565b5f61362861361f8385615735565b62093a80614987565b90505b92915050565b80821115610a5157604051632337edc760e01b815260040160405180910390fd5b5f8061365c611603565b905083604001518161366e919061574c565b90508360600151816136809190615926565b90505f61368b6114a7565b905084608001518161369d919061574c565b9050846101000151816136b0919061574c565b90508460a00151816136c29190615926565b90506136cf8282866148eb565b95945050505050565b7f00000000000000000000000000000000000000000000000000000000000000008110156116d25760405163c855c3b360e01b815260040160405180910390fd5b613721612fc9565b613729615129565b5f546001600160a01b039081168252600854166020820152613749613571565b6060820181905261377a907f00000000000000000000000000000000000000000000000000000000000000006149b4565b1515608082015261378b8585613e53565b6040516331a9108f60e11b8152600481018590525f907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690636352211e90602401602060405180830381865afa1580156137f0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138149190615839565b6060850151909150819015158061382e57505f8560800151115b156138405761383d8683613dd6565b90505b5f8560400151118061385557505f8560a00151115b156138645761386486836149c9565b604051632ab4fd0160e21b8152600481018790526001600160a01b0388169063aad3f4049060240161014060405180830381865afa1580156138a8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138cc919061569c565b604084015260a08501511561393e575f686c6b935b8bbd40000084604001515f0151116138f9575f613913565b60408401515161391390686c6b935b8bbd40000090615926565b9050808660a0015111156139295760a086018190525b61393c8460200151338860a00151613f10565b505b61394785614a2f565b606085015115613967576139678360400151602001518660600151614a7d565b84606001518560400151846040015160200151613984919061574c565b61398e9190615926565b60e084015260a085015160808601516040850151516139ad919061574c565b6139b79190615926565b60c08401525f868152600b60205260409020546001600160a01b03168015156139de61502d565b5f8215613af05760405163309e565760e11b81526001600160a01b0385811660048301528c169063613cacae9060240161016060405180830381865afa158015613a2a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a4e9190615854565b91508860a001518960800151886040015160400151845f0151613a71919061574c565b613a7b919061574c565b613a859190615926565b60408089018051909101518b52516060015160208b015260e0808401516101208c015260a0840151908b01526080830151909150613ac39082615735565b60c0808b01919091526101008301516101608b0152820151613ae59082615735565b6101408a0152613b2f565b60408088018051909101518a5280516060015160208b0152805160e090810151908b01525160c09081015190880151613b299190615735565b60c08a01525b608089015115613c4c5786516040516385fe37a360e01b81525f916001600160a01b0316906385fe37a390613b68908d906004016158e5565b602060405180830381865afa158015613b83573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ba791906158f4565b9050613bb78a6080015182613611565b6101008b01819052613bc9908a613631565b8961010001518860c001818151613be0919061574c565b9052508315613c2c576101008a0151613bf9908361574c565b9150826080015182613c0b9190615735565b60c0808c0191909152830151613c219083615735565b6101408b0152613c4a565b876040015160c001518860c00151613c449190615735565b60c08b01525b505b613c598760c00151614a9e565b613c708760e001518860c0015189606001516148eb565b60a0880152613c7f8988614ac8565b8215613cfe578a6001600160a01b0316631cf740758b8960e001518a60c001518d898860200151895f01516040518863ffffffff1660e01b8152600401613ccc9796959493929190615b97565b5f604051808303815f87803b158015613ce3575f80fd5b505af1158015613cf5573d5f803e3d5ffd5b50505050613d65565b60e087015160c08801516040516203af7d60eb1b81526001600160a01b038e1692631d7be80092613d37928f9291908f90600401615be4565b5f604051808303815f87803b158015613d4e575f80fd5b505af1158015613d60573d5f803e3d5ffd5b505050505b86516040516371d4eb2160e01b81526001600160a01b03909116906371d4eb2190613d96908c9088906004016157dd565b5f604051808303815f87803b158015613dad575f80fd5b505af1158015613dbf573d5f803e3d5ffd5b50505050611b88858a89602001518a5f0151614b15565b5f82815260046020526040812080546001909101546001600160a01b03918216919081169084163314801590613e155750336001600160a01b03831614155b15613e33576040516310bb5c9d60e31b815260040160405180910390fd5b6001600160a01b038116613e4b57839250505061362b565b949350505050565b60405163e47bfaf160e01b8152600481018290525f906001600160a01b0384169063e47bfaf190602401602060405180830381865afa158015613e98573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ebc9190615b65565b90506001816004811115613ed257613ed2615b83565b14158015613ef257506004816004811115613eef57613eef615b83565b14155b156128965760405163019dc6e560e11b815260040160405180910390fd5b6040516370a0823160e01b81526001600160a01b0383811660048301528291908516906370a0823190602401602060405180830381865afa158015613f57573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f7b91906158f4565b1015612896576040516307a5137f60e11b815260040160405180910390fd5b5f818152600a6020908152604080832080546001600160a01b03199081168255600182018590556002909101849055600b909252909120805490911690556116d281614c57565b6002546001600160a01b031633146115c0576040516311a780f560e31b815260040160405180910390fd5b5f805460408051631bfa0d7b60e01b815290516001600160a01b0390921692631bfa0d7b9260048084019382900301818387803b15801561404b575f80fd5b505af115801561405d573d5f803e3d5ffd5b50506009805460ff60a01b1916600160a01b17905550506005546040805163fc0e74d160e01b815290516001600160a01b039092169163fc0e74d1916004808201925f9290919082900301818387803b158015611495575f80fd5b82156140ca57604085018490526140d2565b606085018490525b80156140e45760808501829052611706565b60a085018290525050505050565b6005546001600160a01b031633146115c057604051631c55689560e31b815260040160405180910390fd5b5f614126612fc9565b61418f6040518061014001604052805f6001600160a01b031681526020015f6001600160a01b031681526020015f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b6005546001600160a01b0390811682525f54811660208301526008541660408201526141b9613571565b8160800181815250508e8e6040516020016141e99291906001600160a01b03929092168252602082015260400190565b60408051601f19818403018152919052805160209091012060608201819052815161421391614cfd565b604083018d9052608083018c90528a61422c8d8b61574c565b6142369190615735565b60c084015260208101516040516385fe37a360e01b81526001600160a01b03909116906385fe37a39061426d9086906004016158e5565b602060405180830381865afa158015614288573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142ac91906158f4565b60a0820181905260808401516142c191613611565b61010084018190526142d39088613631565b82610100015183608001516142e8919061574c565b60c082018190526142f890614a9e565b6001600160a01b038a16614320578a8160c001516143169190615735565b60c0840152614364565b8a8160c001518a614331919061574c565b61433b9190615735565b60c0808501919091528101518890614353908b61574c565b61435d9190615735565b6101408401525b6143778d8260c0015183608001516148eb565b60e0820181905261438790614946565b614395838260800151613652565b61010082018190526143a6906136d8565b6143b4816060015187614773565b6143c38160600151868661483d565b80602001516001600160a01b03166371d4eb21848c6040518363ffffffff1660e01b81526004016143f59291906157dd565b5f604051808303815f87803b15801561440c575f80fd5b505af115801561441e573d5f803e3d5ffd5b5050505061443081602001518e614d99565b60408082015190516340c10f1960e01b8152336004820152602481018e90526001600160a01b03909116906340c10f19906044015f604051808303815f87803b15801561447b575f80fd5b505af115801561448d573d5f803e3d5ffd5b50506006546040516323b872dd60e01b81523360048201526001600160a01b03918216602482015266853a0d2313c00060448201527f000000000000000000000000000000000000000000000000000000000000000090911692506323b872dd91506064016020604051808303815f875af115801561450e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614532919061590b565b50606001519e9d5050505050505050505050505050565b805f036116d2576040516302dedfbf60e31b815260040160405180910390fd5b60405163e47bfaf160e01b8152600481018290525f9081906001600160a01b0385169063e47bfaf190602401602060405180830381865afa1580156145b0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906145d49190615b65565b905060048160048111156145ea576145ea615b83565b14949350505050565b6001600160a01b0382166146745760095460405163843aa0db60e01b8152600481018890526024810187905260448101869052606481018590526001600160a01b039091169063843aa0db906084015f604051808303815f87803b158015614659575f80fd5b505af115801561466b573d5f803e3d5ffd5b505050506146da565b600954604051631b55263560e11b81526001600160a01b03909116906336aa4c6a906146ac908990869086908a908a906004016159fb565b5f604051808303815f87803b1580156146c3575f80fd5b505af11580156146d5573d5f803e3d5ffd5b505050505b505050505050565b6001600160a01b0381165f908152600c6020526040902054600160801b90046001600160801b0316156116d257604051632a16d50160e01b815260040160405180910390fd5b808210610a5157604051632a2b2ad160e01b815260040160405180910390fd5b8282118061475557508083115b1561289657604051639736ee7560e01b815260040160405180910390fd5b5f8281526003602090815260409182902080546001600160a01b0319166001600160a01b038516908117909155915191825283917f3942babd464ceb1c7d319f75245a8cd41334592b45507f072e7020e63c22a8dc910160405180910390a25050565b5f818152600b60205260408120546001600160a01b03168061362b576040516393f3f3c160e01b815260040160405180910390fd5b806001600160a01b0316826001600160a01b031603610a5157604051631c56f50360e01b815260040160405180910390fd5b6148478282614e1f565b5f8381526004602090815260409182902080546001600160a01b03199081166001600160a01b0387811691821784556001909301805490921692861692831790915583519081529182015284917f649442545e0f313a6d8087b19bc47bd2bd9b63f79d23a773446e00d2ea01d169910160405180910390a2505050565b6148ce8282614569565b610a515760405163067c71a160e41b815260040160405180910390fd5b5f8215614911575f836148fe8487615735565b6149089190615b46565b91506149159050565b505f195b9392505050565b614926818361574c565b421015610a5157604051638510088360e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000008110156116d2576040516309a8aadb60e31b815260040160405180910390fd5b5f670de0b6b3a76400006301e133806149a08486615735565b6149aa9190615b46565b6136289190615b46565b5f806149bf84614e5c565b9092119392505050565b5f828152600360205260409020546001600160a01b0390811690821633148015906149fc57506001600160a01b03811615155b8015614a115750336001600160a01b03821614155b1561289657604051636522e96960e01b815260040160405180910390fd5b6040810151158015614a4357506060810151155b8015614a5157506080810151155b8015614a5f575060a0810151155b156116d2576040516356515c5360e01b815260040160405180910390fd5b81811115610a515760405163b30a1bc960e01b815260040160405180910390fd5b686c6b935b8bbd4000008110156116d25760405163f1e4191360e01b815260040160405180910390fd5b614ad58160a00151614946565b5f614ae4838360600151613652565b9050816080015115614b0c57614afe836080015182614e7e565b612896838360600151614eca565b612896816136d8565b608083015115614b885760808301516040516340c10f1960e01b81526001600160a01b0386811660048301526024820192909252908316906340c10f19906044015f604051808303815f87803b158015614b6d575f80fd5b505af1158015614b7f573d5f803e3d5ffd5b50505050614bf4565b60a083015115614bf45760a0830151604051632770a7eb60e21b815233600482015260248101919091526001600160a01b03831690639dc29fac906044015f604051808303815f87803b158015614bdd575f80fd5b505af1158015614bef573d5f803e3d5ffd5b505050505b604083015115614c1157614c0c818460400151614d99565b610e77565b606083015115610e77576060830151604051634fa7288f60e11b81526001600160a01b038681166004830152602482019290925290821690639f4e511e90604401611e64565b5f81815260036020908152604080832080546001600160a01b031990811690915560048352818420805482168155600101805490911690555191825282917f3942babd464ceb1c7d319f75245a8cd41334592b45507f072e7020e63c22a8dc910160405180910390a2604080515f808252602082015282917f649442545e0f313a6d8087b19bc47bd2bd9b63f79d23a773446e00d2ea01d169910160405180910390a250565b60405163e47bfaf160e01b8152600481018290525f906001600160a01b0384169063e47bfaf190602401602060405180830381865afa158015614d42573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614d669190615b65565b90505f816004811115614d7b57614d7b615b83565b14612896576040516376ac6c0d60e11b815260040160405180910390fd5b614dce6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016338484614f11565b604051632bcbcbcb60e01b8152600481018290526001600160a01b03831690632bcbcbcb906024015f604051808303815f87803b158015614e0d575f80fd5b505af11580156146da573d5f803e3d5ffd5b6001600160a01b038216158015614e3e57506001600160a01b03811615155b15610a5157604051632235921760e01b815260040160405180910390fd5b5f80614e66611603565b90505f614e716114a7565b9050613e4b8282866148eb565b5f82118015614eac57507f000000000000000000000000000000000000000000000000000000000000000081105b15610a515760405163c855c3b360e01b815260040160405180910390fd5b808260600151614eda9190615735565b670de0b6b3a76400008360a00151614ef29190615735565b1015610a515760405163d676956360e01b815260040160405180910390fd5b604080516001600160a01b038581166024830152841660448201526064808201849052825180830390910181526084909101909152602080820180516001600160e01b03166323b872dd60e01b1781528251610e7793889390925f9283929183919082885af180614f87576040513d5f823e3d81fd5b50505f513d91508115614f9e578060011415614fab565b6001600160a01b0384163b155b15610e7757604051635274afe760e01b81526001600160a01b038516600482015260240160405180910390fd5b6040518061018001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040518061016001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040805160e0810182525f808252602082018190529181018290526060810191909152608081016150ab615176565b81526020016150b861502d565b81526020016150c561502d565b905290565b604080516080810182525f80825260208201529081016150b8614fd8565b6040805160c0810182525f808252602082018190529181019190915260608101615110615176565b815260200161511d61502d565b81526020015f81525090565b60408051610120810182525f8082526020820152908101615148615176565b81526020015f81526020015f151581526020015f81526020015f81526020015f81526020015f151581525090565b6040518061014001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f602082840312156151cf575f80fd5b5035919050565b5f805f805f60a086880312156151ea575f80fd5b505083359560208501359550604085013594606081013594506080013592509050565b6001600160a01b03811681146116d2575f80fd5b5f8060408385031215615232575f80fd5b8235915060208301356152448161520d565b809150509250929050565b5f6020828403121561525f575f80fd5b81356149158161520d565b80356001600160801b0381168114615280575f80fd5b919050565b5f805f8060808587031215615298575f80fd5b6152a18561526a565b966020860135965060408601359560600135945092505050565b5f80604083850312156152cc575f80fd5b50508035926020909101359150565b80151581146116d2575f80fd5b5f805f805f8060c087890312156152fd575f80fd5b86359550602087013594506040870135615316816152db565b935060608701359250608087013561532d816152db565b8092505060a087013590509295509295509295565b5f805f60608486031215615354575f80fd5b505081359360208301359350604090920135919050565b5f805f805f60a0868803121561537f575f80fd5b8535945060208601356153918161520d565b94979496505050506040830135926060810135926080909101359150565b5f805f805f805f805f805f6101608c8e0312156153ca575f80fd5b8b356153d58161520d565b9a5060208c0135995060408c0135985060608c0135975060808c0135965060a08c0135955060c08c0135945060e08c013593506101008c01356154178161520d565b92506101208c01356154288161520d565b91506101408c01356154398161520d565b809150509295989b509295989b9093969950565b5f805f805f60a08688031215615461575f80fd5b61546a8661526a565b94506154786020870161526a565b93506154866040870161526a565b92506154946060870161526a565b91506154a26080870161526a565b90509295509295909350565b5f610160828403121561360b575f80fd5b5f805f805f805f805f6101208a8c0312156154d8575f80fd5b8935985060208a01356154ea8161520d565b97506154f860408b0161526a565b965061550660608b0161526a565b989b979a50959860808101359760a0820135975060c0820135965060e08201359550610100909101359350915050565b5f805f805f805f60e0888a03121561554c575f80fd5b873596506020880135955060408801359450606088013561556c8161520d565b9699959850939660808101359560a0820135955060c0909101359350915050565b5f805f6060848603121561559f575f80fd5b8335925060208401356155b18161520d565b915060408401356155c18161520d565b809150509250925092565b5f805f805f805f80610100898b0312156155e4575f80fd5b883597506020890135965060408901356155fd816152db565b9550606089013594506080890135615614816152db565b979a969950949793969560a0850135955060c08501359460e001359350915050565b604051610140810167ffffffffffffffff8111828210171561566657634e487b7160e01b5f52604160045260245ffd5b60405290565b604051610160810167ffffffffffffffff8111828210171561566657634e487b7160e01b5f52604160045260245ffd5b5f61014082840312156156ad575f80fd5b6156b5615636565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e08201526101008084015181830152506101208084015181830152508091505092915050565b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761362b5761362b615721565b8082018082111561362b5761362b615721565b805182526020810151602083015260408101516040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e08301526101008082015181840152506101208082015181840152506101408082015181840152506101608082015181840152505050565b6101a081016157ec828561575f565b6001600160a01b03929092166101809190910152919050565b5f6102008201905086825285602083015284604083015283606083015261582f608083018461575f565b9695505050505050565b5f60208284031215615849575f80fd5b81516149158161520d565b5f6101608284031215615865575f80fd5b61586d61566c565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e08201526101008084015181830152506101208084015181830152506101408084015181830152508091505092915050565b610180810161362b828461575f565b5f60208284031215615904575f80fd5b5051919050565b5f6020828403121561591b575f80fd5b8151614915816152db565b8181038181111561362b5761362b615721565b5f806040838503121561594a575f80fd5b825191506020830151615244816152db565b8581526102008101615971602083018761575f565b6001600160a01b03949094166101a08201526101c08101929092526101e09091015292915050565b5f6102408201905082518252602083015160208301526040830151604083015260608301516159cb606084018261575f565b5060808301516001600160a01b03166101e083015260a083015161020083015260c0909201516102209091015290565b9485526001600160a01b0393909316602085015260408401919091526060830152608082015260a00190565b6001600160a01b0385168152602081018490526101e08101615a4c604083018561575f565b826101c083015295945050505050565b87815260208101879052604081018690526001600160a01b03851660608201526080810184905260a081018390526102408101615a9c60c083018461575f565b98975050505050505050565b6001600160a01b03878116825260208201879052610220820190615acf604084018861575f565b949094166101c08201526101e0810192909252610200909101529392505050565b88815260208101889052604081018790526102608101615b13606083018861575f565b6001600160a01b03959095166101e082015261020081019390935261022083019190915261024090910152949350505050565b5f82615b6057634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215615b75575f80fd5b815160058110614915575f80fd5b634e487b7160e01b5f52602160045260245ffd5b87815260208101879052604081018690526102408101615bba606083018761575f565b6001600160a01b03949094166101e082015261020081019290925261022090910152949350505050565b84815260208101849052604081018390526101e081016136cf606083018461575f56fea2646970667358221220c2a20eba6d2651cc5f2e529e7dfb443fd78179e6ec775cc8e04d1a8525c79cb764736f6c63430008180033000000000000000000000000ba0f2b2cae0f71997c758ea4e266f6f0fff7d8a7

Deployed Bytecode

0x608060405234801561000f575f80fd5b5060043610610234575f3560e01c806382e43a4911610135578063ba5f47a6116100b4578063d5479cd411610079578063d5479cd4146106eb578063d6491eaf146106fe578063dcfbd29314610711578063f9ef19ca14610724578063fc0e74d114610737575f80fd5b8063ba5f47a61461068c578063bcb266c01461069f578063c440844f146106b2578063c6ac2465146106c5578063d3695fa5146106d8575f80fd5b806390de348a116100fa57806390de348a146106185780639537f0011461062b5780639cb90ba61461063e578063a0df5cd514610651578063ad9be12714610679575f80fd5b806382e43a49146105a857806384e5253c146105b057806385c44a1a146105c3578063887105d3146105fd5780638fef27ab14610605575f80fd5b8063580de360116101c15780636f0b0c1c116101865780636f0b0c1c1461051f57806370986fe114610527578063794e572414610567578063795d26c31461058e5780637f7dde4a14610596575f80fd5b8063580de360146104ac57806358d5a961146104bf57806359f54f40146104e65780635aa6d461146104f95780635cd067cf1461050c575f80fd5b80634c1306b3116102075780634c1306b3146102dc5780634ed1bd5d146103af57806353eb288514610451578063570fb750146104645780635733d58f14610477575f80fd5b806306ff8dfb146102385780630e01617c1461026157806326f4e252146102b4578063292a3f0b146102c9575b5f80fd5b60095461024c90600160a01b900460ff1681565b60405190151581526020015b60405180910390f35b61029461026f3660046151bf565b60046020525f9081526040902080546001909101546001600160a01b03918216911682565b604080516001600160a01b03938416815292909116602083015201610258565b6102c76102c23660046151d6565b61073f565b005b6102c76102d7366004615221565b6109bf565b6103656102ea3660046151bf565b60408051608080820183525f80835260208084018290528385018290526060938401829052948152600a85528390208351918201845280546001600160a01b0316825260018101546001600160801b0380821696840196909652600160801b9004909416928101929092526002909201549181019190915290565b6040805182516001600160a01b031681526020808401516001600160801b039081169183019190915283830151169181019190915260609182015191810191909152608001610258565b6104216103bd36600461524f565b60408051606080820183525f80835260208084018290529284018190526001600160a01b03949094168452600c8252928290208251938401835280546001600160801b038082168652600160801b9091041691840191909152600101549082015290565b6040805182516001600160801b039081168252602080850151909116908201529181015190820152606001610258565b6102c761045f3660046151bf565b610a55565b6102c7610472366004615285565b610a86565b61049e7f00000000000000000000000000000000000000000000000014d1120d7b16000081565b604051908152602001610258565b6102c76104ba3660046152bb565b610e46565b61049e7f0000000000000000000000000000000000000000000000000f43fc2c04ee000081565b6102c76104f43660046152bb565b610e7d565b6102c76105073660046151bf565b610eae565b6102c761051a3660046152bb565b611422565b6102c7611453565b61054f6105353660046151bf565b60036020525f90815260409020546001600160a01b031681565b6040516001600160a01b039091168152602001610258565b61049e7f0000000000000000000000000000000000000000000000000f43fc2c04ee000081565b61049e6114a7565b5f5461054f906001600160a01b031681565b6102c761159c565b6102c76105be3660046152e8565b6115c2565b61024c6105d136600461524f565b6001600160a01b03165f908152600c6020526040902054600160801b90046001600160801b0316151590565b61049e611603565b6102c76106133660046151bf565b6116c1565b6102c7610626366004615342565b6116d5565b6102c761063936600461536b565b61170d565b61049e61064c3660046153af565b611b95565b61054f61065f3660046151bf565b600b6020525f90815260409020546001600160a01b031681565b6102c76106873660046151bf565b611ccc565b6102c761069a366004615342565b611e8d565b6102c76106ad36600461544d565b6121c9565b61049e6106c03660046154ae565b612365565b6102c76106d33660046154bf565b61263f565b6102c76106e6366004615221565b6127cc565b6102c76106f9366004615536565b6127df565b6102c761070c36600461558d565b612882565b6102c761071f3660046155cc565b61289b565b6102c76107323660046151d6565b612a2f565b6102c7612e7d565b610747612fc9565b6005546001600160a01b031661075c85612ff4565b6107658661305c565b61076e86613091565b6107788187613169565b604051632ab4fd0160e21b8152600481018790525f906001600160a01b0383169063aad3f4049060240161014060405180830381865afa1580156107be573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e2919061569c565b90506107f48782610120015188613206565b6108028160c0015187613298565b805161080c614fd8565b60408301518152606083015160208201526108278883615735565b60c08083019190915260e08085015190830152830151881480159061085e57506203f48083610120015161085b919061574c565b42105b156108765761087383602001518383886132b8565b91505b6108808883615735565b60c08201525f80546040516371d4eb2160e01b81526001600160a01b03909116916371d4eb21916108b59185916004016157dd565b5f604051808303815f87803b1580156108cc575f80fd5b505af11580156108de573d5f803e3d5ffd5b5050600954604051634a2c35a760e11b8152600481018d9052602481018c9052604481018b9052606481018a90526001600160a01b0390911692506394586b4e91506084015f604051808303815f87803b15801561093a575f80fd5b505af115801561094c573d5f803e3d5ffd5b505050506020830151604051630f83069360e01b81526001600160a01b03861691630f83069391610987918d9187908e908890600401615805565b5f604051808303815f87803b15801561099e575f80fd5b505af11580156109b0573d5f803e3d5ffd5b50505050505050505050505050565b610a5182827f000000000000000000000000c56e6030516a32bbec08496d44abb569e0497f9c6001600160a01b0316636352211e866040518263ffffffff1660e01b8152600401610a1291815260200190565b602060405180830381865afa158015610a2d573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061070c9190615839565b5050565b610a5e816133a0565b5f908152600a6020526040812080546001600160a01b03191681556001810182905560020155565b610a8e612fc9565b610a9733613458565b610aaa33856001600160801b031661349f565b6005545f805460405163309e565760e11b81523360048201526001600160a01b03938416939091169190839063613cacae9060240161016060405180830381865afa158015610afb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b1f9190615854565b9050610b30338261014001516134fa565b8051610b3a614fd8565b60e08084015161012083015260a084015190820152610b626001600160801b038a1683615735565b60c080830191909152610100840151610160830152830151610b849083615735565b61014082015260808301516001600160801b038a1614801590610bb957506203f480836101400151610bb6919061574c565b42105b15610cae575f610bc7613571565b90505f856001600160a01b03166385fe37a3846040518263ffffffff1660e01b8152600401610bf691906158e5565b602060405180830381865afa158015610c11573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c3591906158f4565b9050610c418482613611565b6101008401819052610c539089613631565b610100830151610c63908561574c565b9350610c786001600160801b038c1685615735565b60c080850191909152850151610c8e9085615735565b6101408401525f610c9f8484613652565b9050610caa816136d8565b5050505b6040516371d4eb2160e01b81526001600160a01b038516906371d4eb2190610cdc90849033906004016157dd565b5f604051808303815f87803b158015610cf3575f80fd5b505af1158015610d05573d5f803e3d5ffd5b5050600954604051630364aefb60e01b81523360048201526001600160a01b039091169250630364aefb9150602401602060405180830381865afa158015610d4f573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d73919061590b565b610ded57600954604051631c403f5960e01b81523360048201526001600160801b038b166024820152604481018a9052606481018990526001600160a01b0390911690631c403f59906084015f604051808303815f87803b158015610dd6575f80fd5b505af1158015610de8573d5f803e3d5ffd5b505050505b60208301516101008201516040516206daed60ec1b81523360048201526024810192909252604482018490526001600160801b038b16606483015260848201526001600160a01b03861690636daed0009060a401610987565b6005546001600160a01b0316610e5c8184613169565b610e64614fd8565b60608101839052610e778285835f613719565b50505050565b6005546001600160a01b0316610e938184613169565b610e9b614fd8565b60408101839052610e778285835f613719565b6005545f80546008546040516331a9108f60e11b8152600481018690526001600160a01b039485169492831693918316927f000000000000000000000000c56e6030516a32bbec08496d44abb569e0497f9c1690636352211e90602401602060405180830381865afa158015610f26573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f4a9190615839565b90505f610f578683613dd6565b9050610f638587613e53565b604051632ab4fd0160e21b8152600481018790525f906001600160a01b0387169063aad3f4049060240161014060405180830381865afa158015610fa9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fcd919061569c565b9050610fdd8433835f0151613f10565b610fe5614fd8565b60408083015182526060808401516020808501919091528085015191840191909152835160a08401525f8a8152600b90915220546001600160a01b031661102a61502d565b6001600160a01b038216156111195760405163309e565760e11b81526001600160a01b0383811660048301528a169063613cacae9060240161016060405180830381865afa15801561107e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110a29190615854565b90505f8460400151855f01516110b89190615926565b82516110c49190615926565b60e08084015161012087015260a08401519086015260808301519091506110eb9082615735565b60c08086019190915261010083015161016086015282015161110d9082615735565b61014085015250611124565b60e080850151908401525b60025460408051630fdb11cf60e01b815281515f936001600160a01b031692630fdb11cf9260048082019391829003018187875af1158015611168573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061118c9190615939565b5090505f61119a8583613652565b600954909150600160a01b900460ff166111b7576111b7816136d8565b8a6001600160a01b031663735ab2a48d87878760200151885f01516040518663ffffffff1660e01b81526004016111f295949392919061595c565b5f604051808303815f87803b158015611209575f80fd5b505af115801561121b573d5f803e3d5ffd5b505050506001600160a01b0384161561124a575f8c8152600b6020526040902080546001600160a01b03191690555b6040516371d4eb2160e01b81526001600160a01b038b16906371d4eb219061127890889088906004016157dd565b5f604051808303815f87803b15801561128f575f80fd5b505af11580156112a1573d5f803e3d5ffd5b50506006546040516323b872dd60e01b81526001600160a01b0391821660048201528a8216602482015266853a0d2313c00060448201527f0000000000000000000000004223f8af31e07815f1a7437336f093f37c065efe90911692506323b872dd91506064016020604051808303815f875af1158015611324573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611348919061590b565b508551604051632770a7eb60e21b815233600482015260248101919091526001600160a01b038a1690639dc29fac906044015f604051808303815f87803b158015611391575f80fd5b505af11580156113a3573d5f803e3d5ffd5b505050506020860151604051634fa7288f60e11b81526001600160a01b0389811660048301526024820192909252908b1690639f4e511e906044015f604051808303815f87803b1580156113f5575f80fd5b505af1158015611407573d5f803e3d5ffd5b505050506114148c613f9a565b505050505050505050505050565b6005546001600160a01b03166114388184613169565b611440614fd8565b60a08101839052610e778285835f613719565b60075460405163b32beb5b60e01b81523360048201526001600160a01b039091169063b32beb5b906024015f604051808303815f87803b158015611495575f80fd5b505af1158015610e77573d5f803e3d5ffd5b5f8054604080516308aa0f3360e31b8152905183926001600160a01b03169163455079989160048083019260209291908290030181865afa1580156114ee573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061151291906158f4565b90505f60015f9054906101000a90046001600160a01b03166001600160a01b031663455079986040518163ffffffff1660e01b8152600401602060405180830381865afa158015611565573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061158991906158f4565b9050611595818361574c565b9250505090565b6115a4613fe1565b600954600160a01b900460ff16156115b857565b6115c061400c565b565b6005546001600160a01b03166115d88188613169565b6115e0614fd8565b6115ed81888888886140b8565b6115f982898386613719565b5050505050505050565b5f8054604080516301b3d98160e11b8152905183926001600160a01b031691630367b3029160048083019260209291908290030181865afa15801561164a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061166e91906158f4565b90505f60015f9054906101000a90046001600160a01b03166001600160a01b0316630367b3026040518163ffffffff1660e01b8152600401602060405180830381865afa158015611565573d5f803e3d5ffd5b6116c96140f2565b6116d281613f9a565b50565b6005546001600160a01b03166116eb8185613169565b6116f3614fd8565b6080810184905261170682868386613719565b5050505050565b611715612fc9565b61171d61507c565b6005546001600160a01b039081168083525f5482166020840152600954909116604083015261174c9087613169565b611755866133a0565b61175e85613458565b6117678661305c565b5f868152600b6020908152604080832080546001600160a01b0319166001600160a01b038a811691909117909155600a9092529091205416156117cb575f868152600a6020526040812080546001600160a01b031916815560018101829055600201555b8051604051632ab4fd0160e21b8152600481018890526001600160a01b039091169063aad3f4049060240161014060405180830381865afa158015611812573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611836919061569c565b6080820152805160405163309e565760e11b81526001600160a01b0387811660048301529091169063613cacae9060240161016060405180830381865afa158015611883573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118a79190615854565b60c08201526118b4614fd8565b608082018051604001518252805160600151602083015260c08301805160e090810151610120850152915190910151905160a001516118f3919061574c565b60e082015260c08201516080808201519084015151915190916119159161574c565b61191f9190615735565b60c082015260808201516020810151905161193c919083866132b8565b608080840180519290925260c084015190810151915151905161195f919061574c565b6119699190615735565b60c0808301919091528281018051610100015161016084015251908101516080840151519151909161199a9161574c565b6119a49190615735565b61014082015260208201516040516371d4eb2160e01b81526001600160a01b03909116906371d4eb21906119de9084908a906004016157dd565b5f604051808303815f87803b1580156119f5575f80fd5b505af1158015611a07573d5f803e3d5ffd5b50505050815f01516001600160a01b031663b3e16c306040518060e001604052808a8152602001856080015160200151815260200185608001515f01518152602001848152602001896001600160a01b031681526020018560c001516020015181526020018560c001515f01518152506040518263ffffffff1660e01b8152600401611a939190615999565b5f604051808303815f87803b158015611aaa575f80fd5b505af1158015611abc573d5f803e3d5ffd5b5050505081604001516001600160a01b0316634cc82215886040518263ffffffff1660e01b8152600401611af291815260200190565b5f604051808303815f87803b158015611b09575f80fd5b505af1158015611b1b573d5f803e3d5ffd5b5050505081604001516001600160a01b03166336aa4c6a88888560c001516080015189896040518663ffffffff1660e01b8152600401611b5f9594939291906159fb565b5f604051808303815f87803b158015611b76575f80fd5b505af1158015611b88573d5f803e3d5ffd5b5050505050505050505050565b5f611b9f86612ff4565b611ba76150ca565b611bc08d8d8d8d8b5f805f8e8e8e8e8d6040015161411d565b81602001818152505060055f9054906101000a90046001600160a01b03166001600160a01b031663b01417758e836020015184604001518b6040518563ffffffff1660e01b8152600401611c179493929190615a27565b5f604051808303815f87803b158015611c2e575f80fd5b505af1158015611c40573d5f803e3d5ffd5b5050600954602084015160405163843aa0db60e01b81526004810191909152602481018b9052604481018d9052606481018c90526001600160a01b03909116925063843aa0db91506084015f604051808303815f87803b158015611ca2575f80fd5b505af1158015611cb4573d5f803e3d5ffd5b50505050602001519c9b505050505050505050505050565b611cd4612fc9565b611cdd33613458565b60055460405163309e565760e11b81523360048201526001600160a01b03909116905f90829063613cacae9060240161016060405180830381865afa158015611d28573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611d4c9190615854565b90508060c001518310611d72576040516333c8dc3560e21b815260040160405180910390fd5b60208101518151604051636506546960e11b815233600482015260248101929092526044820152606481018490526001600160a01b0383169063ca0ca8d2906084015f604051808303815f87803b158015611dcb575f80fd5b505af1158015611ddd573d5f803e3d5ffd5b50505050611de9614fd8565b60e08083015161012083015260a08301519082015260808201518251611e0f9190615735565b60c08201526101008201516101608201528151611e2d908590615735565b6101408201525f546040516371d4eb2160e01b81526001600160a01b03909116906371d4eb2190611e6490849033906004016157dd565b5f604051808303815f87803b158015611e7b575f80fd5b505af11580156115f9573d5f803e3d5ffd5b611e95612fc9565b6005546001600160a01b0316611eab8185613e53565b604051632ab4fd0160e21b8152600481018590525f906001600160a01b0383169063aad3f4049060240161014060405180830381865afa158015611ef1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611f15919061569c565b9050611f23815f0151614549565b611f2b614fd8565b604080830151825260608301516020808401919091525f888152600b90915220546001600160a01b0316611f5d61502d565b6001600160a01b038216611f905760e0808501519084015260c08401518451611f869190615735565b60c084015261206d565b60405163309e565760e11b81526001600160a01b03838116600483015286169063613cacae9060240161016060405180830381865afa158015611fd5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ff99190615854565b60e08082015161012086015260a0820151908501526080810151604086015182519293509091612029919061574c565b6120339190615735565b60c0808501919091526101008201516101608501528101516040850151825161205c919061574c565b6120669190615735565b6101408401525b6020808501518551918301518351604051635ad3396160e11b81526001600160a01b038a169463b5a672c2946120ae948f9491938a92908c90600401615a5c565b5f604051808303815f87803b1580156120c5575f80fd5b505af11580156120d7573d5f803e3d5ffd5b50505f546040516371d4eb2160e01b81526001600160a01b0390911692506371d4eb21915061210c90869086906004016157dd565b5f604051808303815f87803b158015612123575f80fd5b505af1158015612135573d5f803e3d5ffd5b505050506121438589614569565b801561215957508351686c6b935b8bbd40000011155b156115f9576040516338116fa360e01b8152600481018990526001600160a01b038616906338116fa3906024015f604051808303815f87803b15801561219d575f80fd5b505af11580156121af573d5f803e3d5ffd5b505050506115f9888560c00151888a8686608001516145f3565b6121d1612fc9565b6121da336146e2565b6121ec856001600160801b0316612ff4565b6121fe846001600160801b0316612ff4565b61221a856001600160801b0316856001600160801b0316614728565b612240836001600160801b0316866001600160801b0316866001600160801b0316614748565b670de0b6b3a76400006001600160801b03831611156122725760405163177c1b6360e31b815260040160405180910390fd5b60016001600160801b038216101561229d57604051631cbb7eed60e01b815260040160405180910390fd5b604080516060810182526001600160801b0387811682528681166020808401918252858316848601908152335f818152600c90935291869020945192518416600160801b029284169290921784559051600190930192909255600554925163499b069f60e01b815260048101929092528581166024830152841660448201526001600160a01b039091169063499b069f906064015f604051808303815f87803b158015612348575f80fd5b505af115801561235a573d5f803e3d5ffd5b505050505050505050565b5f61237e61237960e0840160c0850161524f565b613458565b6123866150ca565b6005546001600160a01b031680825263613cacae6123aa60e0860160c0870161524f565b6040516001600160e01b031960e084901b1681526001600160a01b03909116600482015260240161016060405180830381865afa1580156123ed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124119190615854565b6060820181815260e0918201516040840180516101200191909152815160a00151815190930192909252516101000151905161016001526124d9612458602085018561524f565b8460200135856040013586606001358560600151608001518860c0016020810190612483919061524f565b6060880151805160c09091015160e08c01356124a76101208e016101008f0161524f565b8d6101200160208101906124bb919061524f565b8e6101400160208101906124cf919061524f565b8d6040015161411d565b60208201526124ee60e0840160c0850161524f565b6020828101515f908152600b82526040902080546001600160a01b0319166001600160a01b03938416179055825190911690631ca2d7d9906125329086018661524f565b6020840151604085015161254c60e0890160c08a0161524f565b6060870151602081015190516040516001600160e01b031960e089901b16815261257e96959493929190600401615aa8565b5f604051808303815f87803b158015612595575f80fd5b505af11580156125a7573d5f803e3d5ffd5b505060095460208401516001600160a01b0390911692506336aa4c6a91506125d560e0870160c0880161524f565b84606001516080015187608001358860a001356040518663ffffffff1660e01b81526004016126089594939291906159fb565b5f604051808303815f87803b15801561261f575f80fd5b505af1158015612631573d5f803e3d5ffd5b505050506020015192915050565b612647612fc9565b60055461265d906001600160a01b03168a613169565b612666896133a0565b612678876001600160801b0316612ff4565b61268a866001600160801b0316612ff4565b6126a6876001600160801b0316876001600160801b0316614728565b6040518060800160405280896001600160a01b03168152602001886001600160801b03168152602001876001600160801b0316815260200182815250600a5f8b81526020019081526020015f205f820151815f015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506020820151816001015f6101000a8154816001600160801b0302191690836001600160801b0316021790555060408201518160010160106101000a8154816001600160801b0302191690836001600160801b03160217905550606082015181600201559050505f6001600160a01b0316600b5f8b81526020019081526020015f205f9054906101000a90046001600160a01b03166001600160a01b03161461235a5761235a8986868686612a2f565b6127d5826133a0565b610a518282614773565b5f6127e9886147d6565b90506127f5818661480b565b60055460405163309e565760e11b81526001600160a01b0383811660048301525f92169063613cacae9060240161016060405180830381865afa15801561283e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128629190615854565b90506128758982608001518a8a5f612a2f565b61235a898787878761170d565b61288b836133a0565b61289683838361483d565b505050565b6005546001600160a01b03166128b1818a6148c4565b6128b9614fd8565b6128c6818a8a8a8a6140b8565b6128d2828b8386613719565b6040516338116fa360e01b8152600481018b90526001600160a01b038316906338116fa3906024015f604051808303815f87803b158015612911575f80fd5b505af1158015612923573d5f803e3d5ffd5b5050505f8b8152600b60205260408120546001600160a01b0316915081156129b95760405163309e565760e11b81526001600160a01b0383811660048301525f919086169063613cacae9060240161016060405180830381865afa15801561298d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906129b19190615854565b608001519150505b604051635ef3b8bf60e01b8152600481018d9052611414908d906001600160a01b03871690635ef3b8bf90602401602060405180830381865afa158015612a02573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612a2691906158f4565b898986866145f3565b612a37612fc9565b612a3f6150e8565b6005546001600160a01b039081168083526009549091166020830152612a659087613169565b612a6e866133a0565b612a7785612ff4565b612a80866147d6565b6001600160a01b039081166040838101919091525f888152600b60209081529082902080546001600160a01b0319169055830151905163f476125960e01b81526004810189905291169063f4761259906024015f604051808303815f87803b158015612aea575f80fd5b505af1158015612afc573d5f803e3d5ffd5b505050602082015160405163843aa0db60e01b8152600481018990526024810188905260448101879052606481018690526001600160a01b03909116915063843aa0db906084015f604051808303815f87803b158015612b5a575f80fd5b505af1158015612b6c573d5f803e3d5ffd5b50508251604051632ab4fd0160e21b8152600481018a90526001600160a01b03909116925063aad3f404915060240161014060405180830381865afa158015612bb7573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bdb919061569c565b60608201528051604080830151905163309e565760e11b81526001600160a01b03918216600482015291169063613cacae9060240161016060405180830381865afa158015612c2c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612c509190615854565b60808201526060810151604081015190515f91612c6c91615926565b608083015151612c7c9190615926565b9050612c86614fd8565b60608084018051604001518352805190910151602083015260808401805160e090810151610120850152905160a00151908301525151612cc7908890615735565b6080808501510151612cd99084615735565b612ce3919061574c565b60c082015260808084015101518714801590612d1557506203f48083606001516101200151612d12919061574c565b42105b15612d3957606083015160208101519051612d32919083876132b8565b6060840151525b606083015151612d4a908890615735565b6080808501510151612d5c9084615735565b612d66919061574c565b60c0808301919091526080840180516101000151610160840152510151612d8d9083615735565b6101408201525f5460408085015190516371d4eb2160e01b81526001600160a01b03909216916371d4eb2191612dc8918591906004016157dd565b5f604051808303815f87803b158015612ddf575f80fd5b505af1158015612df1573d5f803e3d5ffd5b50505050825f01516001600160a01b031663bf49e6498985606001516020015186606001515f01518588604001518960800151602001518a608001515f01518f6040518963ffffffff1660e01b8152600401612e54989796959493929190615af0565b5f604051808303815f87803b158015612e6b575f80fd5b505af1158015611414573d5f803e3d5ffd5b600954600160a01b900460ff1615612ea857604051631de951a160e31b815260040160405180910390fd5b5f612eb1611603565b90505f612ebc6114a7565b60025460408051630fdb11cf60e01b815281519394505f9384936001600160a01b031692630fdb11cf9260048082019391829003018187875af1158015612f05573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612f299190615939565b915091508015612f395750505050565b5f612f458585856148eb565b90507f0000000000000000000000000000000000000000000000000f43fc2c04ee00008110612f87576040516372f2224f60e01b815260040160405180910390fd5b612f8f61400c565b6040518181527f3ea78f7c2d896613dfa93eea56016064d98758df2a799e6eb38ce050c9f9c10e9060200160405180910390a15050505050565b600954600160a01b900460ff16156115c057604051631de951a160e31b815260040160405180910390fd5b60026130096064670de0b6b3a7640000615b46565b6130139190615b46565b81101561303357604051630d2693ab60e41b815260040160405180910390fd5b670de0b6b3a76400008111156116d257604051631030bfe960e21b815260040160405180910390fd5b5f818152600b60205260409020546001600160a01b0316156116d257604051634742bbb360e01b815260040160405180910390fd5b6040516331a9108f60e11b8152600481018290525f907f000000000000000000000000c56e6030516a32bbec08496d44abb569e0497f9c6001600160a01b031690636352211e90602401602060405180830381865afa1580156130f6573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061311a9190615839565b9050336001600160a01b0382161480159061314b57505f828152600a60205260409020546001600160a01b03163314155b15610a51576040516334044c8d60e01b815260040160405180910390fd5b60405163e47bfaf160e01b8152600481018290525f906001600160a01b0384169063e47bfaf190602401602060405180830381865afa1580156131ae573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906131d29190615b65565b905060018160048111156131e8576131e8615b83565b146128965760405163f1669c3d60e01b815260040160405180910390fd5b5f838152600a6020908152604091829020825160808101845281546001600160a01b031680825260018301546001600160801b0380821695840195909552600160801b900490931693810193909352600201546060830152339003610e775761328a8282602001516001600160801b031683604001516001600160801b0316614748565b610e7783826060015161491c565b808203610a51576040516322803e4960e21b815260040160405180910390fd5b5f806132c2613571565b5f80546040516385fe37a360e01b815292935090916001600160a01b03909116906385fe37a3906132f79088906004016158e5565b602060405180830381865afa158015613312573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061333691906158f4565b90506133428682613611565b61010086018190526133549085613631565b610100850151613364908761574c565b95505f6133728888856148eb565b905061337d81614946565b5f6133888785613652565b9050613393816136d8565b5095979650505050505050565b6040516331a9108f60e11b8152600481018290527f000000000000000000000000c56e6030516a32bbec08496d44abb569e0497f9c6001600160a01b031690636352211e90602401602060405180830381865afa158015613403573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906134279190615839565b6001600160a01b0316336001600160a01b0316146116d257604051631963d1e760e31b815260040160405180910390fd5b6001600160a01b0381165f908152600c6020526040812054600160801b90046001600160801b031690036116d25760405163de5a928160e01b815260040160405180910390fd5b6001600160a01b0382165f908152600c6020908152604091829020825160608101845281546001600160801b03808216808452600160801b909204169382018490526001909201549381019390935261289691849190614748565b6001600160a01b0382165f908152600c6020908152604091829020825160608101845281546001600160801b038082168352600160801b90910416928101929092526001015491810182905290613551908361574c565b4210156128965760405163dce1ae8b60e01b815260040160405180910390fd5b5f805f60025f9054906101000a90046001600160a01b03166001600160a01b0316630fdb11cf6040518163ffffffff1660e01b815260040160408051808303815f875af11580156135c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906135e89190615939565b91509150801561360b576040516311b2b23360e11b815260040160405180910390fd5b50919050565b5f61362861361f8385615735565b62093a80614987565b90505b92915050565b80821115610a5157604051632337edc760e01b815260040160405180910390fd5b5f8061365c611603565b905083604001518161366e919061574c565b90508360600151816136809190615926565b90505f61368b6114a7565b905084608001518161369d919061574c565b9050846101000151816136b0919061574c565b90508460a00151816136c29190615926565b90506136cf8282866148eb565b95945050505050565b7f00000000000000000000000000000000000000000000000014d1120d7b1600008110156116d25760405163c855c3b360e01b815260040160405180910390fd5b613721612fc9565b613729615129565b5f546001600160a01b039081168252600854166020820152613749613571565b6060820181905261377a907f00000000000000000000000000000000000000000000000014d1120d7b1600006149b4565b1515608082015261378b8585613e53565b6040516331a9108f60e11b8152600481018590525f907f000000000000000000000000c56e6030516a32bbec08496d44abb569e0497f9c6001600160a01b031690636352211e90602401602060405180830381865afa1580156137f0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138149190615839565b6060850151909150819015158061382e57505f8560800151115b156138405761383d8683613dd6565b90505b5f8560400151118061385557505f8560a00151115b156138645761386486836149c9565b604051632ab4fd0160e21b8152600481018790526001600160a01b0388169063aad3f4049060240161014060405180830381865afa1580156138a8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138cc919061569c565b604084015260a08501511561393e575f686c6b935b8bbd40000084604001515f0151116138f9575f613913565b60408401515161391390686c6b935b8bbd40000090615926565b9050808660a0015111156139295760a086018190525b61393c8460200151338860a00151613f10565b505b61394785614a2f565b606085015115613967576139678360400151602001518660600151614a7d565b84606001518560400151846040015160200151613984919061574c565b61398e9190615926565b60e084015260a085015160808601516040850151516139ad919061574c565b6139b79190615926565b60c08401525f868152600b60205260409020546001600160a01b03168015156139de61502d565b5f8215613af05760405163309e565760e11b81526001600160a01b0385811660048301528c169063613cacae9060240161016060405180830381865afa158015613a2a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a4e9190615854565b91508860a001518960800151886040015160400151845f0151613a71919061574c565b613a7b919061574c565b613a859190615926565b60408089018051909101518b52516060015160208b015260e0808401516101208c015260a0840151908b01526080830151909150613ac39082615735565b60c0808b01919091526101008301516101608b0152820151613ae59082615735565b6101408a0152613b2f565b60408088018051909101518a5280516060015160208b0152805160e090810151908b01525160c09081015190880151613b299190615735565b60c08a01525b608089015115613c4c5786516040516385fe37a360e01b81525f916001600160a01b0316906385fe37a390613b68908d906004016158e5565b602060405180830381865afa158015613b83573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ba791906158f4565b9050613bb78a6080015182613611565b6101008b01819052613bc9908a613631565b8961010001518860c001818151613be0919061574c565b9052508315613c2c576101008a0151613bf9908361574c565b9150826080015182613c0b9190615735565b60c0808c0191909152830151613c219083615735565b6101408b0152613c4a565b876040015160c001518860c00151613c449190615735565b60c08b01525b505b613c598760c00151614a9e565b613c708760e001518860c0015189606001516148eb565b60a0880152613c7f8988614ac8565b8215613cfe578a6001600160a01b0316631cf740758b8960e001518a60c001518d898860200151895f01516040518863ffffffff1660e01b8152600401613ccc9796959493929190615b97565b5f604051808303815f87803b158015613ce3575f80fd5b505af1158015613cf5573d5f803e3d5ffd5b50505050613d65565b60e087015160c08801516040516203af7d60eb1b81526001600160a01b038e1692631d7be80092613d37928f9291908f90600401615be4565b5f604051808303815f87803b158015613d4e575f80fd5b505af1158015613d60573d5f803e3d5ffd5b505050505b86516040516371d4eb2160e01b81526001600160a01b03909116906371d4eb2190613d96908c9088906004016157dd565b5f604051808303815f87803b158015613dad575f80fd5b505af1158015613dbf573d5f803e3d5ffd5b50505050611b88858a89602001518a5f0151614b15565b5f82815260046020526040812080546001909101546001600160a01b03918216919081169084163314801590613e155750336001600160a01b03831614155b15613e33576040516310bb5c9d60e31b815260040160405180910390fd5b6001600160a01b038116613e4b57839250505061362b565b949350505050565b60405163e47bfaf160e01b8152600481018290525f906001600160a01b0384169063e47bfaf190602401602060405180830381865afa158015613e98573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ebc9190615b65565b90506001816004811115613ed257613ed2615b83565b14158015613ef257506004816004811115613eef57613eef615b83565b14155b156128965760405163019dc6e560e11b815260040160405180910390fd5b6040516370a0823160e01b81526001600160a01b0383811660048301528291908516906370a0823190602401602060405180830381865afa158015613f57573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613f7b91906158f4565b1015612896576040516307a5137f60e11b815260040160405180910390fd5b5f818152600a6020908152604080832080546001600160a01b03199081168255600182018590556002909101849055600b909252909120805490911690556116d281614c57565b6002546001600160a01b031633146115c0576040516311a780f560e31b815260040160405180910390fd5b5f805460408051631bfa0d7b60e01b815290516001600160a01b0390921692631bfa0d7b9260048084019382900301818387803b15801561404b575f80fd5b505af115801561405d573d5f803e3d5ffd5b50506009805460ff60a01b1916600160a01b17905550506005546040805163fc0e74d160e01b815290516001600160a01b039092169163fc0e74d1916004808201925f9290919082900301818387803b158015611495575f80fd5b82156140ca57604085018490526140d2565b606085018490525b80156140e45760808501829052611706565b60a085018290525050505050565b6005546001600160a01b031633146115c057604051631c55689560e31b815260040160405180910390fd5b5f614126612fc9565b61418f6040518061014001604052805f6001600160a01b031681526020015f6001600160a01b031681526020015f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f151581525090565b6005546001600160a01b0390811682525f54811660208301526008541660408201526141b9613571565b8160800181815250508e8e6040516020016141e99291906001600160a01b03929092168252602082015260400190565b60408051601f19818403018152919052805160209091012060608201819052815161421391614cfd565b604083018d9052608083018c90528a61422c8d8b61574c565b6142369190615735565b60c084015260208101516040516385fe37a360e01b81526001600160a01b03909116906385fe37a39061426d9086906004016158e5565b602060405180830381865afa158015614288573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906142ac91906158f4565b60a0820181905260808401516142c191613611565b61010084018190526142d39088613631565b82610100015183608001516142e8919061574c565b60c082018190526142f890614a9e565b6001600160a01b038a16614320578a8160c001516143169190615735565b60c0840152614364565b8a8160c001518a614331919061574c565b61433b9190615735565b60c0808501919091528101518890614353908b61574c565b61435d9190615735565b6101408401525b6143778d8260c0015183608001516148eb565b60e0820181905261438790614946565b614395838260800151613652565b61010082018190526143a6906136d8565b6143b4816060015187614773565b6143c38160600151868661483d565b80602001516001600160a01b03166371d4eb21848c6040518363ffffffff1660e01b81526004016143f59291906157dd565b5f604051808303815f87803b15801561440c575f80fd5b505af115801561441e573d5f803e3d5ffd5b5050505061443081602001518e614d99565b60408082015190516340c10f1960e01b8152336004820152602481018e90526001600160a01b03909116906340c10f19906044015f604051808303815f87803b15801561447b575f80fd5b505af115801561448d573d5f803e3d5ffd5b50506006546040516323b872dd60e01b81523360048201526001600160a01b03918216602482015266853a0d2313c00060448201527f0000000000000000000000004223f8af31e07815f1a7437336f093f37c065efe90911692506323b872dd91506064016020604051808303815f875af115801561450e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614532919061590b565b50606001519e9d5050505050505050505050505050565b805f036116d2576040516302dedfbf60e31b815260040160405180910390fd5b60405163e47bfaf160e01b8152600481018290525f9081906001600160a01b0385169063e47bfaf190602401602060405180830381865afa1580156145b0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906145d49190615b65565b905060048160048111156145ea576145ea615b83565b14949350505050565b6001600160a01b0382166146745760095460405163843aa0db60e01b8152600481018890526024810187905260448101869052606481018590526001600160a01b039091169063843aa0db906084015f604051808303815f87803b158015614659575f80fd5b505af115801561466b573d5f803e3d5ffd5b505050506146da565b600954604051631b55263560e11b81526001600160a01b03909116906336aa4c6a906146ac908990869086908a908a906004016159fb565b5f604051808303815f87803b1580156146c3575f80fd5b505af11580156146d5573d5f803e3d5ffd5b505050505b505050505050565b6001600160a01b0381165f908152600c6020526040902054600160801b90046001600160801b0316156116d257604051632a16d50160e01b815260040160405180910390fd5b808210610a5157604051632a2b2ad160e01b815260040160405180910390fd5b8282118061475557508083115b1561289657604051639736ee7560e01b815260040160405180910390fd5b5f8281526003602090815260409182902080546001600160a01b0319166001600160a01b038516908117909155915191825283917f3942babd464ceb1c7d319f75245a8cd41334592b45507f072e7020e63c22a8dc910160405180910390a25050565b5f818152600b60205260408120546001600160a01b03168061362b576040516393f3f3c160e01b815260040160405180910390fd5b806001600160a01b0316826001600160a01b031603610a5157604051631c56f50360e01b815260040160405180910390fd5b6148478282614e1f565b5f8381526004602090815260409182902080546001600160a01b03199081166001600160a01b0387811691821784556001909301805490921692861692831790915583519081529182015284917f649442545e0f313a6d8087b19bc47bd2bd9b63f79d23a773446e00d2ea01d169910160405180910390a2505050565b6148ce8282614569565b610a515760405163067c71a160e41b815260040160405180910390fd5b5f8215614911575f836148fe8487615735565b6149089190615b46565b91506149159050565b505f195b9392505050565b614926818361574c565b421015610a5157604051638510088360e01b815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000000f43fc2c04ee00008110156116d2576040516309a8aadb60e31b815260040160405180910390fd5b5f670de0b6b3a76400006301e133806149a08486615735565b6149aa9190615b46565b6136289190615b46565b5f806149bf84614e5c565b9092119392505050565b5f828152600360205260409020546001600160a01b0390811690821633148015906149fc57506001600160a01b03811615155b8015614a115750336001600160a01b03821614155b1561289657604051636522e96960e01b815260040160405180910390fd5b6040810151158015614a4357506060810151155b8015614a5157506080810151155b8015614a5f575060a0810151155b156116d2576040516356515c5360e01b815260040160405180910390fd5b81811115610a515760405163b30a1bc960e01b815260040160405180910390fd5b686c6b935b8bbd4000008110156116d25760405163f1e4191360e01b815260040160405180910390fd5b614ad58160a00151614946565b5f614ae4838360600151613652565b9050816080015115614b0c57614afe836080015182614e7e565b612896838360600151614eca565b612896816136d8565b608083015115614b885760808301516040516340c10f1960e01b81526001600160a01b0386811660048301526024820192909252908316906340c10f19906044015f604051808303815f87803b158015614b6d575f80fd5b505af1158015614b7f573d5f803e3d5ffd5b50505050614bf4565b60a083015115614bf45760a0830151604051632770a7eb60e21b815233600482015260248101919091526001600160a01b03831690639dc29fac906044015f604051808303815f87803b158015614bdd575f80fd5b505af1158015614bef573d5f803e3d5ffd5b505050505b604083015115614c1157614c0c818460400151614d99565b610e77565b606083015115610e77576060830151604051634fa7288f60e11b81526001600160a01b038681166004830152602482019290925290821690639f4e511e90604401611e64565b5f81815260036020908152604080832080546001600160a01b031990811690915560048352818420805482168155600101805490911690555191825282917f3942babd464ceb1c7d319f75245a8cd41334592b45507f072e7020e63c22a8dc910160405180910390a2604080515f808252602082015282917f649442545e0f313a6d8087b19bc47bd2bd9b63f79d23a773446e00d2ea01d169910160405180910390a250565b60405163e47bfaf160e01b8152600481018290525f906001600160a01b0384169063e47bfaf190602401602060405180830381865afa158015614d42573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190614d669190615b65565b90505f816004811115614d7b57614d7b615b83565b14612896576040516376ac6c0d60e11b815260040160405180910390fd5b614dce6001600160a01b037f0000000000000000000000004223f8af31e07815f1a7437336f093f37c065efe16338484614f11565b604051632bcbcbcb60e01b8152600481018290526001600160a01b03831690632bcbcbcb906024015f604051808303815f87803b158015614e0d575f80fd5b505af11580156146da573d5f803e3d5ffd5b6001600160a01b038216158015614e3e57506001600160a01b03811615155b15610a5157604051632235921760e01b815260040160405180910390fd5b5f80614e66611603565b90505f614e716114a7565b9050613e4b8282866148eb565b5f82118015614eac57507f00000000000000000000000000000000000000000000000014d1120d7b16000081105b15610a515760405163c855c3b360e01b815260040160405180910390fd5b808260600151614eda9190615735565b670de0b6b3a76400008360a00151614ef29190615735565b1015610a515760405163d676956360e01b815260040160405180910390fd5b604080516001600160a01b038581166024830152841660448201526064808201849052825180830390910181526084909101909152602080820180516001600160e01b03166323b872dd60e01b1781528251610e7793889390925f9283929183919082885af180614f87576040513d5f823e3d81fd5b50505f513d91508115614f9e578060011415614fab565b6001600160a01b0384163b155b15610e7757604051635274afe760e01b81526001600160a01b038516600482015260240160405180910390fd5b6040518061018001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040518061016001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6040805160e0810182525f808252602082018190529181018290526060810191909152608081016150ab615176565b81526020016150b861502d565b81526020016150c561502d565b905290565b604080516080810182525f80825260208201529081016150b8614fd8565b6040805160c0810182525f808252602082018190529181019190915260608101615110615176565b815260200161511d61502d565b81526020015f81525090565b60408051610120810182525f8082526020820152908101615148615176565b81526020015f81526020015f151581526020015f81526020015f81526020015f81526020015f151581525090565b6040518061014001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5f602082840312156151cf575f80fd5b5035919050565b5f805f805f60a086880312156151ea575f80fd5b505083359560208501359550604085013594606081013594506080013592509050565b6001600160a01b03811681146116d2575f80fd5b5f8060408385031215615232575f80fd5b8235915060208301356152448161520d565b809150509250929050565b5f6020828403121561525f575f80fd5b81356149158161520d565b80356001600160801b0381168114615280575f80fd5b919050565b5f805f8060808587031215615298575f80fd5b6152a18561526a565b966020860135965060408601359560600135945092505050565b5f80604083850312156152cc575f80fd5b50508035926020909101359150565b80151581146116d2575f80fd5b5f805f805f8060c087890312156152fd575f80fd5b86359550602087013594506040870135615316816152db565b935060608701359250608087013561532d816152db565b8092505060a087013590509295509295509295565b5f805f60608486031215615354575f80fd5b505081359360208301359350604090920135919050565b5f805f805f60a0868803121561537f575f80fd5b8535945060208601356153918161520d565b94979496505050506040830135926060810135926080909101359150565b5f805f805f805f805f805f6101608c8e0312156153ca575f80fd5b8b356153d58161520d565b9a5060208c0135995060408c0135985060608c0135975060808c0135965060a08c0135955060c08c0135945060e08c013593506101008c01356154178161520d565b92506101208c01356154288161520d565b91506101408c01356154398161520d565b809150509295989b509295989b9093969950565b5f805f805f60a08688031215615461575f80fd5b61546a8661526a565b94506154786020870161526a565b93506154866040870161526a565b92506154946060870161526a565b91506154a26080870161526a565b90509295509295909350565b5f610160828403121561360b575f80fd5b5f805f805f805f805f6101208a8c0312156154d8575f80fd5b8935985060208a01356154ea8161520d565b97506154f860408b0161526a565b965061550660608b0161526a565b989b979a50959860808101359760a0820135975060c0820135965060e08201359550610100909101359350915050565b5f805f805f805f60e0888a03121561554c575f80fd5b873596506020880135955060408801359450606088013561556c8161520d565b9699959850939660808101359560a0820135955060c0909101359350915050565b5f805f6060848603121561559f575f80fd5b8335925060208401356155b18161520d565b915060408401356155c18161520d565b809150509250925092565b5f805f805f805f80610100898b0312156155e4575f80fd5b883597506020890135965060408901356155fd816152db565b9550606089013594506080890135615614816152db565b979a969950949793969560a0850135955060c08501359460e001359350915050565b604051610140810167ffffffffffffffff8111828210171561566657634e487b7160e01b5f52604160045260245ffd5b60405290565b604051610160810167ffffffffffffffff8111828210171561566657634e487b7160e01b5f52604160045260245ffd5b5f61014082840312156156ad575f80fd5b6156b5615636565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e08201526101008084015181830152506101208084015181830152508091505092915050565b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761362b5761362b615721565b8082018082111561362b5761362b615721565b805182526020810151602083015260408101516040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e08301526101008082015181840152506101208082015181840152506101408082015181840152506101608082015181840152505050565b6101a081016157ec828561575f565b6001600160a01b03929092166101809190910152919050565b5f6102008201905086825285602083015284604083015283606083015261582f608083018461575f565b9695505050505050565b5f60208284031215615849575f80fd5b81516149158161520d565b5f6101608284031215615865575f80fd5b61586d61566c565b825181526020830151602082015260408301516040820152606083015160608201526080830151608082015260a083015160a082015260c083015160c082015260e083015160e08201526101008084015181830152506101208084015181830152506101408084015181830152508091505092915050565b610180810161362b828461575f565b5f60208284031215615904575f80fd5b5051919050565b5f6020828403121561591b575f80fd5b8151614915816152db565b8181038181111561362b5761362b615721565b5f806040838503121561594a575f80fd5b825191506020830151615244816152db565b8581526102008101615971602083018761575f565b6001600160a01b03949094166101a08201526101c08101929092526101e09091015292915050565b5f6102408201905082518252602083015160208301526040830151604083015260608301516159cb606084018261575f565b5060808301516001600160a01b03166101e083015260a083015161020083015260c0909201516102209091015290565b9485526001600160a01b0393909316602085015260408401919091526060830152608082015260a00190565b6001600160a01b0385168152602081018490526101e08101615a4c604083018561575f565b826101c083015295945050505050565b87815260208101879052604081018690526001600160a01b03851660608201526080810184905260a081018390526102408101615a9c60c083018461575f565b98975050505050505050565b6001600160a01b03878116825260208201879052610220820190615acf604084018861575f565b949094166101c08201526101e0810192909252610200909101529392505050565b88815260208101889052604081018790526102608101615b13606083018861575f565b6001600160a01b03959095166101e082015261020081019390935261022083019190915261024090910152949350505050565b5f82615b6057634e487b7160e01b5f52601260045260245ffd5b500490565b5f60208284031215615b75575f80fd5b815160058110614915575f80fd5b634e487b7160e01b5f52602160045260245ffd5b87815260208101879052604081018690526102408101615bba606083018761575f565b6001600160a01b03949094166101e082015261020081019290925261022090910152949350505050565b84815260208101849052604081018390526101e081016136cf606083018461575f56fea2646970667358221220c2a20eba6d2651cc5f2e529e7dfb443fd78179e6ec775cc8e04d1a8525c79cb764736f6c63430008180033

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

000000000000000000000000ba0f2b2cae0f71997c758ea4e266f6f0fff7d8a7

-----Decoded View---------------
Arg [0] : _addressesRegistry (address): 0xbA0F2B2caE0F71997c758Ea4e266f6F0fff7D8a7

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000ba0f2b2cae0f71997c758ea4e266f6f0fff7d8a7


Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

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

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