ETH Price: $3,304.65 (-1.50%)
Gas: 0.04 Gwei
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Grant Role237563012025-11-08 18:22:1168 days ago1762626131IN
0x562A80ae...19d3bC27d
0 ETH0.000148732.00020934
Liquidate222153712025-04-07 6:54:59283 days ago1744008899IN
0x562A80ae...19d3bC27d
0 ETH0.16949578280.2
Liquidate220075342025-03-09 6:30:47312 days ago1741501847IN
0x562A80ae...19d3bC27d
0 ETH0.0281350440.1
Liquidate219326532025-02-26 19:39:35323 days ago1740598775IN
0x562A80ae...19d3bC27d
0 ETH0.000111074.54200265
Liquidate219234752025-02-25 12:55:11324 days ago1740488111IN
0x562A80ae...19d3bC27d
0 ETH0.00008163.3371482
Liquidate219234732025-02-25 12:54:47324 days ago1740488087IN
0x562A80ae...19d3bC27d
0 ETH0.000034161.39705057
Liquidate219197612025-02-25 0:28:23324 days ago1740443303IN
0x562A80ae...19d3bC27d
0 ETH0.000169876.94649908
Liquidate219134992025-02-24 3:27:35325 days ago1740367655IN
0x562A80ae...19d3bC27d
0 ETH0.000096843.96205573
Liquidate218525472025-02-15 14:53:59334 days ago1739631239IN
0x562A80ae...19d3bC27d
0 ETH0.000053772.2
Liquidate218525472025-02-15 14:53:59334 days ago1739631239IN
0x562A80ae...19d3bC27d
0 ETH0.001556052.2
Liquidate218525352025-02-15 14:51:23334 days ago1739631083IN
0x562A80ae...19d3bC27d
0 ETH0.000048912
Liquidate Positi...218449362025-02-14 13:15:59335 days ago1739538959IN
0x562A80ae...19d3bC27d
0 ETH0.000318640.89323388
Liquidate218418792025-02-14 2:59:35335 days ago1739501975IN
0x562A80ae...19d3bC27d
0 ETH0.000092311.297205

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Method Block
From
To
0x60806040218037832025-02-08 19:08:35341 days ago1739041715
0x562A80ae...19d3bC27d
 Contract Creation0 ETH
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

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

Contract Name:
PositionManager

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 1 runs

Other Settings:
paris EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 34 : PositionManager.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../../../interfaces/IPositionManager.sol";
import "../../../interfaces/ISortedPositions.sol";
import "../../../interfaces/ICollateralSurplusPool.sol";
import "../../../interfaces/IPriceFeed.sol";
import "../../../common/StableMath.sol";
import "../../../interfaces/ICollateralController.sol";
import "./PositionState.sol";
import "./LiquidationManager.sol";
import "../../BaseRateAbstract.sol";
import "../../PermissionedRedeemerAbstract.sol";

/**
 * @title PositionManager
 * @dev This contract manages positions in the system, handling operations like redemptions, liquidations, and fee calculations.
 *
 * Key features:
 *  1. Position Management: Handles creation, modification, and closure of positions.
 *  2. Redemption Mechanism: Allows users to redeem collateral for stable tokens.
 *  3. Liquidation: Integrates with LiquidationManager for position liquidations.
 *  4. Fee Calculation: Computes borrowing and redemption fees based on system state.
 *  5. Reward Distribution: Manages the distribution of rewards to position holders.
 *  6. Optional redeemer whitelist to facilitate external services, or designated redeemers
 */
contract PositionManager is PositionState, IPositionManager, BaseRateAbstract, PermissionedRedeemerAbstract {
    IFeeTokenStaking public feeTokenStaking;
    using Address for address;
    address public liquidationManagerAddress;

    /**
     * @dev Struct to hold information about escrowed redemptions
     */
    struct EscrowedRedemption {
        uint stableAmount;
        uint timestamp;
        uint utilizationPCT;
        uint loadIncrease;
    }

    mapping(address => EscrowedRedemption) public escrowedRedemptions;

    /**
     * @dev Struct to hold totals for redemption operations
     */
    struct RedemptionTotals {
        uint remainingStables;
        uint totalStablesToRedeem;
        uint totalCollateralDrawn;
        uint CollateralFee;
        uint CollateralToSendToRedeemer;
        uint decayedBaseRate;
        uint price;
        uint totalStableSupplyAtStart;
        uint utilizationPCT;
        uint loadIncrease;
        uint maxFeePCT;
        uint suggestedAdditiveFeePCT;
        EscrowedRedemption redemption;
        uint _stableAmount;
        bool timedOut; // either didn't complete in time, or escrow requirement removed while in escrow
        uint cooldownRequirement;
        uint gracePeriod;
        uint8 version;
        uint redemptionsTimeoutFeePct;
        bool firstInLine;
    }

    /**
     * @dev Struct to hold values for a single redemption operation
     */
    struct SingleRedemptionValues {
        uint stableLot;
        uint CollateralLot;
        bool cancelledPartial;
    }

    /**
     * @dev Constructor to initialize the PositionManager contract
     * @param _collateralAsset Address of the collateral asset
     * @param _positionControllerAddress Address of the PositionController contract
     * @param _activePoolAddress Address of the ActivePool contract
     * @param _defaultPoolAddress Address of the DefaultPool contract
     * @param _backstopPoolAddress Address of the BackstopPool contract
     * @param _gasPoolAddress Address of the GasPool contract
     * @param _collSurplusPoolAddress Address of the CollateralSurplusPool contract
     * @param _priceFeedAddress Address of the PriceFeed contract
     * @param _stableTokenAddress Address of the StableToken contract
     * @param _sortedPositionsAddress Address of the SortedPositions contract
     * @param _feeTokenStakingAddress Address of the FeeTokenStaking contract
     * @param _collateralController Address of the CollateralController contract
     */
    constructor(
        address _collateralAsset,
        address _positionControllerAddress,
        address _activePoolAddress,
        address _defaultPoolAddress,
        address _backstopPoolAddress,
        address _gasPoolAddress,
        address _collSurplusPoolAddress,
        address _priceFeedAddress,
        address _stableTokenAddress,
        address _sortedPositionsAddress,
        address _feeTokenStakingAddress,
        address _collateralController
    ) {
        collateralController = ICollateralController(_collateralController);
        positionControllerAddress = _positionControllerAddress;
        collateralToken = IERC20Metadata(_collateralAsset);
        activePool = IActivePool(_activePoolAddress);
        defaultPool = IDefaultPool(_defaultPoolAddress);
        backstopPool = IBackstopPool(_backstopPoolAddress);
        gasPoolAddress = _gasPoolAddress;
        collateralSurplusPool = ICollateralSurplusPool(_collSurplusPoolAddress);
        priceFeed = IPriceFeed(_priceFeedAddress);
        stableToken = IStable(_stableTokenAddress);
        sortedPositions = ISortedPositions(_sortedPositionsAddress);
        feeTokenStaking = IFeeTokenStaking(_feeTokenStakingAddress);
        liquidationManagerAddress = address(new LiquidationManager());
    }

    /**
     * @dev Returns the count of position owners
     * @return The number of position owners
     */
    function getPositionOwnersCount() external view override returns (uint) {
        return PositionOwners.length;
    }

    /**
     * @dev Returns the Minimum Collateralization Ratio (MCR)
     * @return _MCR The Minimum Collateralization Ratio
     */
    function MCR() external view returns (uint _MCR) {
        _MCR = collateralController.getMCR(address(collateralToken), collateralController.getVersion(address(this)));
    }

    /**
     * @dev Returns the Critical Collateralization Ratio (CCR)
     * @return _CCR The Critical Collateralization Ratio
     */
    function CCR() external view returns (uint _CCR) {
        _CCR = collateralController.getCCR(address(collateralToken), collateralController.getVersion(address(this)));
    }

    /**
     * @dev Returns the address of a position owner at a given index
     * @param _index The index of the position owner
     * @return The address of the position owner
     */
    function getPositionFromPositionOwnersArray(uint _index) external view override returns (address) {
        return PositionOwners[_index];
    }

    /**
     * @dev Liquidates a single position
     * @param _borrower The address of the position to liquidate
     */
    function liquidate(address _borrower) external override {
        _requirePositionIsActive(_borrower);

        address[] memory borrowers = new address[](1);
        borrowers[0] = _borrower;
        batchLiquidatePositions(borrowers);
    }

    /**
     * @dev Liquidates multiple positions
     * @param _n The maximum number of positions to liquidate
     */
    function liquidatePositions(uint _n) external override {
        liquidationManagerAddress.functionDelegateCall(
            abi.encodeWithSignature("liquidatePositions(uint256)", _n),
            "liquidatePositions: delegate call failed"
        );
    }

    /**
     * @dev Batch liquidates a list of positions
     * @param _positionArray An array of addresses representing positions to liquidate
     */
    function batchLiquidatePositions(address[] memory _positionArray) public override {
        require(_positionArray.length != 0, "Calldata address array must not be empty");
        liquidationManagerAddress.functionDelegateCall(
            abi.encodeWithSignature("batchLiquidatePositions(address[])", _positionArray),
            "batchLiquidatePositions: delegate call failed"
        );
    }

    /**
     * @dev Redeems collateral from a position
     * @param collateral Cache of contract addresses
     * @param _borrower The address of the position to redeem from
     * @param _maxStableAmount The maximum amount of stable tokens to redeem
     * @param _price The current price of the collateral
     * @param _upperPartialRedemptionHint The upper bound for partial redemption
     * @param _lowerPartialRedemptionHint The lower bound for partial redemption
     * @param _partialRedemptionHintNICR The NICR hint for partial redemption
     * @return singleRedemption The redemption values
     */
    function _redeemCollateralFromPosition(
        ContractsCache memory collateral,
        address _borrower,
        uint _maxStableAmount,
        uint _price,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint _partialRedemptionHintNICR,
        bool firstInLine
    )
    internal returns (SingleRedemptionValues memory singleRedemption)
    {
        singleRedemption.stableLot = StableMath._min(_maxStableAmount, Positions[_borrower].debt - GAS_COMPENSATION);
        singleRedemption.CollateralLot = (singleRedemption.stableLot * DECIMAL_PRECISION) / _price;

        uint newDebt = (Positions[_borrower].debt) - singleRedemption.stableLot;
        uint newColl = (Positions[_borrower].coll) - singleRedemption.CollateralLot;

        if (newDebt == GAS_COMPENSATION) {
            _closePositionWithRedemption(collateral, _borrower, GAS_COMPENSATION, newColl);
        } else {
            singleRedemption = _partialRedemption(
                singleRedemption,
                collateral,
                _borrower,
                _upperPartialRedemptionHint,
                _lowerPartialRedemptionHint,
                _partialRedemptionHintNICR,
                newDebt,
                newColl,
                GAS_COMPENSATION,
                firstInLine
            );
        }

        return singleRedemption;
    }

    /**
     * @dev Closes a position during redemption
     * @param collateral Cache of contract addresses
     * @param _borrower The address of the position to close
     * @param GAS_COMPENSATION The gas compensation amount
     * @param newColl The new collateral amount
     */
    function _closePositionWithRedemption(
        ContractsCache memory collateral,
        address _borrower,
        uint GAS_COMPENSATION,
        uint newColl
    ) internal {
        _removeStake(_borrower);
        _closePosition(_borrower, Status.closedByRedemption);
        _redeemClosePosition(collateral, _borrower, GAS_COMPENSATION, newColl);
        emit PositionUpdated(_borrower, 0, 0, 0, uint8(PositionManagerOperation.redeemCollateral));
    }

    /**
     * @dev Performs a partial redemption of a position
     * @param singleRedemption The current redemption values
     * @param collateral Cache of contract addresses
     * @param _borrower The address of the position
     * @param _upperPartialRedemptionHint The upper bound for partial redemption
     * @param _lowerPartialRedemptionHint The lower bound for partial redemption
     * @param _partialRedemptionHintNICR The NICR hint for partial redemption
     * @param newDebt The new debt amount after redemption
     * @param newColl The new collateral amount after redemption
     * @param GAS_COMPENSATION The gas compensation amount
     * @param firstInLine Whether the partial redemption was the first (IE only) redemption target
     * @return The updated redemption values
     */
    function _partialRedemption(
        SingleRedemptionValues memory singleRedemption,
        ContractsCache memory collateral,
        address _borrower,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint _partialRedemptionHintNICR,
        uint newDebt,
        uint newColl,
        uint GAS_COMPENSATION,
        bool firstInLine
    ) internal returns (SingleRedemptionValues memory) {
        uint newNICR = StableMath._computeNominalCR(newColl, newDebt, collateralToken.decimals());

        if (
            ((newDebt - GAS_COMPENSATION) < MIN_NET_DEBT) ||
            ((newNICR != _partialRedemptionHintNICR) && !firstInLine)
        ) {
            singleRedemption.cancelledPartial = true;
            return singleRedemption;
        }

        collateral.sortedPositions.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);

        Positions[_borrower].debt = newDebt;
        Positions[_borrower].coll = newColl;
        _updateStakeAndTotalStakes(_borrower);

        emit PositionUpdated(_borrower, newDebt, newColl, Positions[_borrower].stake, uint8(PositionManagerOperation.redeemCollateral));

        return singleRedemption;
    }

    /**
     * @dev Closes a position and handles the redemption process
     * @param collateral Cache of contract addresses
     * @param _borrower The address of the position to close
     * @param _stables The amount of stables to burn
     * @param _Collateral The amount of collateral to handle
     */
    function _redeemClosePosition(ContractsCache memory collateral, address _borrower, uint _stables, uint _Collateral) internal {
        stableToken.burn(gasPoolAddress, _stables);
        collateral.activePool.decreaseStableDebt(_stables);

        collateral.collateralSurplusPool.accountSurplus(_borrower, _Collateral);
        collateral.activePool.sendCollateral(address(collateral.collateralSurplusPool), _Collateral);
        collateral.collateralSurplusPool.receiveCollateral(address(collateralToken), _Collateral);
    }

    /**
     * @dev Checks if the first redemption hint is valid
     * @param _sortedPositions The SortedPositions contract
     * @param _firstRedemptionHint The first redemption hint
     * @param _price The current price of the collateral
     * @param MCR The Minimum Collateralization Ratio
     * @return A boolean indicating if the hint is valid
     */
    function _isValidFirstRedemptionHint(ISortedPositions _sortedPositions, address _firstRedemptionHint, uint _price, uint MCR) internal view returns (bool) {
        if (_firstRedemptionHint == address(0) ||
            !_sortedPositions.contains(_firstRedemptionHint) ||
            getCurrentICR(_firstRedemptionHint, _price) < MCR
        ) {
            return false;
        }

        address nextPosition = _sortedPositions.getNext(_firstRedemptionHint);
        return nextPosition == address(0) || getCurrentICR(nextPosition, _price) < MCR;
    }

    /**
     * @dev Queues a redemption request
     * @param _stableAmount The amount of stable tokens to redeem
     */
    function queueRedemption(uint _stableAmount) external override {
        require(canRedeem(msg.sender), "Caller does not have redemption privileges");
        require(_stableAmount > 0, "Amount must be greater than zero");

        // lookup asset to ensure post activation/pre sunset state.
        uint8 associatedVersion = collateralController.getVersion(address(this));
        collateralController.getCollateralInstance(address(collateralToken), associatedVersion);

        EscrowedRedemption storage redemption = escrowedRedemptions[msg.sender];
        require(redemption.timestamp == 0, "Redemption already queued");

        (uint cooldownRequirement,,) = collateralController.getRedemptionCooldownRequirement(address(collateralToken), associatedVersion);
        require(cooldownRequirement > 0, "Cooldown requirement must be greater than 0");

        stableToken.transferForRedemptionEscrow(msg.sender, address(this), _stableAmount);
        redemption.stableAmount = _stableAmount;
        redemption.timestamp = block.timestamp;
        (redemption.utilizationPCT, redemption.loadIncrease) =
            collateralController.regenerateAndConsumeRedemptionPoints(_stableAmount);
    }

    /**
    * @dev Allows a user to dequeue their escrowed stables
    * This provides a way to recover stables without fee, in the event that redemptions become impossible
    * through no fault of the enqueueing user due to cases like CR dropping to dangerous levels, or whitelist being enacted.
    */
    function emergencyDequeue() external {
        (uint price,) = priceFeed.fetchHighestPriceWithFeeSuggestion(0, 0, false, false);
        uint MCR = collateralController.getMCR(address(collateralToken), collateralController.getVersion(address(this)));

        require(
            (_getTCR(price) < MCR) || redemptionWhitelistOnAndUserWithoutRole(msg.sender),
            "TCR must be below MCR to emergency dequeue"
        );

        EscrowedRedemption storage redemption = escrowedRedemptions[msg.sender];
        require(redemption.timestamp != 0, "No redemption queued");

        uint stablesToReturn = redemption.stableAmount;
        require(stableToken.transfer(msg.sender, stablesToReturn), "Stable transfer failed");

        delete escrowedRedemptions[msg.sender];
        emit EmergencyDequeueProcessed(msg.sender, stablesToReturn);
    }

    /**
     * @dev Checks if an address has an enqueued redemption
     * @param redeemer The address to check
     * @return A boolean indicating if the address has an enqueued redemption
     */
    function hasEnqueuedEscrow(address redeemer) public view returns (bool) {
        return escrowedRedemptions[redeemer].timestamp != 0;
    }

    /**
     * @dev Redeems collateral for stable tokens
     * @param _stableAmount The amount of stable tokens to redeem
     * @param _firstRedemptionHint The first redemption hint
     * @param _upperPartialRedemptionHint The upper bound for partial redemption
     * @param _lowerPartialRedemptionHint The lower bound for partial redemption
     * @param _partialRedemptionHintNICR The NICR hint for partial redemption
     * @param _maxIterations The maximum number of iterations for the redemption process
     * @param _maxFeePercentage The maximum fee percentage the redeemer is willing to pay
     */
    function redeemCollateral(
        uint _stableAmount,
        address _firstRedemptionHint,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint _partialRedemptionHintNICR,
        uint _maxIterations,
        uint _maxFeePercentage
    ) external override {
        require(canRedeem(msg.sender), "Caller does not have redemption privileges");

        RedemptionTotals memory totals;

        ContractsCache memory contractsCache =
                        ContractsCache(activePool, defaultPool, stableToken, feeTokenStaking, sortedPositions, collateralSurplusPool);

        totals.version = collateralController.getVersion(address(this));
        totals.maxFeePCT = _maxFeePercentage;

        (totals.cooldownRequirement, totals.gracePeriod, totals.redemptionsTimeoutFeePct) =
            collateralController.getRedemptionCooldownRequirement(address(collateralToken), totals.version);

        (totals._stableAmount, totals.utilizationPCT, totals.loadIncrease, totals.timedOut) =
            _processRedemptionInputAccordingToSource(
                contractsCache,
                _stableAmount,
                totals.cooldownRequirement,
                totals.gracePeriod,
                totals.redemptionsTimeoutFeePct
            );

        if (totals.timedOut) {
            // user either failed to redeem from escrow in time,
            // or had existing escrow which needed to be dequeued after removal of escrow requirement
            return;
        }

        _requireAmountGreaterThanZero(totals._stableAmount);

        (totals.price, totals.suggestedAdditiveFeePCT) = priceFeed.fetchHighestPriceWithFeeSuggestion(
            totals.loadIncrease,
            totals.utilizationPCT,
            true,
            true
        );

        _requireValidMaxFeePercentage(totals.maxFeePCT, totals.suggestedAdditiveFeePCT);

        uint MCR = collateralController.getMCR(address(collateralToken), totals.version);
        _requireTCRoverMCR(totals.price, MCR);

        totals.totalStableSupplyAtStart = stableToken.totalSupply();
        assert(contractsCache.stableToken.balanceOf(msg.sender) <= totals.totalStableSupplyAtStart);

        totals.remainingStables = totals._stableAmount;
        address currentBorrower;

        if (_isValidFirstRedemptionHint(contractsCache.sortedPositions, _firstRedemptionHint, totals.price, MCR)) {
            currentBorrower = _firstRedemptionHint;
        } else {
            currentBorrower = contractsCache.sortedPositions.getLast();
            while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < MCR) {
                currentBorrower = contractsCache.sortedPositions.getPrev(currentBorrower);
            }
        }

        if (_maxIterations == 0) {_maxIterations = type(uint).max;}
        totals.firstInLine = true;

        while (currentBorrower != address(0) && totals.remainingStables > 0 && _maxIterations > 0) {
            _maxIterations--;
            address nextUserToCheck = contractsCache.sortedPositions.getPrev(currentBorrower);

            _applyPendingRewards(contractsCache.activePool, contractsCache.defaultPool, currentBorrower);

            SingleRedemptionValues memory singleRedemption = _redeemCollateralFromPosition(
                contractsCache,
                currentBorrower,
                totals.remainingStables,
                totals.price,
                _upperPartialRedemptionHint,
                _lowerPartialRedemptionHint,
                _partialRedemptionHintNICR,
                totals.firstInLine
            );

            totals.firstInLine = false;

            if (singleRedemption.cancelledPartial) break;

            totals.totalStablesToRedeem = totals.totalStablesToRedeem + singleRedemption.stableLot;
            totals.totalCollateralDrawn = totals.totalCollateralDrawn + singleRedemption.CollateralLot;

            totals.remainingStables = totals.remainingStables - singleRedemption.stableLot;
            currentBorrower = nextUserToCheck;
        }

        require(totals.totalCollateralDrawn > 0, "Unable to redeem any amount");

        if (totals.cooldownRequirement != 0) {
            _checkIfEscrowDepletedAndReEscrowUnusedStables(totals.remainingStables);
        }

        __updateBaseRateFromRedemption(totals.totalCollateralDrawn, totals.price, totals.totalStableSupplyAtStart);

        totals.CollateralFee = _getRedemptionFee(totals.totalCollateralDrawn, totals.suggestedAdditiveFeePCT);

        _requireUserAcceptsFee(totals.CollateralFee, totals.totalCollateralDrawn, totals.maxFeePCT);

        contractsCache.activePool.sendCollateral(address(contractsCache.feeTokenStaking), totals.CollateralFee);
        contractsCache.feeTokenStaking.increaseF_Collateral(address(collateralToken), totals.version, totals.CollateralFee);

        totals.CollateralToSendToRedeemer = totals.totalCollateralDrawn - totals.CollateralFee;

        emit Redemption(totals._stableAmount, totals.totalStablesToRedeem, totals.totalCollateralDrawn, totals.CollateralFee);

        contractsCache.stableToken.burn(msg.sender, totals.totalStablesToRedeem);
        contractsCache.activePool.decreaseStableDebt(totals.totalStablesToRedeem);
        contractsCache.activePool.sendCollateral(msg.sender, totals.CollateralToSendToRedeemer);
    }

    /**
     * @dev Reads back currently pending escrow details, checks timeout status, and debits amount to attempt.
     * @param attemptAmount The amount of stables the user is asking to redeem
     * @param escrowDuration Lockup time before redemptions can be attempted
     * @param claimGracePeriod Max amount of time a user has to clear their redemption amount
     * @return effectiveAmount The amount of stable tokens which are actually going to be processed
     * @return utilizationPCT The utilization percentage
     * @return loadIncrease The load increase
     * @return timedOut Whether the redemption timed out
     */
    function _validateAndReleaseStablesForRedemption(uint attemptAmount, uint escrowDuration, uint claimGracePeriod) private returns
    (uint effectiveAmount, uint utilizationPCT, uint loadIncrease, bool timedOut) {
        EscrowedRedemption storage redemption = escrowedRedemptions[msg.sender];

        require(redemption.timestamp != 0, "Redemption not queued");
        require(attemptAmount <= redemption.stableAmount, "Cannot redeem more than remaining queued in escrow");

        uint cooldownExpiry = redemption.timestamp + escrowDuration;
        uint gracePeriodExpiry = cooldownExpiry + claimGracePeriod;
        bool isGracePeriod = block.timestamp < gracePeriodExpiry;

        (utilizationPCT, loadIncrease) = (redemption.utilizationPCT, redemption.loadIncrease);

        if (isGracePeriod) {
            require(cooldownExpiry <= block.timestamp, "Redemption escrow timelock not satisfied");
            // debit from escrow, as we are about to try and use attemptAmount in a redemption
            // we will add the unused balance back once the redemption is complete
            timedOut = false;
            effectiveAmount = attemptAmount;
            redemption.stableAmount -= effectiveAmount;
        } else {
            // We are about to return stables to user and charge the timeout fee on total remaining amount
            timedOut = true;
            effectiveAmount = redemption.stableAmount;
            redemption.stableAmount = 0;
        }

        require(stableToken.transfer(msg.sender, effectiveAmount), "stable transfer failed");
    }

    /**
     * @dev Re-queues unused stables, or deletes escrow if all stables within have been utilised
     * @param unusedStables The amount of stables unused after the redemption attempt
     */
    function _checkIfEscrowDepletedAndReEscrowUnusedStables(uint unusedStables) private {
        EscrowedRedemption storage escrow = escrowedRedemptions[msg.sender];

        if (unusedStables == 0 && escrow.stableAmount == 0) {
            // if we used everything, the escrow is now exhausted and safe to delete
            delete escrowedRedemptions[msg.sender];
        } else if (unusedStables != 0) {
            // otherwise, transfer back left over stables for next attempt
            stableToken.transferForRedemptionEscrow(msg.sender, address(this), unusedStables);
            escrow.stableAmount += unusedStables;
        }
    }

    /**
    * @dev Performs validation and unpacking of redemption data
    * @param contractsCache Cache of contract references
    * @param requestedStables Amount of stables requested for redemption by the user
    * @param cooldownRequirement Required waiting period in escrow before redemptions can happen
    * @param gracePeriod Time given in which to clear the total redemption amount before suffering a fee
    * @param redemptionsTimeoutFeePct Fee percentage charged if redemption has timed out
    * @return effectiveStables Post validation amount of stables to redeem
    * @return utilizationPCT System utilization percentage at time of escrow
    * @return loadIncrease Impact on points utilization
    * @return timedOut Whether the redemption request has expired
    */
    function _processRedemptionInputAccordingToSource(
        ContractsCache memory contractsCache,
        uint requestedStables,
        uint cooldownRequirement,
        uint gracePeriod,
        uint redemptionsTimeoutFeePct
    ) private returns (uint effectiveStables, uint utilizationPCT, uint loadIncrease, bool timedOut) {
        if (cooldownRequirement != 0) {
            (effectiveStables, utilizationPCT, loadIncrease, timedOut) =
                _validateAndReleaseStablesForRedemption(requestedStables, cooldownRequirement, gracePeriod);

            // Effective stables should have been returned to redeemer during _validateAndReleaseStablesForRedemption
            _requireStableBalanceCoversRedemption(contractsCache.stableToken, msg.sender, effectiveStables);

            if (timedOut) {
                _chargeTimeoutFeeAndClearEscrow(contractsCache, effectiveStables, redemptionsTimeoutFeePct);
            }
        } else {
            if (hasEnqueuedEscrow(msg.sender)) {
                _dequeueEscrow();
                (effectiveStables, utilizationPCT, loadIncrease, timedOut) = (0, 0, 0, true);
            } else {
                timedOut = false;
                effectiveStables = requestedStables;

                // No escrow required, so we just need to check that user has at least requestedStables/effectiveStables
                _requireStableBalanceCoversRedemption(contractsCache.stableToken, msg.sender, effectiveStables);

                (utilizationPCT, loadIncrease) =
                    collateralController.regenerateAndConsumeRedemptionPoints(effectiveStables);
            }
        }
    }

    /**
    * @dev Charges a timeout fee and clears the escrow when a redemption request expires
    * @param contractsCache Cache of contract references
    * @param stablesNotClearedInTime Amount of stables that weren't redeemed before timeout
    * @param redemptionsTimeoutFeePct Percentage fee charged for timeout
    */
    function _chargeTimeoutFeeAndClearEscrow(
        ContractsCache memory contractsCache,
        uint stablesNotClearedInTime,
        uint redemptionsTimeoutFeePct
    ) private {
        uint timeoutFee = (redemptionsTimeoutFeePct * stablesNotClearedInTime) / DECIMAL_PRECISION;
        contractsCache.feeTokenStaking.increaseF_STABLE(timeoutFee);
        contractsCache.stableToken.transferForRedemptionEscrow(msg.sender, address(contractsCache.feeTokenStaking), timeoutFee);
        delete escrowedRedemptions[msg.sender];
    }

    /**
     * @dev Dequeues an escrowed redemption when cooldown requirement is zero
     */
    function _dequeueEscrow() private {
        EscrowedRedemption memory redemption = escrowedRedemptions[msg.sender];
        if (redemption.timestamp != 0) {
            require(stableToken.transfer(msg.sender, redemption.stableAmount), "stable transfer failed");
            delete escrowedRedemptions[msg.sender];
        }
    }

    // --- Helper functions ---

    /**
     * @dev Calculates the nominal ICR (Individual Collateralization Ratio) for a position
     * @param _borrower The address of the position owner
     * @return The nominal ICR
     */
    function getNominalICR(address _borrower) public view override returns (uint) {
        (uint currentCollateral, uint currentStableDebt) = _getCurrentPositionAmounts(_borrower);

        uint NICR = StableMath._computeNominalCR(currentCollateral, currentStableDebt, collateralToken.decimals());
        return NICR;
    }

    /**
     * @dev Calculates the current ICR (Individual Collateralization Ratio) for a position
     * @param _borrower The address of the position owner
     * @param _price The current price of the collateral
     * @return The current ICR
     */
    function getCurrentICR(address _borrower, uint _price) public view override returns (uint) {
        return _getCurrentICR(_borrower, _price);
    }

    /**
     * @dev Applies pending rewards to a position
     * @param _borrower The address of the position owner
     */
    function applyPendingRewards(address _borrower) external override {
        _requireCallerIsPositionController();
        return _applyPendingRewards(activePool, defaultPool, _borrower);
    }

    /**
     * @dev Internal function to apply pending rewards to a position
     * @param _activePool The active pool contract
     * @param _defaultPool The default pool contract
     * @param _borrower The address of the position owner
     */
    function _applyPendingRewards(IActivePool _activePool, IDefaultPool _defaultPool, address _borrower) internal {
        if (hasPendingRewards(_borrower)) {
            _requirePositionIsActive(_borrower);

            uint pendingCollateralReward = getPendingCollateralReward(_borrower);
            uint pendingStableDebtReward = getPendingStableDebtReward(_borrower);

            Positions[_borrower].coll = Positions[_borrower].coll + pendingCollateralReward;
            Positions[_borrower].debt = Positions[_borrower].debt + pendingStableDebtReward;

            _updatePositionRewardSnapshots(_borrower);

            _movePendingPositionRewardsToActivePool(_activePool, _defaultPool, pendingStableDebtReward, pendingCollateralReward);

            emit PositionUpdated(
                _borrower,
                Positions[_borrower].debt,
                Positions[_borrower].coll,
                Positions[_borrower].stake,
                uint8(PositionManagerOperation.applyPendingRewards)
            );
        }
    }

    /**
     * @dev Updates the reward snapshots for a position
     * @param _borrower The address of the position owner
     */
    function updatePositionRewardSnapshots(address _borrower) external override {
        _requireCallerIsPositionController();
        return _updatePositionRewardSnapshots(_borrower);
    }

    /**
     * @dev Internal function to update the reward snapshots for a position
     * @param _borrower The address of the position owner
     */
    function _updatePositionRewardSnapshots(address _borrower) internal {
        rewardSnapshots[_borrower].Collateral = L_Collateral;
        rewardSnapshots[_borrower].stableDebt = L_StableDebt;
    }

    /**
     * @dev Calculates the pending collateral reward for a position
     * @param _borrower The address of the position owner
     * @return The pending collateral reward
     */
    function getPendingCollateralReward(address _borrower) public view override returns (uint) {
        return _getPendingCollateralReward(_borrower);
    }

    /**
     * @dev Calculates the pending stable debt reward for a position
     * @param _borrower The address of the position owner
     * @return The pending stable debt reward
     */
    function getPendingStableDebtReward(address _borrower) public view override returns (uint) {
        return _getPendingStableDebtReward(_borrower);
    }

    /**
     * @dev Checks if a position has pending rewards
     * @param _borrower The address of the position owner
     * @return A boolean indicating if the position has pending rewards
     */
    function hasPendingRewards(address _borrower) public view override returns (bool) {
        if (Positions[_borrower].status != Status.active) {return false;}
        return (rewardSnapshots[_borrower].Collateral < L_Collateral);
    }

    /**
     * @dev Gets the entire debt and collateral for a position, including pending rewards
     * @param _borrower The address of the position owner
     * @return debt The total debt of the position
     * @return coll The total collateral of the position
     * @return pendingStableDebtReward The pending stable debt reward
     * @return pendingCollateralReward The pending collateral reward
     */
    function getEntireDebtAndColl(
        address _borrower
    )
    public
    view
    override
    returns (uint debt, uint coll, uint pendingStableDebtReward, uint pendingCollateralReward)
    {
        return _getEntireDebtAndColl(_borrower);
    }

    /**
     * @dev Removes the stake for a position
     * @param _borrower The address of the position owner
     */
    function removeStake(address _borrower) external override {
        _requireCallerIsPositionController();
        return _removeStake(_borrower);
    }

    /**
     * @dev Updates the stake and total stakes for a position
     * @param _borrower The address of the position owner
     * @return The new stake amount
     */
    function updateStakeAndTotalStakes(address _borrower) external override returns (uint) {
        _requireCallerIsPositionController();
        return _updateStakeAndTotalStakes(_borrower);
    }

    /**
     * @dev Internal function to update the stake and total stakes for a position
     * @param _borrower The address of the position owner
     * @return The new stake amount
     */
    function _updateStakeAndTotalStakes(address _borrower) internal returns (uint) {
        uint newStake = _computeNewStake(Positions[_borrower].coll);
        uint oldStake = Positions[_borrower].stake;
        Positions[_borrower].stake = newStake;
        totalStakes = (totalStakes - oldStake) + newStake;
        emit StakesUpdated(totalStakes);
        return newStake;
    }

    /**
     * @dev Computes a new stake based on the collateral amount
     * @param _coll The collateral amount
     * @return The computed stake
     */
    function _computeNewStake(uint _coll) internal view returns (uint) {
        uint stake;
        if (totalCollateralSnapshot == 0) {
            stake = _coll;
        } else {
            assert(totalStakesSnapshot > 0);
            stake = (_coll * totalStakesSnapshot) / totalCollateralSnapshot;
        }
        return stake;
    }

    /**
     * @dev Closes a position
     * @param _borrower The address of the position owner
     */
    function closePosition(address _borrower) external override {
        _requireCallerIsPositionController();
        return _closePosition(_borrower, Status.closedByOwner);
    }

    /**
     * @dev Adds a position owner to the array of position owners
     * @param _borrower The address of the position owner
     * @return index The index of the added position owner
     */
    function addPositionOwnerToArray(address _borrower) external override returns (uint index) {
        _requireCallerIsPositionController();
        return _addPositionOwnerToArray(_borrower);
    }

    /**
     * @dev Internal function to add a position owner to the array of position owners
     * @param _borrower The address of the position owner
     * @return index The index of the added position owner
     */
    function _addPositionOwnerToArray(address _borrower) internal returns (uint128 index) {
        PositionOwners.push(_borrower);
        index = uint128(PositionOwners.length - 1);
        Positions[_borrower].arrayIndex = index;
        return index;
    }

    // --- Redemption fee functions ---

    /**
     * @dev Calculates the redemption rate
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated redemption rate
     */
    function getRedemptionRate(uint suggestedAdditiveFeePCT) public view virtual returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if(brt == ICollateralController.BaseRateType.Global) {
            return _calcRedemptionRate(collateralController.getBaseRate(), suggestedAdditiveFeePCT);
        } else {
            return _calcRedemptionRate(_baseRate, suggestedAdditiveFeePCT);
        }
    }

    /**
     * @dev Calculates the redemption rate with decay
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated redemption rate with decay
     */
    function getRedemptionRateWithDecay(uint suggestedAdditiveFeePCT) public view override returns (uint) {
        return _calcRedemptionRate(__calcDecayedBaseRate(), suggestedAdditiveFeePCT);
    }

    /**
     * @dev Internal function to calculate the redemption rate
     * @param _baseRate The base rate
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated redemption rate
     */
    function _calcRedemptionRate(uint _baseRate, uint suggestedAdditiveFeePCT) internal view returns (uint) {
        return collateralController.calcRedemptionRate(address(collateralToken), _baseRate, suggestedAdditiveFeePCT);
    }

    /**
     * @dev Internal function to calculate the borrowing rate
     * @param _baseRate The base rate
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated borrowing rate
     */
    function _calcBorrowingRate(uint _baseRate, uint suggestedAdditiveFeePCT) internal view returns (uint) {
        return collateralController.calcBorrowingRate(address(collateralToken), _baseRate, suggestedAdditiveFeePCT);
    }

    /**
     * @dev Calculates the redemption fee
     * @param _CollateralDrawn The amount of collateral drawn
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated redemption fee
     */
    function _getRedemptionFee(uint _CollateralDrawn, uint suggestedAdditiveFeePCT) internal view returns (uint) {
        return _calcRedemptionFee(getRedemptionRate(suggestedAdditiveFeePCT), _CollateralDrawn);
    }

    /**
     * @dev Calculates the redemption fee with decay
     * @param _CollateralDrawn The amount of collateral drawn
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated redemption fee with decay
     */
    function getRedemptionFeeWithDecay(uint _CollateralDrawn, uint suggestedAdditiveFeePCT) external view override returns (uint) {
        return _calcRedemptionFee(getRedemptionRateWithDecay(suggestedAdditiveFeePCT), _CollateralDrawn);
    }

    /**
     * @dev Internal function to calculate the redemption fee
     * @param _redemptionRate The redemption rate
     * @param _CollateralDrawn The amount of collateral drawn
     * @return The calculated redemption fee
     */
    function _calcRedemptionFee(uint _redemptionRate, uint _CollateralDrawn) internal pure returns (uint) {
        uint redemptionFee = (_redemptionRate * _CollateralDrawn) / DECIMAL_PRECISION;
        require(redemptionFee < _CollateralDrawn, "Fee would eat up all returned collateral");
        return redemptionFee;
    }

    // --- Borrowing fee functions ---

    /**
     * @dev Calculates the borrowing rate with decay
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated borrowing rate with decay
     */
    function getBorrowingRateWithDecay(uint suggestedAdditiveFeePCT) public view override returns (uint) {
        return _calcBorrowingRate(__calcDecayedBaseRate(), suggestedAdditiveFeePCT);
    }

    /**
     * @dev Calculates the borrowing fee
     * @param _stableDebt The stable debt amount
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated borrowing fee
     */
    function getBorrowingFee(uint _stableDebt, uint suggestedAdditiveFeePCT) external view override returns (uint) {
        return _calcBorrowingFee(getBorrowingRate(suggestedAdditiveFeePCT), _stableDebt);
    }

    /**
     * @dev Calculates the borrowing fee with decay
     * @param _stableDebt The stable debt amount
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated borrowing fee with decay
     */
    function getBorrowingFeeWithDecay(uint _stableDebt, uint suggestedAdditiveFeePCT) external view override returns (uint) {
        return _calcBorrowingFee(getBorrowingRateWithDecay(suggestedAdditiveFeePCT), _stableDebt);
    }

    /**
     * @dev Internal function to calculate the borrowing fee
     * @param _borrowingRate The borrowing rate
     * @param _stableDebt The stable debt amount
     * @return The calculated borrowing fee
     */
    function _calcBorrowingFee(uint _borrowingRate, uint _stableDebt) internal pure returns (uint) {
        return (_borrowingRate * _stableDebt) / DECIMAL_PRECISION;
    }

    /**
     * @dev Decays the base rate from borrowing
     */
    function decayBaseRateFromBorrowing() external override {
        _requireCallerIsPositionController();

        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if(brt == ICollateralController.BaseRateType.Global) {
            collateralController.decayBaseRateFromBorrowing();
        } else {
            _decayBaseRateFromBorrowing();
        }
    }

    /**
     * @dev Ensures that the caller is the PositionController
     */
    function _requireCallerIsPositionController() internal view {
        require(msg.sender == positionControllerAddress, "Caller is not the PositionController");
    }

    /**
     * @dev Checks if a position is active
     * @param _borrower The address of the position owner
     */
    function _requirePositionIsActive(address _borrower) internal view {
        require(Positions[_borrower].status == Status.active, "Position does not exist or is closed");
    }

    /**
     * @dev Ensures that the redeemer has sufficient stable token balance for redemption
     * @param _stableToken The stable token contract
     * @param _redeemer The address of the redeemer
     * @param _amount The amount to be redeemed
     */
    function _requireStableBalanceCoversRedemption(IStable _stableToken, address _redeemer, uint _amount) internal view {
        require(_stableToken.balanceOf(_redeemer) >= _amount, "Requested redemption amount must be <= user's stable token balance");
    }

    /**
     * @dev Checks if the given amount is greater than zero
     * @param _amount The amount to check
     */
    function _requireAmountGreaterThanZero(uint _amount) internal pure {
        require(_amount > 0, "Amount must be greater than zero");
    }

    /**
     * @dev Retrieves the total debt in the system
     * @return total The total debt
     */
    function getEntireDebt() public override view returns (uint total) {
        return _getEntireDebt();
    }

    /**
     * @dev Retrieves the total collateral in the system
     * @return total The total collateral
     */
    function getEntireCollateral() public override view returns (uint total) {
        return _getEntireCollateral();
    }

    /**
     * @dev Calculates the Total Collateralization Ratio (TCR)
     * @param _price The current price of the collateral
     * @return TCR The Total Collateralization Ratio
     */
    function getTCR(uint _price) external view override returns (uint TCR) {
        return _getTCR(_price);
    }

    /**
     * @dev Checks if the system is in Recovery Mode
     * @param _price The current price of the collateral
     * @return A boolean indicating if the system is in Recovery Mode
     */
    function checkRecoveryMode(uint _price) external view override returns (bool) {
        return _checkRecoveryMode(_price);
    }

    /**
     * @dev Checks if the PositionManager has been sunset
     * @return A boolean indicating if the PositionManager is sunset
     */
    function isSunset() external view override returns (bool) {
        return collateralController.decommissionedAndSunsetPositionManager(address(this), address(collateralToken));
    }

    /**
     * @dev Ensures that the Total Collateralization Ratio (TCR) is above the Minimum Collateralization Ratio (MCR)
     * @param _price The current price of the collateral
     * @param MCR The Minimum Collateralization Ratio
     */
    function _requireTCRoverMCR(uint _price, uint MCR) internal view {
        require(_getTCR(_price) >= MCR, "Cannot redeem when TCR < MCR");
    }

    /**
     * @dev Validates the maximum fee percentage
     * @param _maxFeePercentage The maximum fee percentage specified
     * @param volatilityFee The current volatility fee
     */
    function _requireValidMaxFeePercentage(uint _maxFeePercentage, uint volatilityFee) internal view {
        uint8 version = collateralController.getVersion(address(this));
        uint256 minRedemptionsFeePct = collateralController.getMinRedemptionsFeePct(address(collateralToken), version);
        require(
            _maxFeePercentage >= StableMath._max(DYNAMIC_REDEMPTION_FEE_FLOOR, minRedemptionsFeePct) + volatilityFee &&
            _maxFeePercentage <= DECIMAL_PRECISION,
            "Max fee percentage must be between 0.5% and 100%"
        );
    }

    /**
     * @dev Calculates the borrowing rate
     * @param suggestedAdditiveFeePCT The suggested additive fee percentage
     * @return The calculated borrowing rate
     */
    function getBorrowingRate(uint suggestedAdditiveFeePCT) public view override returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if(brt == ICollateralController.BaseRateType.Global) {
            return _calcBorrowingRate(collateralController.getBaseRate(), suggestedAdditiveFeePCT);
        } else {
            return _calcBorrowingRate(_baseRate, suggestedAdditiveFeePCT);
        }
    }

    /**
     * @dev Updates the base rate from redemption
     * @param _CollateralDrawn The amount of collateral drawn
     * @param _price The current price of the collateral
     * @param _totalStableSupply The total supply of stable tokens
     * @return The updated base rate
     */
    function __updateBaseRateFromRedemption(uint _CollateralDrawn, uint _price, uint _totalStableSupply) internal virtual returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if(brt == ICollateralController.BaseRateType.Global) {
            return collateralController.updateBaseRateFromRedemption(_CollateralDrawn, _price, _totalStableSupply);
        } else {
            return _updateBaseRateFromRedemption(_CollateralDrawn, _price, _totalStableSupply);
        }
    }

    /**
     * @dev Retrieves the current base rate
     * @return The current base rate
     */
    function baseRate() external virtual view returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if(brt == ICollateralController.BaseRateType.Global) {
            return collateralController.getBaseRate();
        } else {
            return _baseRate;
        }
    }

    /**
     * @dev Retrieves the timestamp of the last fee operation
     * @return The timestamp of the last fee operation
     */
    function lastFeeOperationTime() external virtual view returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if (brt == ICollateralController.BaseRateType.Global) {
            return collateralController.getLastFeeOperationTime();
        } else {
            return _lastFeeOperationTime;
        }
    }

    /**
     * @dev Updates the timestamp of the last fee operation
     */
    function __updateLastFeeOpTime() internal virtual {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if (brt == ICollateralController.BaseRateType.Global) {
            collateralController.updateLastFeeOpTime();
        } else {
            _updateLastFeeOpTime();
        }
    }

    /**
     * @dev Calculates the decayed base rate
     * @return The decayed base rate
     */
    function __calcDecayedBaseRate() internal virtual view returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if (brt == ICollateralController.BaseRateType.Global) {
            return collateralController.calcDecayedBaseRate();
        } else {
            return _calcDecayedBaseRate();
        }
    }

    /**
     * @dev Calculates the minutes passed since the last fee operation
     * @return The number of minutes passed since the last fee operation
     */
    function __minutesPassedSinceLastFeeOp() internal virtual view returns (uint) {
        ICollateralController.BaseRateType brt = collateralController.getBaseRateType();
        if (brt == ICollateralController.BaseRateType.Global) {
            return collateralController.minutesPassedSinceLastFeeOp();
        } else {
            return _minutesPassedSinceLastFeeOp();
        }
    }

    /**
     * @dev Gets the status of a position
     * @param _borrower The address of the position owner
     * @return The status of the position
     */
    function getPositionStatus(address _borrower) external view override returns (uint) {
        return uint(Positions[_borrower].status);
    }

    /**
     * @dev Gets the stake of a position
     * @param _borrower The address of the position owner
     * @return The stake of the position
     */
    function getPositionStake(address _borrower) external view override returns (uint) {
        return Positions[_borrower].stake;
    }

    /**
     * @dev Gets the debt of a position
     * @param _borrower The address of the position owner
     * @return The debt of the position
     */
    function getPositionDebt(address _borrower) external view override returns (uint) {
        return Positions[_borrower].debt;
    }

    /**
     * @dev Gets the collateral of a position
     * @param _borrower The address of the position owner
     * @return The collateral of the position
     */
    function getPositionColl(address _borrower) external view override returns (uint) {
        return Positions[_borrower].coll;
    }

    // --- Position property setters, called by PositionController ---

    /**
     * @dev Sets the status of a position
     * @param _borrower The address of the position owner
     * @param _num The new status value
     */
    function setPositionStatus(address _borrower, uint _num) external override {
        _requireCallerIsPositionController();
        Positions[_borrower].status = Status(_num);
    }

    /**
     * @dev Increases the collateral of a position
     * @param _borrower The address of the position owner
     * @param _collIncrease The amount to increase the collateral by
     * @return The new collateral amount
     */
    function increasePositionColl(address _borrower, uint _collIncrease) external override returns (uint) {
        _requireCallerIsPositionController();
        uint newColl = Positions[_borrower].coll + _collIncrease;
        Positions[_borrower].coll = newColl;
        return newColl;
    }

    /**
     * @dev Decreases the collateral of a position
     * @param _borrower The address of the position owner
     * @param _collDecrease The amount to decrease the collateral by
     * @return The new collateral amount
     */
    function decreasePositionColl(address _borrower, uint _collDecrease) external override returns (uint) {
        _requireCallerIsPositionController();
        uint newColl = Positions[_borrower].coll - _collDecrease;
        Positions[_borrower].coll = newColl;
        return newColl;
    }

    /**
     * @dev Increases the debt of a position
     * @param _borrower The address of the position owner
     * @param _debtIncrease The amount to increase the debt by
     * @return The new debt amount
     */
    function increasePositionDebt(address _borrower, uint _debtIncrease) external override returns (uint) {
        _requireCallerIsPositionController();
        uint newDebt = Positions[_borrower].debt + _debtIncrease;
        Positions[_borrower].debt = newDebt;
        return newDebt;
    }

    /**
     * @dev Decreases the debt of a position
     * @param _borrower The address of the position owner
     * @param _debtDecrease The amount to decrease the debt by
     * @return The new debt amount
     */
    function decreasePositionDebt(address _borrower, uint _debtDecrease) external override returns (uint) {
        _requireCallerIsPositionController();
        uint newDebt = Positions[_borrower].debt - _debtDecrease;
        Positions[_borrower].debt = newDebt;
        return newDebt;
    }
}

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

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

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

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 5 of 34 : IERC2612.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC2612.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/extensions/IERC20Permit.sol";

interface IERC2612 is IERC20Permit {}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

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

pragma solidity ^0.8.0;

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

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

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

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

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

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

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

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

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

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

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "./BaseMath.sol";

/* Contains global system constants and common functions. */
contract Base is BaseMath {
    uint constant internal SECONDS_IN_ONE_MINUTE = 60;

    /*
     * Half-life of 12h. 12h = 720 min
     * (1/2) = d^720 => d = (1/2)^(1/720)
     */
    uint constant internal 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.
    */
    uint constant internal BETA = 2;

    uint constant public _100pct = 1000000000000000000; // 1e18 == 100%

    // Min net debt remains a system global due to its rationale for keeping SortedPositions relatively small
    uint constant public MIN_NET_DEBT = 1800e18;

    uint constant internal PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%

    // Gas compensation is not configurable per collateral type, as this is
    // more-so a chain specific consideration rather than collateral specific
    uint constant public GAS_COMPENSATION = 200e18;

    // A dynamic fee, which kicks in and acts as a floor if the custom min fee % attached to a collateral instance is too low.
    uint constant public DYNAMIC_BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%
    uint constant public DYNAMIC_REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%

    address internal positionControllerAddress;
    address internal gasPoolAddress;

    // Return the amount of Collateral to be drawn from a position's collateral and sent as gas compensation.
    function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
        return _entireColl / PERCENT_DIVISOR;
    }

    function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure {
        uint feePercentage = (_fee * DECIMAL_PRECISION) / _amount;
        require(feePercentage <= _maxFeePercentage, "Fee exceeded");
    }
}

File 17 of 34 : BaseMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

contract BaseMath {
    uint constant public DECIMAL_PRECISION = 1e18;
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

library StableMath {
    uint internal constant DECIMAL_PRECISION = 1e18;

    /* Precision for Nominal ICR (independent of price). Rationale for the value:
     *
     * - Making it “too high” could lead to overflows.
     * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division. 
     *
     * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH,
     * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
     *
     */
    uint internal constant NICR_PRECISION = 1e20;

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

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

    /* 
    * 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(uint x, uint y) internal pure returns (uint decProd) {
        uint 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 PositionManager._calcDecayedBaseRate
    *
    * 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(uint _base, uint _minutes) internal pure returns (uint) {
       
        if (_minutes > 525600000) {_minutes = 525600000;}  // cap to avoid overflow
    
        if (_minutes == 0) {return DECIMAL_PRECISION;}

        uint y = DECIMAL_PRECISION;
        uint x = _base;
        uint 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(uint _a, uint _b) internal pure returns (uint) {
        return (_a >= _b) ? _a - _b : _b - _a;
    }

    function _adjustDecimals(uint _val, uint8 _collDecimals) internal pure returns (uint) {
        if (_collDecimals < 18) {
            return _val * (10 ** (18 - _collDecimals));
        } else if (_collDecimals > 18) {
            // Assuming _collDecimals won't exceed 25, this should be safe from overflow.
            return _val / (10 ** (_collDecimals - 18));
        } else {
            return _val;
        }
    }

    function _computeNominalCR(uint _coll, uint _debt, uint8 _collDecimals) internal pure returns (uint) {
        if (_debt > 0) {
            _coll = _adjustDecimals(_coll, _collDecimals);
            return (_coll * NICR_PRECISION) / _debt;
        }
        // Return the maximal value for uint256 if the Position has a debt of 0. Represents "infinite" CR.
        else { // if (_debt == 0)
            return type(uint256).max;
        }
    }

    function _computeCR(uint _coll, uint _debt, uint _price, uint8 _collDecimals) internal pure returns (uint) {
        // Check for zero debt to avoid division by zero
        if (_debt == 0) {
            return type(uint256).max; // Infinite CR since there's no debt.
        }

        _coll = _adjustDecimals(_coll, _collDecimals);
        uint newCollRatio = (_coll * _price) / _debt;
        return newCollRatio;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "./IPool.sol";
import "./ICanReceiveCollateral.sol";

/// @title IActivePool Interface
/// @notice Interface for the ActivePool contract which manages the main collateral pool
interface IActivePool is IPool, ICanReceiveCollateral {
    /// @notice Emitted when the stable debt in the ActivePool is updated
    /// @param _STABLEDebt The new total stable debt amount
    event ActivePoolStableDebtUpdated(uint _STABLEDebt);

    /// @notice Emitted when the collateral balance in the ActivePool is updated
    /// @param _Collateral The new total collateral amount
    event ActivePoolCollateralBalanceUpdated(uint _Collateral);

    /// @notice Sends collateral from the ActivePool to a specified account
    /// @param _account The address of the account to receive the collateral
    /// @param _amount The amount of collateral to send
    function sendCollateral(address _account, uint _amount) external;

    /// @notice Sets the addresses of connected contracts and components
    /// @param _positionControllerAddress Address of the PositionController contract
    /// @param _positionManagerAddress Address of the PositionManager contract
    /// @param _backstopPoolAddress Address of the BackstopPool contract
    /// @param _defaultPoolAddress Address of the DefaultPool contract
    /// @param _collateralAssetAddress Address of the collateral asset token
    function setAddresses(
        address _positionControllerAddress,
        address _positionManagerAddress,
        address _backstopPoolAddress,
        address _defaultPoolAddress,
        address _collateralAssetAddress
    ) external;
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

/// @title IBackstopPool Interface
/// @notice Interface for the BackstopPool contract which manages deposits and collateral gains
interface IBackstopPool {
    /// @notice Struct to represent collateral gains for a specific asset
    struct CollateralGain {
        address asset;
        uint gains;
    }

    /// @notice Emitted when the collateral balance of the BackstopPool is updated
    /// @param asset The address of the collateral asset
    /// @param _newBalance The new balance of the collateral
    event BackstopPoolCollateralBalanceUpdated(address asset, uint _newBalance);

    /// @notice Emitted when the stable token balance of the BackstopPool is updated
    /// @param _newBalance The new balance of stable tokens
    event BackstopPoolStableBalanceUpdated(uint _newBalance);

    /// @notice Emitted when the product P is updated
    /// @param _P The new value of P
    event P_Updated(uint _P);

    /// @notice Emitted when the sum S is updated for a specific collateral asset
    /// @param collateralAsset The address of the collateral asset
    /// @param _S The new value of S
    /// @param _epoch The current epoch
    /// @param _scale The current scale
    event S_Updated(address collateralAsset, uint _S, uint128 _epoch, uint128 _scale);

    /// @notice Emitted when the sum G is updated
    /// @param _G The new value of G
    /// @param _epoch The current epoch
    /// @param _scale The current scale
    event G_Updated(uint _G, uint128 _epoch, uint128 _scale);

    /// @notice Emitted when the current epoch is updated
    /// @param _currentEpoch The new current epoch
    event EpochUpdated(uint128 _currentEpoch);

    /// @notice Emitted when the current scale is updated
    /// @param _currentScale The new current scale
    event ScaleUpdated(uint128 _currentScale);

    /// @notice Emitted when a depositor's snapshot is updated
    /// @param _depositor The address of the depositor
    /// @param _asset The address of the asset
    /// @param _P The current value of P
    /// @param _S The current value of S
    /// @param _G The current value of G
    event DepositSnapshotUpdated(address indexed _depositor, address indexed _asset, uint _P, uint _S, uint _G);

    /// @notice Emitted when a user's deposit amount changes
    /// @param _depositor The address of the depositor
    /// @param _newDeposit The new deposit amount
    event UserDepositChanged(address indexed _depositor, uint _newDeposit);

    /// @notice Emitted when collateral gains are withdrawn
    /// @param _depositor The address of the depositor
    /// @param gains An array of CollateralGain structs representing the gains
    /// @param _stableLoss The amount of stable tokens lost
    event CollateralGainsWithdrawn(address indexed _depositor, IBackstopPool.CollateralGain[] gains, uint _stableLoss);

    /// @notice Emitted when collateral is sent to an address
    /// @param asset The address of the collateral asset
    /// @param _to The recipient address
    /// @param _amount The amount of collateral sent
    event CollateralSent(address indexed asset, address indexed _to, uint _amount);

    /// @notice Emitted when fee tokens are paid to a depositor
    /// @param _depositor The address of the depositor
    /// @param _feeToken The amount of fee tokens paid
    event FeeTokenPaidToDepositor(address indexed _depositor, uint _feeToken);

    /// @notice Sets the addresses of connected contracts
    /// @param _collateralController The address of the CollateralController contract
    /// @param _stableTokenAddress The address of the StableToken contract
    /// @param _positionController The address of the PositionController contract
    /// @param _incentivesIssuance The address of the IncentivesIssuance contract
    function setAddresses(address _collateralController, address _stableTokenAddress, address _positionController, address _incentivesIssuance) external;

    /// @notice Allows a user to provide stable tokens to the BackstopPool
    /// @param _amount The amount of stable tokens to provide
    function provideToBP(uint _amount) external;

    /// @notice Allows a user to withdraw stable tokens from the BackstopPool
    /// @param _amount The amount of stable tokens to withdraw
    function withdrawFromBP(uint _amount) external;

    /// @notice Allows a user to withdraw collateral gains to their position
    /// @param asset The address of the collateral asset
    /// @param version The version of the collateral
    /// @param _upperHint The upper hint for position insertion
    /// @param _lowerHint The lower hint for position insertion
    function withdrawCollateralGainToPosition(address asset, uint8 version, address _upperHint, address _lowerHint) external;

    /// @notice Offsets debt with collateral
    /// @param collateralAsset The address of the collateral asset
    /// @param version The version of the collateral
    /// @param _debt The amount of debt to offset
    /// @param _coll The amount of collateral to add
    function offset(address collateralAsset, uint8 version, uint _debt, uint _coll) external;

    /// @notice Gets the total amount of a specific collateral in the BackstopPool
    /// @param asset The address of the collateral asset
    /// @return The amount of collateral
    function getCollateral(address asset) external view returns (uint);

    /// @notice Gets the total amount of stable token deposits in the BackstopPool
    /// @return The total amount of stable token deposits
    function getTotalStableDeposits() external view returns (uint);

    /// @notice Gets the collateral gains for a depositor
    /// @param _depositor The address of the depositor
    /// @return An array of CollateralGain structs representing the gains
    function getDepositorCollateralGains(address _depositor) external view returns (IBackstopPool.CollateralGain[] memory);

    /// @notice Gets the collateral gain for a specific asset and depositor
    /// @param asset The address of the collateral asset
    /// @param _depositor The address of the depositor
    /// @return The amount of collateral gain
    function getDepositorCollateralGain(address asset, address _depositor) external view returns (uint);

    /// @notice Gets the compounded stable deposit for a depositor
    /// @param _depositor The address of the depositor
    /// @return The compounded stable deposit amount
    function getCompoundedStableDeposit(address _depositor) external view returns (uint);

    /// @notice Gets the sum S for a specific asset, epoch, and scale
    /// @param asset The address of the collateral asset
    /// @param epoch The epoch number
    /// @param scale The scale number
    /// @return The sum S
    function getEpochToScaleToSum(address asset, uint128 epoch, uint128 scale) external view returns(uint);

    /// @notice Gets the fee token gain for a depositor
    /// @param _depositor The address of the depositor
    /// @return The amount of fee token gain
    function getDepositorFeeTokenGain(address _depositor) external view returns (uint);

    /// @notice Gets the sum S from the deposit snapshot for a specific user and asset
    /// @param user The address of the user
    /// @param asset The address of the asset
    /// @return The sum S from the deposit snapshot
    function getDepositSnapshotToAssetToSum(address user, address asset) external view returns(uint);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

// Common interface for the contracts which need internal collateral counters to be updated.
interface ICanReceiveCollateral {
    function receiveCollateral(address asset, uint amount) external;
}

File 22 of 34 : ICollateralController.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

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

import "./IActivePool.sol";
import "./ICollateralSurplusPool.sol";
import "./IDefaultPool.sol";
import "./IPriceFeed.sol";
import "./ISortedPositions.sol";
import "./IPositionManager.sol";

/// @title ICollateralController Interface
/// @notice Interface for the CollateralController contract which manages multiple collateral types and their settings
interface ICollateralController {
    /// @notice Emitted when the redemption cooldown requirement is changed
    /// @param newRedemptionCooldownRequirement The new cooldown period for redemptions
    event RedemptionCooldownRequirementChanged(uint newRedemptionCooldownRequirement);

    /// @notice Gets the address of the guardian
    /// @return The address of the guardian
    function getGuardian() external view returns (address);

    /// @notice Structure to hold redemption settings for a collateral type
    struct RedemptionSettings {
        uint256 redemptionCooldownPeriod;
        uint256 redemptionGracePeriod;
        uint256 maxRedemptionPoints;
        uint256 availableRedemptionPoints;
        uint256 redemptionRegenerationRate;
        uint256 lastRedemptionRegenerationTimestamp;
    }

    /// @notice Structure to hold loan settings for a collateral type
    struct LoanSettings {
        uint256 loanCooldownPeriod;
        uint256 loanGracePeriod;
        uint256 maxLoanPoints;
        uint256 availableLoanPoints;
        uint256 loanRegenerationRate;
        uint256 lastLoanRegenerationTimestamp;
    }

    /// @notice Enum to represent the base rate type
    enum BaseRateType {
        Global,
        Local
    }

    /// @notice Structure to hold fee settings for a collateral type
    struct FeeSettings {
        uint256 redemptionsTimeoutFeePct;
        uint256 maxRedemptionsFeePct;
        uint256 minRedemptionsFeePct;
        uint256 minBorrowingFeePct;
        uint256 maxBorrowingFeePct;
        BaseRateType baseRateType;
    }

    /// @notice Structure to hold all settings for a collateral type
    struct Settings {
        uint256 debtCap;
        uint256 decommissionedOn;
        uint256 MCR;
        uint256 CCR;
        RedemptionSettings redemptionSettings;
        LoanSettings loanSettings;
        FeeSettings feeSettings;
    }

    /// @notice Structure to represent a collateral type and its associated contracts
    struct Collateral {
        uint8 version;
        IActivePool activePool;
        ICollateralSurplusPool collateralSurplusPool;
        IDefaultPool defaultPool;
        IERC20Metadata asset;
        IPriceFeed priceFeed;
        ISortedPositions sortedPositions;
        IPositionManager positionManager;
        bool sunset;
    }

    /// @notice Structure to represent a collateral type with its settings and associated contracts
    struct CollateralWithSettings {
        string name;
        string symbol;
        uint8 decimals;
        uint8 version;
        Settings settings;
        IActivePool activePool;
        ICollateralSurplusPool collateralSurplusPool;
        IDefaultPool defaultPool;
        IERC20Metadata asset;
        IPriceFeed priceFeed;
        ISortedPositions sortedPositions;
        IPositionManager positionManager;
        bool sunset;
        uint256 availableRedemptionPoints;
        uint256 availableLoanPoints;
    }

    /// @notice Adds support for a new collateral type
    /// @param collateralAddress Address of the collateral token
    /// @param positionManagerAddress Address of the PositionManager contract
    /// @param sortedPositionsAddress Address of the SortedPositions contract
    /// @param activePoolAddress Address of the ActivePool contract
    /// @param priceFeedAddress Address of the PriceFeed contract
    /// @param defaultPoolAddress Address of the DefaultPool contract
    /// @param collateralSurplusPoolAddress Address of the CollateralSurplusPool contract
    function supportCollateral(
        address collateralAddress,
        address positionManagerAddress,
        address sortedPositionsAddress,
        address activePoolAddress,
        address priceFeedAddress,
        address defaultPoolAddress,
        address collateralSurplusPoolAddress
    ) external;

    /// @notice Gets all active collateral types
    /// @return An array of Collateral structs representing active collateral types
    function getActiveCollaterals() external view returns (Collateral[] memory);

    /// @notice Gets the unique addresses of all active collateral tokens
    /// @return An array of addresses representing active collateral token addresses
    function getUniqueActiveCollateralAddresses() external view returns (address[] memory);

    /// @notice Gets the debt cap for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return debtCap The debt cap for the specified collateral type
    function getDebtCap(address asset, uint8 version) external view returns (uint debtCap);

    /// @notice Gets the Critical Collateral Ratio (CCR) for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return The CCR for the specified collateral type
    function getCCR(address asset, uint8 version) external view returns (uint);

    /// @notice Gets the Minimum Collateral Ratio (MCR) for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return The MCR for the specified collateral type
    function getMCR(address asset, uint8 version) external view returns (uint);

    /// @notice Gets the minimum borrowing fee percentage for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return The minimum borrowing fee percentage for the specified collateral type
    function getMinBorrowingFeePct(address asset, uint8 version) external view returns (uint);

    /// @notice Gets the maximum borrowing fee percentage for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return The maximum borrowing fee percentage for the specified collateral type
    function getMaxBorrowingFeePct(address asset, uint8 version) external view returns (uint);

    /// @notice Gets the minimum redemption fee percentage for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return The minimum redemption fee percentage for the specified collateral type
    function getMinRedemptionsFeePct(address asset, uint8 version) external view returns (uint);

    /// @notice Requires that the commissioning period has passed for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    function requireAfterCommissioningPeriod(address asset, uint8 version) external view;

    /// @notice Requires that a specific collateral type is active
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    function requireIsActive(address asset, uint8 version) external view;

    /// @notice Gets the Collateral struct for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return A Collateral struct representing the specified collateral type
    function getCollateralInstance(address asset, uint8 version) external view returns (ICollateralController.Collateral memory);

    /// @notice Gets the Settings struct for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return A Settings struct representing the settings for the specified collateral type
    function getSettings(address asset, uint8 version) external view returns (ICollateralController.Settings memory);

    /// @notice Gets the total collateral amount for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return assetColl The total collateral amount for the specified collateral type
    function getAssetColl(address asset, uint8 version) external view returns (uint assetColl);

    /// @notice Gets the total debt amount for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return assetDebt The total debt amount for the specified collateral type
    function getAssetDebt(address asset, uint8 version) external view returns (uint assetDebt);

    /// @notice Gets the version of a specific PositionManager
    /// @param positionManager Address of the PositionManager contract
    /// @return version The version of the specified PositionManager
    function getVersion(address positionManager) external view returns (uint8 version);

    /// @notice Checks if a specific collateral type is in Recovery Mode
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @param price Current price of the collateral
    /// @return A boolean indicating whether the collateral type is in Recovery Mode
    function checkRecoveryMode(address asset, uint8 version, uint price) external returns (bool);

    /// @notice Requires that there are no undercollateralized positions across all collateral types
    function requireNoUnderCollateralizedPositions() external;

    /// @notice Checks if a given address is a valid PositionManager
    /// @param positionManager Address to check
    /// @return A boolean indicating whether the address is a valid PositionManager
    function validPositionManager(address positionManager) external view returns (bool);

    /// @notice Checks if a specific collateral type is decommissioned
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return A boolean indicating whether the collateral type is decommissioned
    function isDecommissioned(address asset, uint8 version) external view returns (bool);

    /// @notice Checks if a specific PositionManager is decommissioned and its sunset period has elapsed
    /// @param pm Address of the PositionManager
    /// @param collateral Address of the collateral token
    /// @return A boolean indicating whether the PositionManager is decommissioned and its sunset period has elapsed
    function decommissionedAndSunsetPositionManager(address pm, address collateral) external view returns (bool);

    /// @notice Gets the base rate type (Global or Local)
    /// @return The base rate type
    function getBaseRateType() external view returns (BaseRateType);

    /// @notice Gets the timestamp of the last fee operation
    /// @return The timestamp of the last fee operation
    function getLastFeeOperationTime() external view returns (uint);

    /// @notice Gets the current base rate
    /// @return The current base rate
    function getBaseRate() external view returns (uint);

    /// @notice Decays the base rate from borrowing
    function decayBaseRateFromBorrowing() external;

    /// @notice Updates the timestamp of the last fee operation
    function updateLastFeeOpTime() external;

    /// @notice Calculates the number of minutes passed since the last fee operation
    /// @return The number of minutes passed since the last fee operation
    function minutesPassedSinceLastFeeOp() external view returns (uint);

    /// @notice Calculates the decayed base rate
    /// @return The decayed base rate
    function calcDecayedBaseRate() external view returns (uint);

    /// @notice Updates the base rate from redemption
    /// @param _CollateralDrawn Amount of collateral drawn
    /// @param _price Current price of the collateral
    /// @param _totalStableSupply Total supply of stable tokens
    /// @return The updated base rate
    function updateBaseRateFromRedemption(uint _CollateralDrawn, uint _price, uint _totalStableSupply) external returns (uint);

    /// @notice Regenerates and consumes redemption points
    /// @param amount Amount of redemption points to consume
    /// @return utilizationPCT The utilization percentage after consumption
    /// @return loadIncrease The increase in load after consumption
    function regenerateAndConsumeRedemptionPoints(uint amount) external returns (uint utilizationPCT, uint loadIncrease);

    /// @notice Gets the redemption cooldown requirement for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return escrowDuration The duration of the escrow period
    /// @return gracePeriod The grace period for redemptions
    /// @return redemptionsTimeoutFeePct The fee percentage for redemption timeouts
    function getRedemptionCooldownRequirement(address asset, uint8 version) external returns (uint escrowDuration,uint gracePeriod,uint redemptionsTimeoutFeePct);

    /// @notice Calculates the redemption points at a specific timestamp for a collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @param targetTimestamp The timestamp to calculate the redemption points for
    /// @return workingRedemptionPoints The redemption points at the specified timestamp
    function redemptionPointsAt(address asset, uint8 version, uint targetTimestamp) external view returns (uint workingRedemptionPoints);

    /// @notice Regenerates and consumes loan points
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @param amount Amount of loan points to consume
    /// @return utilizationPCT The utilization percentage after consumption
    /// @return loadIncrease The increase in load after consumption
    function regenerateAndConsumeLoanPoints(address asset, uint8 version, uint amount) external returns (uint utilizationPCT, uint loadIncrease);

    /// @notice Gets the loan cooldown requirement for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @return escrowDuration The duration of the escrow period
    /// @return gracePeriod The grace period for loans
    function getLoanCooldownRequirement(address asset, uint8 version) external view returns (uint escrowDuration, uint gracePeriod);

    /// @notice Calculates the loan points at a specific timestamp for a collateral type
    /// @param asset Address of the collateral token
    /// @param version Version of the collateral type
    /// @param targetTimestamp The timestamp to calculate the loan points for
    /// @return workingLoanPoints The loan points at the specified timestamp
    function loanPointsAt(address asset, uint8 version, uint targetTimestamp) external view returns (uint workingLoanPoints);

    /// @notice Calculates the borrowing rate for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param baseRate The base rate to use in the calculation
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The calculated borrowing rate
    function calcBorrowingRate(address asset, uint baseRate, uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Calculates the redemption rate for a specific collateral type
    /// @param asset Address of the collateral token
    /// @param baseRate The base rate to use in the calculation
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The calculated redemption rate
    function calcRedemptionRate(address asset, uint baseRate, uint suggestedAdditiveFeePCT) external view returns (uint);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "./ICanReceiveCollateral.sol";

/// @title ICollateralSurplusPool Interface
/// @notice Interface for the CollateralSurplusPool contract which manages surplus collateral
interface ICollateralSurplusPool is ICanReceiveCollateral {
    /// @notice Emitted when a user's collateral balance is updated
    /// @param _account The address of the account
    /// @param _newBalance The new balance of the account
    event CollBalanceUpdated(address indexed _account, uint _newBalance);

    /// @notice Emitted when collateral is sent to an account
    /// @param _to The address receiving the collateral
    /// @param _amount The amount of collateral sent
    event CollateralSent(address _to, uint _amount);

    /// @notice Sets the addresses of connected contracts
    /// @param _positionControllerAddress Address of the PositionController contract
    /// @param _positionManagerAddress Address of the PositionManager contract
    /// @param _activePoolAddress Address of the ActivePool contract
    /// @param _collateralAssetAddress Address of the collateral asset token
    function setAddresses(address _positionControllerAddress, address _positionManagerAddress, address _activePoolAddress, address _collateralAssetAddress) external;

    /// @notice Gets the total amount of collateral in the pool
    /// @return The total amount of collateral
    function getCollateral() external view returns (uint);

    /// @notice Gets the amount of claimable collateral for a specific account
    /// @param _account The address of the account
    /// @return The amount of claimable collateral for the account
    function getUserCollateral(address _account) external view returns (uint);

    /// @notice Accounts for surplus collateral for a specific account
    /// @param _account The address of the account
    /// @param _amount The amount of surplus collateral to account for
    function accountSurplus(address _account, uint _amount) external;

    /// @notice Allows an account to claim their surplus collateral
    /// @param _account The address of the account claiming the collateral
    function claimColl(address _account) external;
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "./IPool.sol";
import "./ICanReceiveCollateral.sol";

/// @title IDefaultPool Interface
/// @notice Interface for the DefaultPool contract which manages defaulted debt and collateral
interface IDefaultPool is IPool, ICanReceiveCollateral {
    /// @notice Emitted when the STABLE debt in the DefaultPool is updated
    /// @param _STABLEDebt The new total STABLE debt amount
    event DefaultPoolSTABLEDebtUpdated(uint _STABLEDebt);

    /// @notice Emitted when the collateral balance in the DefaultPool is updated
    /// @param _Collateral The new total collateral amount
    event DefaultPoolCollateralBalanceUpdated(uint _Collateral);

    /// @notice Sends collateral from the DefaultPool to the ActivePool
    /// @param _amount The amount of collateral to send
    function sendCollateralToActivePool(uint _amount) external;

    /// @notice Sets the addresses of connected contracts
    /// @param _positionManagerAddress Address of the PositionManager contract
    /// @param _activePoolAddress Address of the ActivePool contract
    /// @param _collateralAssetAddress Address of the collateral asset token
    function setAddresses(address _positionManagerAddress, address _activePoolAddress, address _collateralAssetAddress) external;
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;
import "./IBackstopPool.sol";

/**
 * @title IFeeTokenStaking
 * @dev Interface for the FeeTokenStaking contract.
 */
interface IFeeTokenStaking {
    /**
     * @dev Emitted when a user's stake amount changes
     * @param staker Address of the staker
     * @param newStake New stake amount
     */
    event StakeChanged(address indexed staker, uint newStake);

    /**
     * @dev Emitted when stable token rewards are withdrawn
     * @param staker Address of the staker
     * @param stableGain Amount of stable tokens withdrawn
     */
    event StakingStablesWithdrawn(address indexed staker, uint stableGain);

    /**
     * @dev Emitted when collateral rewards are withdrawn
     * @param asset Address of the collateral asset
     * @param staker Address of the staker
     * @param _amount Amount of collateral withdrawn
     */
    event StakingCollateralWithdrawn(address indexed asset, address indexed staker, uint _amount);

    /**
     * @dev Emitted when the cumulative collateral rewards per staked token is updated
     * @param asset Address of the collateral asset
     * @param _F_Collateral New cumulative collateral rewards value
     */
    event F_CollateralUpdated(address asset, uint _F_Collateral);

    /**
     * @dev Emitted when the cumulative stable token rewards per staked token is updated
     * @param _F_STABLE New cumulative stable token rewards value
     */
    event F_STABLEUpdated(uint _F_STABLE);

    /**
     * @dev Emitted when the total amount of staked FeeTokens is updated
     * @param _totalfeeTokenStaked New total amount of staked FeeTokens
     */
    event TotalFeeTokenStakedUpdated(uint _totalfeeTokenStaked);

    /**
     * @dev Emitted when a staker's reward snapshots are updated
     * @param _staker Address of the staker
     * @param _F_Collateral New collateral rewards snapshot
     * @param _F_STABLE New stable token rewards snapshot
     */
    event StakerSnapshotsUpdated(address _staker, uint _F_Collateral, uint _F_STABLE);

    /**
     * @dev Sets the addresses for the contract dependencies
     * @param _feeTokenAddress Address of the FeeToken contract
     * @param _stableTokenAddress Address of the StableToken contract
     * @param _positionControllerAddress Address of the PositionController contract
     * @param _collateralControllerAddress Address of the CollateralController contract
     */
    function setAddresses(
        address _feeTokenAddress,
        address _stableTokenAddress,
        address _positionControllerAddress,
        address _collateralControllerAddress
    ) external;

    /**
     * @dev Allows users to stake FeeTokens
     * @param _feeTokenAmount Amount of FeeTokens to stake
     */
    function stake(uint _feeTokenAmount) external;

    /**
     * @dev Allows users to unstake FeeTokens and claim rewards
     * @param _feeTokenAmount Amount of FeeTokens to unstake
     */
    function unstake(uint _feeTokenAmount) external;

    /**
     * @dev Increases the cumulative collateral rewards per staked token
     * @param asset Address of the collateral asset
     * @param version Version of the collateral asset
     * @param _CollateralFee Amount of collateral fee to distribute
     */
    function increaseF_Collateral(address asset, uint8 version, uint _CollateralFee) external;

    /**
     * @dev Increases the cumulative stable token rewards per staked token
     * @param _feeTokenFee Amount of stable token fee to distribute
     */
    function increaseF_STABLE(uint _feeTokenFee) external;

    /**
     * @dev Gets the pending collateral gains for a user
     * @param _user Address of the user
     * @return An array of CollateralGain structs representing pending gains
     */
    function getPendingCollateralGains(address _user) external view returns (IBackstopPool.CollateralGain[] memory);

    /**
     * @dev Gets the pending collateral gain for a specific asset and user
     * @param asset Address of the collateral asset
     * @param _user Address of the user
     * @return The pending collateral gain amount
     */
    function getPendingCollateralGain(address asset, address _user) external view returns (uint);

    /**
     * @dev Gets the pending stable token gain for a user
     * @param _user Address of the user
     * @return The pending stable token gain amount
     */
    function getPendingStableGain(address _user) external view returns (uint);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

/// @title IPool Interface
/// @notice Interface for Pool contracts that manage collateral and stable debt
interface IPool {
    /// @notice Emitted when collateral is sent from the pool
    /// @param _to The address receiving the collateral
    /// @param _amount The amount of collateral sent
    event CollateralSent(address _to, uint _amount);

    /// @notice Gets the total amount of collateral in the pool
    /// @return The total amount of collateral
    function getCollateral() external view returns (uint);

    /// @notice Gets the total amount of stable debt in the pool
    /// @return The total amount of stable debt
    function getStableDebt() external view returns (uint);

    /// @notice Increases the stable debt in the pool
    /// @param _amount The amount to increase the debt by
    function increaseStableDebt(uint _amount) external;

    /// @notice Decreases the stable debt in the pool
    /// @param _amount The amount to decrease the debt by
    function decreaseStableDebt(uint _amount) external;
}

File 27 of 34 : IPositionManager.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

/// @title IPositionManager Interface
/// @notice Interface for the PositionManager contract which manages individual positions
interface IPositionManager {
    /// @notice Emitted when a redemption occurs
    /// @param _attemptedStableAmount The amount of stable tokens attempted to redeem
    /// @param _actualStableAmount The actual amount of stable tokens redeemed
    /// @param _CollateralSent The amount of collateral sent to the redeemer
    /// @param _CollateralFee The fee paid in collateral for the redemption
    event Redemption(uint _attemptedStableAmount, uint _actualStableAmount, uint _CollateralSent, uint _CollateralFee);

    /// @notice Emitted when total stakes are updated
    /// @param _newTotalStakes The new total stakes value
    event TotalStakesUpdated(uint _newTotalStakes);

    /// @notice Emitted when system snapshots are updated
    /// @param _totalStakesSnapshot The new total stakes snapshot
    /// @param _totalCollateralSnapshot The new total collateral snapshot
    event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);

    /// @notice Emitted when L terms are updated
    /// @param _L_Collateral The new L_Collateral value
    /// @param _L_STABLE The new L_STABLE value
    event LTermsUpdated(uint _L_Collateral, uint _L_STABLE);

    /// @notice Emitted when position snapshots are updated
    /// @param _L_Collateral The new L_Collateral value for the position
    /// @param _L_STABLEDebt The new L_STABLEDebt value for the position
    event PositionSnapshotsUpdated(uint _L_Collateral, uint _L_STABLEDebt);

    /// @notice Emitted when a position's index is updated
    /// @param _borrower The address of the position owner
    /// @param _newIndex The new index value
    event PositionIndexUpdated(address _borrower, uint _newIndex);

    /// @notice Get the total count of position owners
    /// @return The number of position owners
    function getPositionOwnersCount() external view returns (uint);

    /// @notice Get a position owner's address by index
    /// @param _index The index in the position owners array
    /// @return The address of the position owner
    function getPositionFromPositionOwnersArray(uint _index) external view returns (address);

    /// @notice Get the nominal ICR (Individual Collateral Ratio) of a position
    /// @param _borrower The address of the position owner
    /// @return The nominal ICR of the position
    function getNominalICR(address _borrower) external view returns (uint);

    /// @notice Get the current ICR of a position
    /// @param _borrower The address of the position owner
    /// @param _price The current price of the collateral
    /// @return The current ICR of the position
    function getCurrentICR(address _borrower, uint _price) external view returns (uint);

    /// @notice Liquidate a single position
    /// @param _borrower The address of the position owner to liquidate
    function liquidate(address _borrower) external;

    /// @notice Liquidate multiple positions
    /// @param _n The number of positions to attempt to liquidate
    function liquidatePositions(uint _n) external;

    /// @notice Batch liquidate a specific set of positions
    /// @param _positionArray An array of position owner addresses to liquidate
    function batchLiquidatePositions(address[] calldata _positionArray) external;

    /// @notice Queue a redemption request
    /// @param _stableAmount The amount of stable tokens to queue for redemption
    function queueRedemption(uint _stableAmount) external;

    /// @notice Redeem collateral for stable tokens
    /// @param _stableAmount The amount of stable tokens to redeem
    /// @param _firstRedemptionHint The address of the first position to consider for redemption
    /// @param _upperPartialRedemptionHint The address of the position just above the partial redemption
    /// @param _lowerPartialRedemptionHint The address of the position just below the partial redemption
    /// @param _partialRedemptionHintNICR The nominal ICR of the partial redemption hint
    /// @param _maxIterations The maximum number of iterations to perform in the redemption algorithm
    /// @param _maxFee The maximum acceptable fee percentage for the redemption
    function redeemCollateral(
        uint _stableAmount,
        address _firstRedemptionHint,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint _partialRedemptionHintNICR,
        uint _maxIterations,
        uint _maxFee
    ) external;

    /// @notice Update the stake and total stakes for a position
    /// @param _borrower The address of the position owner
    /// @return The new stake value
    function updateStakeAndTotalStakes(address _borrower) external returns (uint);

    /// @notice Update the reward snapshots for a position
    /// @param _borrower The address of the position owner
    function updatePositionRewardSnapshots(address _borrower) external;

    /// @notice Add a position owner to the array of position owners
    /// @param _borrower The address of the position owner
    /// @return index The index of the new position owner in the array
    function addPositionOwnerToArray(address _borrower) external returns (uint index);

    /// @notice Apply pending rewards to a position
    /// @param _borrower The address of the position owner
    function applyPendingRewards(address _borrower) external;

    /// @notice Get the pending collateral reward for a position
    /// @param _borrower The address of the position owner
    /// @return The amount of pending collateral reward
    function getPendingCollateralReward(address _borrower) external view returns (uint);

    /// @notice Get the pending stable debt reward for a position
    /// @param _borrower The address of the position owner
    /// @return The amount of pending stable debt reward
    function getPendingStableDebtReward(address _borrower) external view returns (uint);

    /// @notice Check if a position has pending rewards
    /// @param _borrower The address of the position owner
    /// @return True if the position has pending rewards, false otherwise
    function hasPendingRewards(address _borrower) external view returns (bool);

    /// @notice Get the entire debt and collateral for a position, including pending rewards
    /// @param _borrower The address of the position owner
    /// @return debt The total debt of the position
    /// @return coll The total collateral of the position
    /// @return pendingStableDebtReward The pending stable debt reward
    /// @return pendingCollateralReward The pending collateral reward
    function getEntireDebtAndColl(address _borrower)
    external view returns (uint debt, uint coll, uint pendingStableDebtReward, uint pendingCollateralReward);

    /// @notice Close a position
    /// @param _borrower The address of the position owner
    function closePosition(address _borrower) external;

    /// @notice Remove the stake for a position
    /// @param _borrower The address of the position owner
    function removeStake(address _borrower) external;

    /// @notice Get the current redemption rate
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The current redemption rate
    function getRedemptionRate(uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Get the redemption rate with decay
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The redemption rate with decay applied
    function getRedemptionRateWithDecay(uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Get the redemption fee with decay
    /// @param _CollateralDrawn The amount of collateral drawn
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The redemption fee with decay applied
    function getRedemptionFeeWithDecay(uint _CollateralDrawn, uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Get the current borrowing rate
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The current borrowing rate
    function getBorrowingRate(uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Get the borrowing rate with decay
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The borrowing rate with decay applied
    function getBorrowingRateWithDecay(uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Get the borrowing fee
    /// @param stableDebt The amount of stable debt
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The borrowing fee
    function getBorrowingFee(uint stableDebt, uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Get the borrowing fee with decay
    /// @param _stableDebt The amount of stable debt
    /// @param suggestedAdditiveFeePCT The suggested additive fee percentage
    /// @return The borrowing fee with decay applied
    function getBorrowingFeeWithDecay(uint _stableDebt, uint suggestedAdditiveFeePCT) external view returns (uint);

    /// @notice Decay the base rate from borrowing
    function decayBaseRateFromBorrowing() external;

    /// @notice Get the status of a position
    /// @param _borrower The address of the position owner
    /// @return The status of the position
    function getPositionStatus(address _borrower) external view returns (uint);

    /// @notice Get the stake of a position
    /// @param _borrower The address of the position owner
    /// @return The stake of the position
    function getPositionStake(address _borrower) external view returns (uint);

    /// @notice Get the debt of a position
    /// @param _borrower The address of the position owner
    /// @return The debt of the position
    function getPositionDebt(address _borrower) external view returns (uint);

    /// @notice Get the collateral of a position
    /// @param _borrower The address of the position owner
    /// @return The collateral of the position
    function getPositionColl(address _borrower) external view returns (uint);

    /// @notice Set the status of a position
    /// @param _borrower The address of the position owner
    /// @param num The new status value
    function setPositionStatus(address _borrower, uint num) external;

    /// @notice Increase the collateral of a position
    /// @param _borrower The address of the position owner
    /// @param _collIncrease The amount of collateral to increase
    /// @return The new collateral amount
    function increasePositionColl(address _borrower, uint _collIncrease) external returns (uint);

    /// @notice Decrease the collateral of a position
    /// @param _borrower The address of the position owner
    /// @param _collDecrease The amount of collateral to decrease
    /// @return The new collateral amount
    function decreasePositionColl(address _borrower, uint _collDecrease) external returns (uint);

    /// @notice Increase the debt of a position
    /// @param _borrower The address of the position owner
    /// @param _debtIncrease The amount of debt to increase
    /// @return The new debt amount
    function increasePositionDebt(address _borrower, uint _debtIncrease) external returns (uint);

    /// @notice Decrease the debt of a position
    /// @param _borrower The address of the position owner
    /// @param _debtDecrease The amount of debt to decrease
    /// @return The new debt amount
    function decreasePositionDebt(address _borrower, uint _debtDecrease) external returns (uint);

    /// @notice Get the entire debt of the system
    /// @return total The total debt in the system
    function getEntireDebt() external view returns (uint total);

    /// @notice Get the entire collateral in the system
    /// @return total The total collateral in the system
    function getEntireCollateral() external view returns (uint total);

    /// @notice Get the Total Collateral Ratio (TCR) of the system
    /// @param _price The current price of the collateral
    /// @return TCR The Total Collateral Ratio
    function getTCR(uint _price) external view returns(uint TCR);

    /// @notice Check if the system is in Recovery Mode
    /// @param _price The current price of the collateral
    /// @return True if the system is in Recovery Mode, false otherwise
    function checkRecoveryMode(uint _price) external returns(bool);

    /// @notice Check if the position manager is in sunset mode
    /// @return True if the position manager is in sunset mode, false otherwise
    function isSunset() external returns(bool);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

/// @title IPriceFeed Interface
/// @notice Interface for price feed contracts that provide various price-related functionalities
interface IPriceFeed {
    /// @notice Enum to represent the current operational mode of the oracle
    enum OracleMode {AUTOMATED, FALLBACK}

    /// @notice Struct to hold detailed price information
    struct PriceDetails {
        uint lowestPrice;
        uint highestPrice;
        uint weightedAveragePrice;
        uint spotPrice;
        uint shortTwapPrice;
        uint longTwapPrice;
        uint suggestedAdditiveFeePCT;
        OracleMode currentMode;
    }

    /// @notice Fetches the current price details
    /// @param utilizationPCT The current utilization percentage
    /// @return A PriceDetails struct containing various price metrics
    function fetchPrice(uint utilizationPCT) external view returns (PriceDetails memory);

    /// @notice Fetches the weighted average price, used during liquidations
    /// @param testLiquidity Whether to test for liquidity
    /// @param testDeviation Whether to test for price deviation
    /// @return price The weighted average price
    function fetchWeightedAveragePrice(bool testLiquidity, bool testDeviation) external returns (uint price);

    /// @notice Fetches the lowest price, used when exiting escrow or testing for under-collateralized positions
    /// @param testLiquidity Whether to test for liquidity
    /// @param testDeviation Whether to test for price deviation
    /// @return price The lowest price
    function fetchLowestPrice(bool testLiquidity, bool testDeviation) external returns (uint price);

    /// @notice Fetches the lowest price with a fee suggestion, used when issuing new debt
    /// @param loadIncrease The increase in load
    /// @param originationOrRedemptionLoadPCT The origination or redemption load percentage
    /// @param testLiquidity Whether to test for liquidity
    /// @param testDeviation Whether to test for price deviation
    /// @return price The lowest price
    /// @return suggestedAdditiveFeePCT The suggested additive fee percentage
    function fetchLowestPriceWithFeeSuggestion(
        uint loadIncrease,
        uint originationOrRedemptionLoadPCT,
        bool testLiquidity,
        bool testDeviation
    ) external returns (uint price, uint suggestedAdditiveFeePCT);

    /// @notice Fetches the highest price with a fee suggestion, used during redemptions
    /// @param loadIncrease The increase in load
    /// @param originationOrRedemptionLoadPCT The origination or redemption load percentage
    /// @param testLiquidity Whether to test for liquidity
    /// @param testDeviation Whether to test for price deviation
    /// @return price The highest price
    /// @return suggestedAdditiveFeePCT The suggested additive fee percentage
    function fetchHighestPriceWithFeeSuggestion(
        uint loadIncrease,
        uint originationOrRedemptionLoadPCT,
        bool testLiquidity,
        bool testDeviation
    ) external returns (uint price, uint suggestedAdditiveFeePCT);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

/// @title ISortedPositions Interface
/// @notice Interface for a sorted list of positions, ordered by their Individual Collateral Ratio (ICR)
interface ISortedPositions {
    /// @notice Emitted when the PositionManager address is changed
    /// @param _positionManagerAddress The new address of the PositionManager
    event PositionManagerAddressChanged(address _positionManagerAddress);

    /// @notice Emitted when the PositionController address is changed
    /// @param _positionControllerAddress The new address of the PositionController
    event PositionControllerAddressChanged(address _positionControllerAddress);

    /// @notice Emitted when a new node (position) is added to the list
    /// @param _id The address of the new position
    /// @param _NICR The Nominal Individual Collateral Ratio of the new position
    event NodeAdded(address _id, uint _NICR);

    /// @notice Emitted when a node (position) is removed from the list
    /// @param _id The address of the removed position
    event NodeRemoved(address _id);

    /// @notice Sets the parameters for the sorted list
    /// @param _size The maximum size of the list
    /// @param _positionManagerAddress The address of the PositionManager contract
    /// @param _positionControllerAddress The address of the PositionController contract
    function setParams(uint256 _size, address _positionManagerAddress, address _positionControllerAddress) external;

    /// @notice Inserts a new node (position) into the list
    /// @param _id The address of the new position
    /// @param _ICR The Individual Collateral Ratio of the new position
    /// @param _prevId The address of the previous node in the insertion position
    /// @param _nextId The address of the next node in the insertion position
    function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;

    /// @notice Removes a node (position) from the list
    /// @param _id The address of the position to remove
    function remove(address _id) external;

    /// @notice Re-inserts a node (position) into the list with a new ICR
    /// @param _id The address of the position to re-insert
    /// @param _newICR The new Individual Collateral Ratio of the position
    /// @param _prevId The address of the previous node in the new insertion position
    /// @param _nextId The address of the next node in the new insertion position
    function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;

    /// @notice Checks if a position is in the list
    /// @param _id The address of the position to check
    /// @return bool True if the position is in the list, false otherwise
    function contains(address _id) external view returns (bool);

    /// @notice Checks if the list is full
    /// @return bool True if the list is full, false otherwise
    function isFull() external view returns (bool);

    /// @notice Checks if the list is empty
    /// @return bool True if the list is empty, false otherwise
    function isEmpty() external view returns (bool);

    /// @notice Gets the current size of the list
    /// @return uint256 The current number of positions in the list
    function getSize() external view returns (uint256);

    /// @notice Gets the maximum size of the list
    /// @return uint256 The maximum number of positions the list can hold
    function getMaxSize() external view returns (uint256);

    /// @notice Gets the first position in the list (highest ICR)
    /// @return address The address of the first position
    function getFirst() external view returns (address);

    /// @notice Gets the last position in the list (lowest ICR)
    /// @return address The address of the last position
    function getLast() external view returns (address);

    /// @notice Gets the next position in the list after a given position
    /// @param _id The address of the current position
    /// @return address The address of the next position
    function getNext(address _id) external view returns (address);

    /// @notice Gets the previous position in the list before a given position
    /// @param _id The address of the current position
    /// @return address The address of the previous position
    function getPrev(address _id) external view returns (address);

    /// @notice Checks if a given insertion position is valid for a new ICR
    /// @param _ICR The ICR of the position to insert
    /// @param _prevId The address of the proposed previous node
    /// @param _nextId The address of the proposed next node
    /// @return bool True if the insertion position is valid, false otherwise
    function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);

    /// @notice Finds the correct insertion position for a given ICR
    /// @param _ICR The ICR of the position to insert
    /// @param _prevId A hint for the previous node
    /// @param _nextId A hint for the next node
    /// @return address The address of the previous node for insertion
    /// @return address The address of the next node for insertion
    function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

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

/// @title IStable Interface
/// @notice Interface for the Stable token contract, extending ERC20 and ERC2612 functionality
interface IStable is IERC20, IERC2612 {
    /// @notice Mints new tokens to a specified account
    /// @param _account The address to receive the minted tokens
    /// @param _amount The amount of tokens to mint
    function mint(address _account, uint256 _amount) external;

    /// @notice Burns tokens from a specified account
    /// @param _account The address from which to burn tokens
    /// @param _amount The amount of tokens to burn
    function burn(address _account, uint256 _amount) external;

    /// @notice Transfers tokens from a sender to a pool
    /// @param _sender The address sending the tokens
    /// @param poolAddress The address of the pool receiving the tokens
    /// @param _amount The amount of tokens to transfer
    function sendToPool(address _sender, address poolAddress, uint256 _amount) external;

    /// @notice Transfers tokens for redemption escrow
    /// @param from The address sending the tokens
    /// @param to The address receiving the tokens (likely a position manager)
    /// @param amount The amount of tokens to transfer
    function transferForRedemptionEscrow(address from, address to, uint amount) external;

    /// @notice Returns tokens from a pool to a user
    /// @param poolAddress The address of the pool sending the tokens
    /// @param user The address of the user receiving the tokens
    /// @param _amount The amount of tokens to return
    function returnFromPool(address poolAddress, address user, uint256 _amount) external;
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../common/Base.sol";
import "../common/StableMath.sol";

/**
 * @title BaseRateAbstract
 * @dev Abstract contract for managing a dynamic base rate
 * The base rate is used to calculate fees for redemptions and new issuances of debt.
 * It decays over time and increases based on redemption volume.
 */
abstract contract BaseRateAbstract is Base {
    // Current base rate, represented with precision DECIMAL_PRECISION
    uint public _baseRate;

    // Timestamp of the latest fee operation (redemption or new stable issuance)
    uint public _lastFeeOperationTime;

    event BaseRateUpdated(uint newBaseRate);
    event LastFeeOpTimeUpdated(uint lastFeeOpTime);

    /**
     * @dev Updates the base rate based on a redemption operation
     * @param _CollateralDrawn Amount of collateral drawn for redemption
     * @param _price Price of the collateral
     * @param _totalStableSupply Total supply of the stablecoin
     * @return The new base rate after the update
     */
    function _updateBaseRateFromRedemption(uint _CollateralDrawn, uint _price, uint _totalStableSupply) internal returns (uint) {
        // First, decay the base rate based on time passed since last fee operation
        uint decayedBaseRate = _calcDecayedBaseRate();

        // Calculate the fraction of total supply that was redeemed at face value
        uint redeemedStableFraction = (_CollateralDrawn * _price) / _totalStableSupply;

        // Increase the base rate based on the redeemed fraction
        uint newBaseRate = decayedBaseRate + (redeemedStableFraction / BETA);
        newBaseRate = StableMath._min(newBaseRate, StableMath.DECIMAL_PRECISION); // Cap base rate at 100%
        assert(newBaseRate > 0); // Base rate is always non-zero after redemption

        // Update the base rate state variable
        _baseRate = newBaseRate;
        emit BaseRateUpdated(newBaseRate);

        _updateLastFeeOpTime();

        return newBaseRate;
    }

    /**
     * @dev Calculates the decayed base rate based on time passed since last fee operation
     * @return The decayed base rate
     */
    function _calcDecayedBaseRate() internal view returns (uint) {
        uint minutesPassed = _minutesPassedSinceLastFeeOp();
        uint decayFactor = StableMath._decPow(MINUTE_DECAY_FACTOR, minutesPassed);
        return (_baseRate * decayFactor) / StableMath.DECIMAL_PRECISION;
    }

    /**
     * @dev Calculates the number of minutes passed since the last fee operation
     * @return Number of minutes passed
     */
    function _minutesPassedSinceLastFeeOp() internal view returns (uint) {
        return (block.timestamp - _lastFeeOperationTime) / SECONDS_IN_ONE_MINUTE;
    }

    /**
     * @dev Updates the last fee operation time
     * Only updates if at least one minute has passed to prevent base rate griefing.
     * _lastFeeOperationTime is incremented in multiples of SECONDS_IN_ONE_MINUTE, so that seconds in the current
     * minute are not ignored for the purposes of baseRate decay.
     */
    function _updateLastFeeOpTime() internal {
        uint minutesPassed = _minutesPassedSinceLastFeeOp();

        if (minutesPassed > 0) {
            _lastFeeOperationTime += minutesPassed * SECONDS_IN_ONE_MINUTE;
            emit LastFeeOpTimeUpdated(block.timestamp);
        }
    }

    /**
     * @dev Decays the base rate when new stablecoins are borrowed
     * This function is called during borrowing operations to reduce the base rate over time
     */
    function _decayBaseRateFromBorrowing() internal {
        uint decayedBaseRate = _calcDecayedBaseRate();
        assert(decayedBaseRate <= StableMath.DECIMAL_PRECISION); // The base rate can decay to 0

        _baseRate = decayedBaseRate;
        emit BaseRateUpdated(decayedBaseRate);

        _updateLastFeeOpTime();
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../../common/StableMath.sol";
import "../../../common/Base.sol";
import "../../../interfaces/IPositionManager.sol";
import "../../../interfaces/ISortedPositions.sol";
import "../../../interfaces/ICollateralSurplusPool.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../../../interfaces/IPriceFeed.sol";
import "../../../interfaces/ICollateralController.sol";
import "./PositionState.sol";

/**
 * @title LiquidationManager
 * @dev Contract for managing the liquidation process of positions in the system.
 *
 * Key features:
 *      1. Liquidation Execution: Handles both individual and batch liquidations.
 *      2. Mode-specific Liquidation: Supports liquidations in both Normal and Recovery modes.
 *      3. Collateral Distribution: Manages the distribution of liquidated collateral.
 *      4. Debt Redistribution: Handles the redistribution of debt from liquidated positions.
 *      5. System State Updates: Updates system snapshots after liquidations.
 *      6. Gas Compensation: Provides gas compensation for liquidators.
 */
contract LiquidationManager is PositionState {
    // !!! IMPORTANT !!!: Do not reorder inheritance.
    // PositionState must start at storage slot zero, so that shared liquidation state with PositionManager is aligned.

    /**
     * @dev Liquidates multiple positions up to a specified number.
     * @param _n The maximum number of positions to liquidate.
     */
    function liquidatePositions(uint _n) external {
        ContractsCache memory contractsCache = ContractsCache(
            activePool,
            defaultPool,
            IStable(address(0)),
            IFeeTokenStaking(address(0)),
            sortedPositions,
            ICollateralSurplusPool(address(0))
        );
        IBackstopPool backstopPoolCached = backstopPool;
        LocalVariables_OuterLiquidationFunction memory vars;
        LiquidationTotals memory totals;

        uint8 version = collateralController.getVersion(address(this));

        /*
            A note on why we don't allow the circuit breaker to kick in during liquidations:
            For backstop depositors, buying collateral which is experiencing a rapid price drop, is part of the
            involved risks of being a backstop depositor.  We use a weighted average price to allow the short term
            TWAP to somewhat soften the price they are paying, but in the event where a collateral type is
            experiencing a massive drop, we need to clear that outstanding debt from the USDx supply.

            If we prevented clearing of debt, then by the time price stabilised, we would clear hardly any.
            The primary way to manage risk of highly volatile collateral types, and prevent too much overpriced debt
            being cleared, is by setting appropriate debt caps
        */
        vars.price = priceFeed.fetchWeightedAveragePrice(
            true, // Test liquidity to prevent manipulation of liquidation mechanism
            false // We are softening the deviation with an average, so no need to test it
        );
        vars.stablesInStabPool = backstopPoolCached.getTotalStableDeposits();
        vars.recoveryModeAtStart = _checkRecoveryMode(vars.price);
        uint MCR = collateralController.getMCR(address(collateralToken), collateralController.getVersion(address(this)));
        uint CCR = collateralController.getCCR(address(collateralToken), collateralController.getVersion(address(this)));

        // Perform the appropriate liquidation sequence - tally the values, and obtain their totals
        if (vars.recoveryModeAtStart) {
            totals = _getTotalsFromLiquidatePositionsSequence_RecoveryMode(contractsCache, vars.price, vars.stablesInStabPool, _n, MCR, CCR);
        } else { // if !vars.recoveryModeAtStart
            totals = _getTotalsFromLiquidatePositionsSequence_NormalMode(contractsCache.activePool, contractsCache.defaultPool, vars.price, vars.stablesInStabPool, _n, MCR);
        }

        require(totals.totalDebtInSequence > 0, "Nothing to liquidate");

        // Move liquidated Collateral and stables to the appropriate pools
        backstopPoolCached.offset(address(collateralToken), version, totals.totalDebtToOffset, totals.totalCollToSendToBP);
        _redistributeDebtAndColl(contractsCache.activePool, contractsCache.defaultPool, totals.totalDebtToRedistribute, totals.totalCollToRedistribute);
        if (totals.totalCollSurplus > 0) {
            contractsCache.activePool.sendCollateral(address(collateralSurplusPool), totals.totalCollSurplus);
            collateralSurplusPool.receiveCollateral(address(collateralToken), totals.totalCollSurplus);
        }

        // Update system snapshots
        _updateSystemSnapshots_excludeCollRemainder(contractsCache.activePool, totals.totalCollGasCompensation);

        vars.liquidatedDebt = totals.totalDebtInSequence;
        vars.liquidatedColl = (totals.totalCollInSequence - totals.totalCollGasCompensation) - totals.totalCollSurplus;
        emit Liquidation(vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalGasCompensation);

        // Send gas compensation to caller
        _sendGasCompensation(contractsCache.activePool, msg.sender, totals.totalGasCompensation, totals.totalCollGasCompensation);
    }

    /**
     * @dev Liquidates a batch of positions specified by their addresses.
     * @param _positionArray An array of position addresses to liquidate.
     */
    function batchLiquidatePositions(address[] memory _positionArray) external {
        require(_positionArray.length != 0, "Calldata address array must not be empty");

        IActivePool activePoolCached = activePool;
        IDefaultPool defaultPoolCached = defaultPool;
        IBackstopPool backstopPoolCached = backstopPool;

        LocalVariables_OuterLiquidationFunction memory vars;
        LiquidationTotals memory totals;

        uint8 version = collateralController.getVersion(address(this));

        /*
            A note on why we don't allow the circuit breaker to kick in during liquidations:
            For backstop depositors, buying collateral which is experiencing a rapid price drop, is part of the
            involved risks of being a backstop depositor.  We use a weighted average price to allow the short term
            TWAP to somewhat soften the price they are paying, but in the event where a collateral type is
            experiencing a massive drop, we need to clear that outstanding debt from the USDx supply.

            If we prevented clearing of debt, then by the time price stabilised, we would clear hardly any.
            The primary way to manage risk of highly volatile collateral types, and prevent too much overpriced debt
            being cleared, is by setting appropriate debt caps
        */
        vars.price = priceFeed.fetchWeightedAveragePrice(
            true, // Test liquidity to prevent manipulation of liquidation mechanism
            false // We are softening the deviation with an average, so no need to test it
        );
        vars.stablesInStabPool = backstopPoolCached.getTotalStableDeposits();
        vars.recoveryModeAtStart = _checkRecoveryMode(vars.price);
        uint MCR = collateralController.getMCR(address(collateralToken), collateralController.getVersion(address(this)));
        uint CCR = collateralController.getCCR(address(collateralToken), collateralController.getVersion(address(this)));

        // Perform the appropriate liquidation sequence - tally values and obtain their totals.
        if (vars.recoveryModeAtStart) {
            totals = _getTotalFromBatchLiquidate_RecoveryMode(activePoolCached, defaultPoolCached, vars.price, vars.stablesInStabPool, _positionArray, MCR, CCR);
        } else {  //  if !vars.recoveryModeAtStart
            totals = _getTotalsFromBatchLiquidate_NormalMode(activePoolCached, defaultPoolCached, vars.price, vars.stablesInStabPool, _positionArray, MCR);
        }

        require(totals.totalDebtInSequence > 0, "Nothing to liquidate");

        // Move liquidated Collateral and stable to the appropriate pools
        backstopPoolCached.offset(address(collateralToken), version, totals.totalDebtToOffset, totals.totalCollToSendToBP);
        _redistributeDebtAndColl(activePoolCached, defaultPoolCached, totals.totalDebtToRedistribute, totals.totalCollToRedistribute);
        if (totals.totalCollSurplus > 0) {
            activePoolCached.sendCollateral(address(collateralSurplusPool), totals.totalCollSurplus);
            collateralSurplusPool.receiveCollateral(address(collateralToken), totals.totalCollSurplus);
        }

        // Update system snapshots
        _updateSystemSnapshots_excludeCollRemainder(activePoolCached, totals.totalCollGasCompensation);

        vars.liquidatedDebt = totals.totalDebtInSequence;
        vars.liquidatedColl = (totals.totalCollInSequence - totals.totalCollGasCompensation) - totals.totalCollSurplus;
        emit Liquidation(vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalGasCompensation);

        // Send gas compensation to caller
        _sendGasCompensation(activePoolCached, msg.sender, totals.totalGasCompensation, totals.totalCollGasCompensation);
    }

    /**
     * @dev Calculates totals for liquidating positions in Normal Mode.
     * @param _activePool The active pool contract.
     * @param _defaultPool The default pool contract.
     * @param _price The current price of the collateral.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @param _n The maximum number of positions to liquidate.
     * @param MCR The Minimum Collateralization Ratio.
     * @return totals The calculated liquidation totals.
     */
    function _getTotalsFromLiquidatePositionsSequence_NormalMode(
        IActivePool _activePool,
        IDefaultPool _defaultPool,
        uint _price,
        uint _stablesInBackstopPool,
        uint _n,
        uint MCR
    )
    internal
    returns (LiquidationTotals memory totals)
    {
        LocalVariables_LiquidationSequence memory vars;
        LiquidationValues memory singleLiquidation;
        ISortedPositions sortedPositionsCached = sortedPositions;

        vars.remainingStablesInStabPool = _stablesInBackstopPool;

        for (vars.i = 0; vars.i < _n; vars.i++) {
            vars.user = sortedPositionsCached.getLast();
            vars.ICR = _getCurrentICR(vars.user, _price);

            if (vars.ICR < MCR) {
                singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, vars.user, vars.remainingStablesInStabPool);

                vars.remainingStablesInStabPool = vars.remainingStablesInStabPool - singleLiquidation.debtToOffset;

                // Add liquidation values to their respective running totals
                totals = _addLiquidationValuesToTotals(totals, singleLiquidation);

            } else break;  // break if the loop reaches a Position with ICR >= MCR
        }
    }

    /**
     * @dev Calculates totals for liquidating positions in Recovery Mode.
     * @param _contractsCache A cache of contract addresses.
     * @param _price The current price of the collateral.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @param _n The maximum number of positions to liquidate.
     * @param MCR The Minimum Collateralization Ratio.
     * @param CCR The Critical Collateralization Ratio.
     * @return totals The calculated liquidation totals.
     */
    function _getTotalsFromLiquidatePositionsSequence_RecoveryMode(
        ContractsCache memory _contractsCache,
        uint _price,
        uint _stablesInBackstopPool,
        uint _n,
        uint MCR,
        uint CCR
    )
    internal
    returns (LiquidationTotals memory totals)
    {
        LocalVariables_LiquidationSequence memory vars;
        LiquidationValues memory singleLiquidation;

        vars.remainingStablesInStabPool = _stablesInBackstopPool;
        vars.backToNormalMode = false;
        vars.entireSystemDebt = _getEntireDebt();
        vars.entireSystemColl = _getEntireCollateral();

        vars.user = _contractsCache.sortedPositions.getLast();
        address firstUser = _contractsCache.sortedPositions.getFirst();
        for (vars.i = 0; vars.i < _n && vars.user != firstUser; vars.i++) {
            // we need to cache it, because current user is likely going to be deleted
            address nextUser = _contractsCache.sortedPositions.getPrev(vars.user);

            vars.ICR = _getCurrentICR(vars.user, _price);

            if (!vars.backToNormalMode) {
                // Break the loop if ICR is greater than MCR and Backstop Pool is empty
                if (vars.ICR >= MCR && vars.remainingStablesInStabPool == 0) {break;}
                (vars, singleLiquidation, totals) = _performRecoveryLiquidation(vars, _contractsCache, singleLiquidation, totals, _price, CCR);
            }
            else if (vars.backToNormalMode && vars.ICR < MCR) {
                singleLiquidation = _liquidateNormalMode(_contractsCache.activePool, _contractsCache.defaultPool, vars.user, vars.remainingStablesInStabPool);

                vars.remainingStablesInStabPool = vars.remainingStablesInStabPool - singleLiquidation.debtToOffset;

                // Add liquidation values to their respective running totals
                totals = _addLiquidationValuesToTotals(totals, singleLiquidation);

            } else break;  // break if the loop reaches a Position with ICR >= MCR

            vars.user = nextUser;
        }
    }

    /**
     * @dev Calculates totals for batch liquidating positions in Recovery Mode.
     * @param _activePool The active pool contract.
     * @param _defaultPool The default pool contract.
     * @param _price The current price of the collateral.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @param _positionArray An array of position addresses to liquidate.
     * @param MCR The Minimum Collateralization Ratio.
     * @param CCR The Critical Collateralization Ratio.
     * @return totals The calculated liquidation totals.
     */
    function _getTotalFromBatchLiquidate_RecoveryMode(
        IActivePool _activePool,
        IDefaultPool _defaultPool,
        uint _price,
        uint _stablesInBackstopPool,
        address[] memory _positionArray,
        uint MCR,
        uint CCR
    )
    internal
    returns (LiquidationTotals memory totals)
    {
        LocalVariables_LiquidationSequence memory vars;
        LiquidationValues memory singleLiquidation;

        vars.remainingStablesInStabPool = _stablesInBackstopPool;
        vars.backToNormalMode = false;
        vars.entireSystemDebt = _getEntireDebt();
        vars.entireSystemColl = _getEntireCollateral();

        for (vars.i = 0; vars.i < _positionArray.length; vars.i++) {
            vars.user = _positionArray[vars.i];
            // Skip non-active Positions
            if (Positions[vars.user].status != Status.active) {continue;}
            vars.ICR = _getCurrentICR(vars.user, _price);

            if (!vars.backToNormalMode) {

                // Skip this position if ICR is greater than MCR and Backstop Pool is empty
                if (vars.ICR >= MCR && vars.remainingStablesInStabPool == 0) {continue;}

                uint TCR = StableMath._computeCR(vars.entireSystemColl, vars.entireSystemDebt, _price, collateralToken.decimals());

                singleLiquidation = _liquidateRecoveryMode(_activePool, _defaultPool, vars.user, vars.ICR, vars.remainingStablesInStabPool, TCR, _price);

                // Update aggregate trackers
                vars.remainingStablesInStabPool = vars.remainingStablesInStabPool - singleLiquidation.debtToOffset;
                vars.entireSystemDebt = vars.entireSystemDebt - singleLiquidation.debtToOffset;
                vars.entireSystemColl =
                    ((vars.entireSystemColl - singleLiquidation.collToSendToBP) -
                        singleLiquidation.collGasCompensation) - singleLiquidation.collSurplus;

                // Add liquidation values to their respective running totals
                totals = _addLiquidationValuesToTotals(totals, singleLiquidation);

                vars.backToNormalMode = !_checkPotentialRecoveryMode(vars.entireSystemColl, vars.entireSystemDebt, _price, CCR);
            }

            else if (vars.backToNormalMode && vars.ICR < MCR) {
                singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, vars.user, vars.remainingStablesInStabPool);
                vars.remainingStablesInStabPool = vars.remainingStablesInStabPool - singleLiquidation.debtToOffset;

                // Add liquidation values to their respective running totals
                totals = _addLiquidationValuesToTotals(totals, singleLiquidation);

            } else continue; // In Normal Mode skip Positions with ICR >= MCR
        }
    }

    /**
     * @dev Calculates totals for batch liquidating positions in Normal Mode.
     * @param _activePool The active pool contract.
     * @param _defaultPool The default pool contract.
     * @param _price The current price of the collateral.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @param _positionArray An array of position addresses to liquidate.
     * @param MCR The Minimum Collateralization Ratio.
     * @return totals The calculated liquidation totals.
     */
    function _getTotalsFromBatchLiquidate_NormalMode(
        IActivePool _activePool,
        IDefaultPool _defaultPool,
        uint _price,
        uint _stablesInBackstopPool,
        address[] memory _positionArray,
        uint MCR
    )
    internal
    returns (LiquidationTotals memory totals)
    {
        LocalVariables_LiquidationSequence memory vars;
        LiquidationValues memory singleLiquidation;

        vars.remainingStablesInStabPool = _stablesInBackstopPool;

        for (vars.i = 0; vars.i < _positionArray.length; vars.i++) {
            vars.user = _positionArray[vars.i];
            vars.ICR = _getCurrentICR(vars.user, _price);

            if (vars.ICR < MCR) {
                singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, vars.user, vars.remainingStablesInStabPool);
                vars.remainingStablesInStabPool = vars.remainingStablesInStabPool - singleLiquidation.debtToOffset;

                // Add liquidation values to their respective running totals
                totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
            }
        }
    }

    // --- Liquidation helper functions ---

    /**
     * @dev Adds the values from a single liquidation to the running totals.
     * @param oldTotals The current running totals.
     * @param singleLiquidation The values from the single liquidation to add.
     * @return newTotals The updated running totals.
     */
    function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)
    internal pure returns (LiquidationTotals memory newTotals) {
        // Tally all the values with their respective running totals
        newTotals.totalCollGasCompensation = oldTotals.totalCollGasCompensation + singleLiquidation.collGasCompensation;
        newTotals.totalGasCompensation = oldTotals.totalGasCompensation + singleLiquidation.gasCompensation;
        newTotals.totalDebtInSequence = oldTotals.totalDebtInSequence + singleLiquidation.entirePositionDebt;
        newTotals.totalCollInSequence = oldTotals.totalCollInSequence + singleLiquidation.entirePositionColl;
        newTotals.totalDebtToOffset = oldTotals.totalDebtToOffset + singleLiquidation.debtToOffset;
        newTotals.totalCollToSendToBP = oldTotals.totalCollToSendToBP + singleLiquidation.collToSendToBP;
        newTotals.totalDebtToRedistribute = oldTotals.totalDebtToRedistribute + singleLiquidation.debtToRedistribute;
        newTotals.totalCollToRedistribute = oldTotals.totalCollToRedistribute + singleLiquidation.collToRedistribute;
        newTotals.totalCollSurplus = oldTotals.totalCollSurplus + singleLiquidation.collSurplus;

        return newTotals;
    }

    /**
     * @dev Performs a liquidation in Recovery Mode.
     * @param vars Local variables for the liquidation sequence.
     * @param _contractsCache A cache of contract addresses.
     * @param singleLiquidation The liquidation values for a single position.
     * @param totals The running totals for the liquidation sequence.
     * @param _price The current price of the collateral.
     * @param CCR The Critical Collateralization Ratio.
     * @return Updated vars, singleLiquidation, and totals.
     */
    function _performRecoveryLiquidation(
        LocalVariables_LiquidationSequence memory vars,
        ContractsCache memory _contractsCache,
        LiquidationValues memory singleLiquidation,
        LiquidationTotals memory totals,
        uint _price,
        uint CCR
    ) private returns (
        LocalVariables_LiquidationSequence memory,
        LiquidationValues memory,
        LiquidationTotals memory
    ) {
        uint TCR = StableMath._computeCR(vars.entireSystemColl, vars.entireSystemDebt, _price, collateralToken.decimals());

        singleLiquidation = _liquidateRecoveryMode(_contractsCache.activePool, _contractsCache.defaultPool, vars.user, vars.ICR, vars.remainingStablesInStabPool, TCR, _price);

        // Update aggregate trackers
        vars.remainingStablesInStabPool = vars.remainingStablesInStabPool - singleLiquidation.debtToOffset;
        vars.entireSystemDebt = vars.entireSystemDebt - singleLiquidation.debtToOffset;
        vars.entireSystemColl =
            ((vars.entireSystemColl - singleLiquidation.collToSendToBP) -
                singleLiquidation.collGasCompensation) -
            singleLiquidation.collSurplus;

        // Add liquidation values to their respective running totals
        totals = _addLiquidationValuesToTotals(totals, singleLiquidation);

        vars.backToNormalMode = !_checkPotentialRecoveryMode(vars.entireSystemColl, vars.entireSystemDebt, _price, CCR);

        return (vars, singleLiquidation, totals);
    }

    /**
     * @dev Liquidates a single position in Recovery Mode.
     * @param _activePool The active pool contract.
     * @param _defaultPool The default pool contract.
     * @param _borrower The address of the position's owner.
     * @param _ICR The Individual Collateralization Ratio of the position.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @param _TCR The Total Collateralization Ratio of the system.
     * @param _price The current price of the collateral.
     * @return singleLiquidation The liquidation values for the position.
     */
    function _liquidateRecoveryMode(
        IActivePool _activePool,
        IDefaultPool _defaultPool,
        address _borrower,
        uint _ICR,
        uint _stablesInBackstopPool,
        uint _TCR,
        uint _price
    )
    internal
    returns (LiquidationValues memory singleLiquidation)
    {
        LocalVariables_InnerSingleLiquidateFunction memory vars;
        if (PositionOwners.length <= 1) {return singleLiquidation;} // don't liquidate if last position
        (singleLiquidation.entirePositionDebt, singleLiquidation.entirePositionColl, vars.pendingDebtReward, vars.pendingCollReward) =
            _getEntireDebtAndColl(_borrower);

        singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entirePositionColl);
        singleLiquidation.gasCompensation = GAS_COMPENSATION;
        vars.collToLiquidate = singleLiquidation.entirePositionColl - singleLiquidation.collGasCompensation;

        uint MCR = collateralController.getMCR(address(collateralToken), collateralController.getVersion(address(this)));

        // If ICR <= 100%, purely redistribute the Position across all active Position
        if (_ICR <= _100pct) {
            _movePendingPositionRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
            _removeStake(_borrower);

            singleLiquidation.debtToOffset = 0;
            singleLiquidation.collToSendToBP = 0;
            singleLiquidation.debtToRedistribute = singleLiquidation.entirePositionDebt;
            singleLiquidation.collToRedistribute = vars.collToLiquidate;

            _closePosition(_borrower, Status.closedByLiquidation);
            emit PositionLiquidated(_borrower, singleLiquidation.entirePositionDebt, singleLiquidation.entirePositionColl, uint8(PositionManagerOperation.liquidateInRecoveryMode));
            emit PositionUpdated(_borrower, 0, 0, 0, uint8(PositionManagerOperation.liquidateInRecoveryMode));

            // If 100% < ICR < MCR, offset as much as possible, and redistribute the remainder
        } else if ((_ICR > _100pct) && (_ICR < MCR)) {
            _movePendingPositionRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
            _removeStake(_borrower);

            (singleLiquidation.debtToOffset,
                singleLiquidation.collToSendToBP,
                singleLiquidation.debtToRedistribute,
                singleLiquidation.collToRedistribute) = _getOffsetAndRedistributionVals(singleLiquidation.entirePositionDebt, vars.collToLiquidate, _stablesInBackstopPool);

            _closePosition(_borrower, Status.closedByLiquidation);
            emit PositionLiquidated(_borrower, singleLiquidation.entirePositionDebt, singleLiquidation.entirePositionColl, uint8(PositionManagerOperation.liquidateInRecoveryMode));
            emit PositionUpdated(_borrower, 0, 0, 0, uint8(PositionManagerOperation.liquidateInRecoveryMode));
        } else if ((_ICR >= MCR) && (_ICR < _TCR) && (singleLiquidation.entirePositionDebt <= _stablesInBackstopPool)) {
            _movePendingPositionRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
            assert(_stablesInBackstopPool != 0);

            _removeStake(_borrower);
            singleLiquidation = _getCappedOffsetVals(singleLiquidation.entirePositionDebt, singleLiquidation.entirePositionColl, _price, MCR, GAS_COMPENSATION);

            _closePosition(_borrower, Status.closedByLiquidation);
            if (singleLiquidation.collSurplus > 0) {
                collateralSurplusPool.accountSurplus(_borrower, singleLiquidation.collSurplus);
            }

            emit PositionLiquidated(_borrower, singleLiquidation.entirePositionDebt, singleLiquidation.collToSendToBP, uint8(PositionManagerOperation.liquidateInRecoveryMode));
            emit PositionUpdated(_borrower, 0, 0, 0, uint8(PositionManagerOperation.liquidateInRecoveryMode));

        } else { // if (_ICR >= MCR && ( _ICR >= _TCR || singleLiquidation.entirePositionDebt > _stablesInBackstopPool))
            LiquidationValues memory zeroVals;
            return zeroVals;
        }

        return singleLiquidation;
    }

    // --- Inner single liquidation functions ---

    /**
     * @dev Liquidates a single position in Normal Mode.
     * @param _activePool The active pool contract.
     * @param _defaultPool The default pool contract.
     * @param _borrower The address of the position's owner.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @return singleLiquidation The liquidation values for the position.
     */
    function _liquidateNormalMode(IActivePool _activePool, IDefaultPool _defaultPool, address _borrower, uint _stablesInBackstopPool)
    internal
    returns (LiquidationValues memory singleLiquidation)
    {
        LocalVariables_InnerSingleLiquidateFunction memory vars;

        (singleLiquidation.entirePositionDebt, singleLiquidation.entirePositionColl, vars.pendingDebtReward, vars.pendingCollReward) =
        _getEntireDebtAndColl(_borrower);

        _movePendingPositionRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
        _removeStake(_borrower);

        singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entirePositionColl);
        singleLiquidation.gasCompensation = GAS_COMPENSATION;
        uint collToLiquidate = singleLiquidation.entirePositionColl - singleLiquidation.collGasCompensation;

        (singleLiquidation.debtToOffset, singleLiquidation.collToSendToBP, singleLiquidation.debtToRedistribute, singleLiquidation.collToRedistribute) =
        _getOffsetAndRedistributionVals(singleLiquidation.entirePositionDebt, collToLiquidate, _stablesInBackstopPool);

        _closePosition(_borrower, Status.closedByLiquidation);
        emit PositionLiquidated(_borrower, singleLiquidation.entirePositionDebt, singleLiquidation.entirePositionColl, uint8(PositionManagerOperation.liquidateInNormalMode));
        emit PositionUpdated(_borrower, 0, 0, 0, uint8(PositionManagerOperation.liquidateInNormalMode));
        return singleLiquidation;
    }

    /**
     * @dev Calculates the values for offsetting and redistributing debt and collateral in a full liquidation.
     * @param _debt The total debt of the position.
     * @param _coll The total collateral of the position.
     * @param _stablesInBackstopPool The amount of stables in the backstop pool.
     * @return debtToOffset Amount of debt to be offset.
     * @return collToSendToBP Amount of collateral to be sent to the Backstop Pool.
     * @return debtToRedistribute Amount of debt to be redistributed.
     * @return collToRedistribute Amount of collateral to be redistributed.
     */
    function _getOffsetAndRedistributionVals
    (
        uint _debt,
        uint _coll,
        uint _stablesInBackstopPool
    )
    internal
    pure
    returns (uint debtToOffset, uint collToSendToBP, uint debtToRedistribute, uint collToRedistribute)
    {
        if (_stablesInBackstopPool > 0) {
            /*
            * Offset as much debt & collateral as possible against the Backstop Pool, and redistribute the remainder
            * between all active Positions.
            *
            *  If the position's debt is larger than the deposited stables in the Backstop Pool:
            *
            *  - Offset an amount of the position's debt equal to the stables in the Backstop Pool
            *  - Send a fraction of the position's collateral to the Backstop Pool, equal to the fraction of its offset debt
            *
            */
            debtToOffset = StableMath._min(_debt, _stablesInBackstopPool);
            collToSendToBP = (_coll * debtToOffset) / _debt;
            debtToRedistribute = _debt - debtToOffset;
            collToRedistribute = _coll - collToSendToBP;
        } else {
            debtToOffset = 0;
            collToSendToBP = 0;
            debtToRedistribute = _debt;
            collToRedistribute = _coll;
        }
    }

    /**
     * @dev Calculates the capped offset values for a position in Recovery Mode.
     * @param _entirePositionDebt The total debt of the position.
     * @param _entirePositionColl The total collateral of the position.
     * @param _price The current price of the collateral.
     * @param MCR The Minimum Collateralization Ratio.
     * @param gasComp The gas compensation amount.
     * @return singleLiquidation The liquidation values for the position.
     */
    function _getCappedOffsetVals
    (
        uint _entirePositionDebt,
        uint _entirePositionColl,
        uint _price,
        uint MCR,
        uint gasComp
    )
    internal
    pure
    returns (LiquidationValues memory singleLiquidation)
    {
        singleLiquidation.entirePositionDebt = _entirePositionDebt;
        singleLiquidation.entirePositionColl = _entirePositionColl;
        uint cappedCollPortion = (_entirePositionDebt * MCR) / _price;

        singleLiquidation.collGasCompensation = _getCollGasCompensation(cappedCollPortion);
        singleLiquidation.gasCompensation = gasComp;

        singleLiquidation.debtToOffset = _entirePositionDebt;
        singleLiquidation.collToSendToBP = cappedCollPortion - singleLiquidation.collGasCompensation;
        singleLiquidation.collSurplus = _entirePositionColl - cappedCollPortion;
        singleLiquidation.debtToRedistribute = 0;
        singleLiquidation.collToRedistribute = 0;
    }

    /**
     * @dev Updates system snapshots of total stakes and total collateral, excluding a given collateral remainder.
     * @param _activePool The active pool contract.
     * @param _collRemainder The amount of collateral to exclude from the snapshot.
     */
    function _updateSystemSnapshots_excludeCollRemainder(IActivePool _activePool, uint _collRemainder) internal {
        totalStakesSnapshot = totalStakes;
        uint activeColl = _activePool.getCollateral();
        uint liquidatedColl = defaultPool.getCollateral();
        totalCollateralSnapshot = (activeColl - _collRemainder) + liquidatedColl;
    }

    /**
     * @dev Redistributes debt and collateral from a liquidated position to all active positions.
     * @param _activePool The active pool contract.
     * @param _defaultPool The default pool contract.
     * @param _debt The amount of debt to redistribute.
     * @param _coll The amount of collateral to redistribute.
     */
    function _redistributeDebtAndColl(IActivePool _activePool, IDefaultPool _defaultPool, uint _debt, uint _coll) internal {
        if (_debt == 0) {return;}

        /*
        * Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a "feedback"
        * error correction, to keep the cumulative error low in the running totals L_Collateral and L_StableDebt:
        *
        * 1) Form numerators which compensate for the floor division errors that occurred the last time this
        * function was called.
        * 2) Calculate "per-unit-staked" ratios.
        * 3) Multiply each ratio back by its denominator, to reveal the current floor division error.
        * 4) Store these errors for use in the next correction when this function is called.
        * 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended.
        */
        uint CollateralNumerator = (_coll * DECIMAL_PRECISION) + lastCollateralError_Redistribution;
        uint stableDebtNumerator = (_debt * DECIMAL_PRECISION) + lastStableDebtError_Redistribution;

        // Get the per-unit-staked terms
        uint CollateralRewardPerUnitStaked = CollateralNumerator / totalStakes;
        uint stableDebtRewardPerUnitStaked = stableDebtNumerator / totalStakes;

        lastCollateralError_Redistribution = CollateralNumerator - (CollateralRewardPerUnitStaked * totalStakes);
        lastStableDebtError_Redistribution = stableDebtNumerator - (stableDebtRewardPerUnitStaked * totalStakes);

        // Add per-unit-staked terms to the running totals
        L_Collateral += CollateralRewardPerUnitStaked;
        L_StableDebt += stableDebtRewardPerUnitStaked;

        // Transfer coll and debt from ActivePool to DefaultPool
        _activePool.decreaseStableDebt(_debt);
        _defaultPool.increaseStableDebt(_debt);
        _activePool.sendCollateral(address(_defaultPool), _coll);
        _defaultPool.receiveCollateral(address(collateralToken), _coll);
    }

    /**
     * @dev Sends gas compensation to the liquidator.
     * @param _activePool The active pool contract.
     * @param _liquidator The address of the liquidator.
     * @param _stables The amount of stables for gas compensation.
     * @param _Collateral The amount of collateral for gas compensation.
     */
    function _sendGasCompensation(IActivePool _activePool, address _liquidator, uint _stables, uint _Collateral) internal {
        if (_stables > 0) {
            stableToken.returnFromPool(gasPoolAddress, _liquidator, _stables);
        }

        if (_Collateral > 0) {
            _activePool.sendCollateral(_liquidator, _Collateral);
        }
    }

    /**
     * @dev Checks if the system would be in Recovery Mode given the provided parameters.
     * @param _entireSystemColl The total collateral in the system.
     * @param _entireSystemDebt The total debt in the system.
     * @param _price The current price of the collateral.
     * @param CCR The Critical Collateralization Ratio.
     * @return A boolean indicating whether the system would be in Recovery Mode.
     */
    function _checkPotentialRecoveryMode(
        uint _entireSystemColl,
        uint _entireSystemDebt,
        uint _price,
        uint CCR
    )
    internal
    view
    returns (bool)
    {
        uint TCR = StableMath._computeCR(_entireSystemColl, _entireSystemDebt, _price, collateralToken.decimals());
        return TCR < CCR;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "../../../interfaces/IActivePool.sol";
import "../../../interfaces/IDefaultPool.sol";
import "../../../interfaces/ISortedPositions.sol";
import "../../../common/StableMath.sol";
import "../../../interfaces/ICollateralSurplusPool.sol";
import "../../../interfaces/ICollateralController.sol";
import "../../../common/Base.sol";
import "../../../interfaces/IFeeTokenStaking.sol";
import "../../../interfaces/IStable.sol";

/**
 * @title PositionState
 * @dev Abstract contract that manages the state of positions in the system.
 * It includes data structures and functions for handling liquidations, rewards, and position management.
 */
abstract contract PositionState is Base {
    // Events
    event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _gasCompensation);
    event PositionUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
    event PositionLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
    event PositionIndexMoved(address _borrower, uint _newIndex);
    event StakesUpdated(uint _newTotalStakes);
    event EmergencyDequeueProcessed(address indexed redeemer, uint stableAmount);


    /**
     * @dev Struct to cache contract addresses to save gas
     */
    struct ContractsCache {
        IActivePool activePool;
        IDefaultPool defaultPool;
        IStable stableToken;
        IFeeTokenStaking feeTokenStaking;
        ISortedPositions sortedPositions;
        ICollateralSurplusPool collateralSurplusPool;
    }

    // Variable container structs for liquidations

    /**
     * @dev Struct for variables used in the outer liquidation function
     */
    struct LocalVariables_OuterLiquidationFunction {
        uint price;
        uint stablesInStabPool;
        bool recoveryModeAtStart;
        uint liquidatedDebt;
        uint liquidatedColl;
    }

    /**
     * @dev Struct for tracking liquidation totals
     */
    struct LiquidationTotals {
        uint totalCollInSequence;
        uint totalDebtInSequence;
        uint totalCollGasCompensation;
        uint totalGasCompensation;
        uint totalDebtToOffset;
        uint totalCollToSendToBP;
        uint totalDebtToRedistribute;
        uint totalCollToRedistribute;
        uint totalCollSurplus;
    }

    /**
     * @dev Struct for variables used in the liquidation sequence
     */
    struct LocalVariables_LiquidationSequence {
        uint remainingStablesInStabPool;
        uint i;
        uint ICR;
        address user;
        bool backToNormalMode;
        uint entireSystemDebt;
        uint entireSystemColl;
    }

    /**
     * @dev Struct for storing liquidation values
     */
    struct LiquidationValues {
        uint entirePositionDebt;
        uint entirePositionColl;
        uint collGasCompensation;
        uint gasCompensation;
        uint debtToOffset;
        uint collToSendToBP;
        uint debtToRedistribute;
        uint collToRedistribute;
        uint collSurplus;
    }

    /**
     * @dev Struct for variables used in the inner single liquidate function
     */
    struct LocalVariables_InnerSingleLiquidateFunction {
        uint collToLiquidate;
        uint pendingDebtReward;
        uint pendingCollReward;
    }

    /**
     * @dev Enum representing the status of a position
     */
    enum Status {
        nonExistent,
        active,
        closedByOwner,
        closedByLiquidation,
        closedByRedemption
    }

    /**
     * @dev Struct representing a position
     */
    struct Position {
        uint debt;
        uint coll;
        uint stake;
        Status status;
        uint128 arrayIndex;
    }

    /**
     * @dev Enum representing different operations in the PositionManager
     */
    enum PositionManagerOperation {
        applyPendingRewards,
        liquidateInNormalMode,
        liquidateInRecoveryMode,
        redeemCollateral
    }

    // Contract interfaces
    IStable public stableToken;
    IPriceFeed public priceFeed;
    IActivePool public activePool;
    IDefaultPool public defaultPool;
    IBackstopPool public backstopPool;
    IERC20Metadata public collateralToken;
    ISortedPositions public sortedPositions;
    ICollateralController public collateralController;
    ICollateralSurplusPool public collateralSurplusPool;

    // Mappings and state variables
    mapping (address => RewardSnapshot) public rewardSnapshots;

    /**
     * @dev Struct for storing reward snapshots for a position
     */
    struct RewardSnapshot { uint Collateral; uint stableDebt;}

    address[] public PositionOwners;
    mapping (address => Position) public Positions;
    uint public totalStakes;
    uint public totalStakesSnapshot;

    // Snapshot of the total collateral across the ActivePool and DefaultPool, immediately after the latest liquidation.
    uint public totalCollateralSnapshot;
    uint public L_Collateral;
    uint public L_StableDebt;
    uint public lastCollateralError_Redistribution;
    uint public lastStableDebtError_Redistribution;

    /**
     * @dev Moves pending position rewards from the Default Pool to the Active Pool
     * @param _activePool The Active Pool contract
     * @param _defaultPool The Default Pool contract
     * @param _stables The amount of stables to move
     * @param _Collateral The amount of collateral to move
     */
    function _movePendingPositionRewardsToActivePool(IActivePool _activePool, IDefaultPool _defaultPool, uint _stables, uint _Collateral) internal {
        _defaultPool.decreaseStableDebt(_stables);
        _activePool.increaseStableDebt(_stables);
        _defaultPool.sendCollateralToActivePool(_Collateral);
    }

    /**
     * @dev Removes a borrower's stake from the total stakes
     * @param _borrower The address of the borrower
     */
    function _removeStake(address _borrower) internal {
        uint stake = Positions[_borrower].stake;
        totalStakes = totalStakes - stake;
        emit StakesUpdated(totalStakes);
        Positions[_borrower].stake = 0;
    }

    /**
     * @dev Closes a position
     * @param _borrower The address of the borrower
     * @param closedStatus The new status of the closed position
     */
    function _closePosition(address _borrower, Status closedStatus) internal {
        assert(closedStatus != Status.nonExistent && closedStatus != Status.active);

        uint PositionOwnersArrayLength = PositionOwners.length;
        _requireMoreThanOnePositionInSystem(PositionOwnersArrayLength);

        Positions[_borrower].status = closedStatus;
        Positions[_borrower].coll = 0;
        Positions[_borrower].debt = 0;

        rewardSnapshots[_borrower].Collateral = 0;
        rewardSnapshots[_borrower].stableDebt = 0;

        _removePositionOwner(_borrower, PositionOwnersArrayLength);
        sortedPositions.remove(_borrower);
    }

    /**
     * @dev Requires that there is more than one position in the system
     * @param PositionOwnersArrayLength The length of the PositionOwners array
     */
    function _requireMoreThanOnePositionInSystem(uint PositionOwnersArrayLength) internal view {
        require (PositionOwnersArrayLength > 1 && sortedPositions.getSize() > 1, "Only one position in the system");
    }

    /**
     * @dev Removes a position owner from the PositionOwners array
     * @param _borrower The address of the borrower to remove
     * @param PositionOwnersArrayLength The length of the PositionOwners array
     */
    function _removePositionOwner(address _borrower, uint PositionOwnersArrayLength) internal {
        Status PositionStatus = Positions[_borrower].status;
        assert(PositionStatus != Status.nonExistent && PositionStatus != Status.active);

        uint128 index = Positions[_borrower].arrayIndex;
        uint length = PositionOwnersArrayLength;
        uint idxLast = length - 1;

        assert(index <= idxLast);

        address addressToMove = PositionOwners[idxLast];

        PositionOwners[index] = addressToMove;
        Positions[addressToMove].arrayIndex = index;
        emit PositionIndexMoved(addressToMove, index);

        PositionOwners.pop();
    }

    /**
     * @dev Gets the entire debt and collateral for a borrower
     * @param _borrower The address of the borrower
     * @return debt The total debt of the borrower
     * @return coll The total collateral of the borrower
     * @return pendingStableDebtReward The pending stable debt reward
     * @return pendingCollateralReward The pending collateral reward
     */
    function _getEntireDebtAndColl(address _borrower) internal view
    returns (uint debt, uint coll, uint pendingStableDebtReward, uint pendingCollateralReward) {
        debt = Positions[_borrower].debt;
        coll = Positions[_borrower].coll;

        pendingStableDebtReward = _getPendingStableDebtReward(_borrower);
        pendingCollateralReward = _getPendingCollateralReward(_borrower);

        debt = debt + pendingStableDebtReward;
        coll = coll + pendingCollateralReward;
    }

    /**
     * @dev Calculates the pending collateral reward for a borrower
     * @param _borrower The address of the borrower
     * @return The pending collateral reward
     */
    function _getPendingCollateralReward(address _borrower) internal view returns (uint) {
        uint snapshotCollateral = rewardSnapshots[_borrower].Collateral;
        uint rewardPerUnitStaked = L_Collateral - snapshotCollateral;
        if ( rewardPerUnitStaked == 0 || Positions[_borrower].status != Status.active) {
            return 0;
        }
        uint stake = Positions[_borrower].stake;
        uint pendingCollateralReward = (stake * rewardPerUnitStaked) / DECIMAL_PRECISION;
        return pendingCollateralReward;
    }

    /**
     * @dev Calculates the pending stable debt reward for a borrower
     * @param _borrower The address of the borrower
     * @return The pending stable debt reward
     */
    function _getPendingStableDebtReward(address _borrower) internal view returns (uint) {
        uint snapshotStableDebt = rewardSnapshots[_borrower].stableDebt;
        uint rewardPerUnitStaked = L_StableDebt - snapshotStableDebt;

        if ( rewardPerUnitStaked == 0 || Positions[_borrower].status != Status.active) { return 0; }

        uint stake =  Positions[_borrower].stake;

        uint pendingStableDebtReward = (stake * rewardPerUnitStaked) / DECIMAL_PRECISION;

        return pendingStableDebtReward;
    }

    /**
     * @dev Calculates the current Individual Collateralization Ratio (ICR) for a borrower
     * @param _borrower The address of the borrower
     * @param _price The current price of the collateral
     * @return The current ICR
     */
    function _getCurrentICR(address _borrower, uint _price) internal view returns (uint) {
        (uint currentCollateral, uint currentStableDebt) = _getCurrentPositionAmounts(_borrower);

        uint ICR = StableMath._computeCR(currentCollateral, currentStableDebt, _price, collateralToken.decimals());
        return ICR;
    }

    /**
     * @dev Gets the current position amounts for a borrower
     * @param _borrower The address of the borrower
     * @return currentCollateral The current collateral amount
     * @return currentStableDebt The current stable debt amount
     */
    function _getCurrentPositionAmounts(address _borrower) internal view returns (uint, uint) {
        uint pendingCollateralReward = _getPendingCollateralReward(_borrower);
        uint pendingStableDebtReward = _getPendingStableDebtReward(_borrower);
        uint currentCollateral = Positions[_borrower].coll + pendingCollateralReward;
        uint currentStableDebt = Positions[_borrower].debt + pendingStableDebtReward;
        return (currentCollateral, currentStableDebt);
    }

    /**
     * @dev Gets the entire debt in the system
     * @return total The total debt in the system
     */
    function _getEntireDebt() internal view returns (uint total) {
        total = activePool.getStableDebt() + defaultPool.getStableDebt();
    }

    /**
     * @dev Gets the entire collateral in the system
     * @return total The total collateral in the system
     */
    function _getEntireCollateral() internal view returns (uint total) {
        total = activePool.getCollateral() + defaultPool.getCollateral();
    }

    /**
     * @dev Checks if the system is in recovery mode
     * @param _price The current price of the collateral
     * @return A boolean indicating if the system is in recovery mode
     */
    function _checkRecoveryMode(uint _price) internal view returns (bool) {
        uint CCR = collateralController.getCCR(address(collateralToken), collateralController.getVersion(address(this)));
        return _getTCR(_price) < CCR;
    }

    /**
     * @dev Calculates the Total Collateralization Ratio (TCR)
     * @param _price The current price of the collateral
     * @return TCR The Total Collateralization Ratio
     */
    function _getTCR(uint _price) internal view returns (uint TCR) {
        uint entirePositionColl = _getEntireCollateral();
        uint entirePositionDebt = _getEntireDebt();
        TCR = StableMath._computeCR(entirePositionColl, entirePositionDebt, _price, collateralToken.decimals());
    }
}

pragma solidity 0.8.21;

import "@openzeppelin/contracts/access/AccessControl.sol";

/**
 * @title PermissionedRedeemerAbstract
 * @dev Abstract contract implementing a role-based permission system for redemptions.
 *
 * This contract enables a whitelist mechanism for redemptions, where redemptions
 * can be restricted to only whitelisted addresses. The whitelist becomes active
 * as soon as at least one address has been granted the REDEEMER_ROLE.
 *
 * Key features:
 * - Maintains a count of whitelisted redeemers
 * - Automatically activates restrictions when first redeemer is added
 * - Automatically deactivates restrictions when last redeemer is removed
 */
abstract contract PermissionedRedeemerAbstract is AccessControl {
    /// @dev Role identifier for redeemers. Addresses with this role can perform redemptions when restrictions are active.
    bytes32 public constant REDEEMER_ROLE = keccak256("REDEEMER_ROLE");

    /// @dev Counter tracking the number of addresses with REDEEMER_ROLE. Used to determine if whitelist is active.
    uint public countWhitelistedRedeemers;

    /**
     * @dev Constructor that grants the contract deployer the default admin role.
     * The admin can then grant and revoke the REDEEMER_ROLE to other addresses.
     */
    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    /**
     * @dev Overrides the OpenZeppelin grantRole to track the number of redeemers.
     * Increments the redeemer counter when a new address is granted the REDEEMER_ROLE.
     * @param role The role being granted
     * @param account The address receiving the role
     */
    function grantRole(bytes32 role, address account) public override {
        if (!hasRole(role, account) && role == REDEEMER_ROLE) {
            countWhitelistedRedeemers++;
        }

        super.grantRole(role, account);
    }

    /**
     * @dev Overrides the OpenZeppelin revokeRole to track the number of redeemers.
     * Decrements the redeemer counter when the REDEEMER_ROLE is revoked from an address.
     * @param role The role being revoked
     * @param account The address losing the role
     */
    function revokeRole(bytes32 role, address account) public override {
        if (hasRole(role, account) && role == REDEEMER_ROLE) {
            countWhitelistedRedeemers--;
        }

        super.revokeRole(role, account);
    }

    /**
     * @dev Overrides the OpenZeppelin renounceRole to track the number of redeemers.
     * Decrements the redeemer counter when an address renounces their REDEEMER_ROLE.
     * @param role The role being renounced
     * @param account The address renouncing the role
     */
    function renounceRole(bytes32 role, address account) public override {
        if (hasRole(role, account) && role == REDEEMER_ROLE) {
            countWhitelistedRedeemers--;
        }

        super.renounceRole(role, account);
    }

    /**
     * @dev Checks if redemptions are currently restricted to whitelisted addresses.
     * Restrictions are active if there is at least one address with REDEEMER_ROLE.
     * @return bool True if redemptions are restricted to whitelisted addresses, false if open to all
     */
    function isRedemptionRestricted() public view returns (bool) {
        return countWhitelistedRedeemers > 0;
    }

    /**
     * @dev Determines if a specific address has permission to perform redemptions.
     * Permission is granted either when no restrictions are active, or when the
     * address has been granted the REDEEMER_ROLE.
     * @param _redeemer Address to check for redemption permissions
     * @return bool True if the address can perform redemptions, false otherwise
     */
    function canRedeem(address _redeemer) public view returns (bool) {
        return !isRedemptionRestricted() || hasRole(REDEEMER_ROLE, _redeemer);
    }

    /**
     * @dev Checks if redemption whitelist is active and the caller lacks the REDEEMER_ROLE.
     * @param user Address to check (currently unused - checks msg.sender instead)
     * @return bool True if whitelist is active and caller lacks REDEEMER_ROLE
     * @notice The user parameter is currently not used - function checks msg.sender instead
     */
    function redemptionWhitelistOnAndUserWithoutRole(address user) public view returns (bool) {
        return isRedemptionRestricted() && !hasRole(REDEEMER_ROLE, msg.sender);
    }
}

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

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_collateralAsset","type":"address"},{"internalType":"address","name":"_positionControllerAddress","type":"address"},{"internalType":"address","name":"_activePoolAddress","type":"address"},{"internalType":"address","name":"_defaultPoolAddress","type":"address"},{"internalType":"address","name":"_backstopPoolAddress","type":"address"},{"internalType":"address","name":"_gasPoolAddress","type":"address"},{"internalType":"address","name":"_collSurplusPoolAddress","type":"address"},{"internalType":"address","name":"_priceFeedAddress","type":"address"},{"internalType":"address","name":"_stableTokenAddress","type":"address"},{"internalType":"address","name":"_sortedPositionsAddress","type":"address"},{"internalType":"address","name":"_feeTokenStakingAddress","type":"address"},{"internalType":"address","name":"_collateralController","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"newBaseRate","type":"uint256"}],"name":"BaseRateUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"redeemer","type":"address"},{"indexed":false,"internalType":"uint256","name":"stableAmount","type":"uint256"}],"name":"EmergencyDequeueProcessed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_L_Collateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_L_STABLE","type":"uint256"}],"name":"LTermsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"lastFeeOpTime","type":"uint256"}],"name":"LastFeeOpTimeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_liquidatedDebt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_liquidatedColl","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_collGasCompensation","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_gasCompensation","type":"uint256"}],"name":"Liquidation","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"_newIndex","type":"uint256"}],"name":"PositionIndexMoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"_newIndex","type":"uint256"}],"name":"PositionIndexUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"_debt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_coll","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"operation","type":"uint8"}],"name":"PositionLiquidated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_L_Collateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_L_STABLEDebt","type":"uint256"}],"name":"PositionSnapshotsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"_debt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_coll","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"stake","type":"uint256"},{"indexed":false,"internalType":"uint8","name":"operation","type":"uint8"}],"name":"PositionUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_attemptedStableAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_actualStableAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_CollateralSent","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_CollateralFee","type":"uint256"}],"name":"Redemption","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_newTotalStakes","type":"uint256"}],"name":"StakesUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_totalStakesSnapshot","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_totalCollateralSnapshot","type":"uint256"}],"name":"SystemSnapshotsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_newTotalStakes","type":"uint256"}],"name":"TotalStakesUpdated","type":"event"},{"inputs":[],"name":"CCR","outputs":[{"internalType":"uint256","name":"_CCR","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DECIMAL_PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DYNAMIC_BORROWING_FEE_FLOOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DYNAMIC_REDEMPTION_FEE_FLOOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GAS_COMPENSATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"L_Collateral","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"L_StableDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MCR","outputs":[{"internalType":"uint256","name":"_MCR","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_NET_DEBT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"PositionOwners","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"Positions","outputs":[{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"coll","type":"uint256"},{"internalType":"uint256","name":"stake","type":"uint256"},{"internalType":"enum PositionState.Status","name":"status","type":"uint8"},{"internalType":"uint128","name":"arrayIndex","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REDEEMER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_100pct","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_baseRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_lastFeeOperationTime","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":"address","name":"_borrower","type":"address"}],"name":"addPositionOwnerToArray","outputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"applyPendingRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"backstopPool","outputs":[{"internalType":"contract IBackstopPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_positionArray","type":"address[]"}],"name":"batchLiquidatePositions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_redeemer","type":"address"}],"name":"canRedeem","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_price","type":"uint256"}],"name":"checkRecoveryMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"closePosition","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collateralController","outputs":[{"internalType":"contract ICollateralController","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralSurplusPool","outputs":[{"internalType":"contract ICollateralSurplusPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"contract IERC20Metadata","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"countWhitelistedRedeemers","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decayBaseRateFromBorrowing","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_collDecrease","type":"uint256"}],"name":"decreasePositionColl","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_debtDecrease","type":"uint256"}],"name":"decreasePositionDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"defaultPool","outputs":[{"internalType":"contract IDefaultPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"emergencyDequeue","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"escrowedRedemptions","outputs":[{"internalType":"uint256","name":"stableAmount","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"uint256","name":"utilizationPCT","type":"uint256"},{"internalType":"uint256","name":"loadIncrease","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeTokenStaking","outputs":[{"internalType":"contract IFeeTokenStaking","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_stableDebt","type":"uint256"},{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getBorrowingFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_stableDebt","type":"uint256"},{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getBorrowingFeeWithDecay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getBorrowingRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getBorrowingRateWithDecay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_price","type":"uint256"}],"name":"getCurrentICR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEntireCollateral","outputs":[{"internalType":"uint256","name":"total","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEntireDebt","outputs":[{"internalType":"uint256","name":"total","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getEntireDebtAndColl","outputs":[{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"coll","type":"uint256"},{"internalType":"uint256","name":"pendingStableDebtReward","type":"uint256"},{"internalType":"uint256","name":"pendingCollateralReward","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getNominalICR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getPendingCollateralReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getPendingStableDebtReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getPositionColl","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getPositionDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_index","type":"uint256"}],"name":"getPositionFromPositionOwnersArray","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPositionOwnersCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getPositionStake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"getPositionStatus","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_CollateralDrawn","type":"uint256"},{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getRedemptionFeeWithDecay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getRedemptionRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"suggestedAdditiveFeePCT","type":"uint256"}],"name":"getRedemptionRateWithDecay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_price","type":"uint256"}],"name":"getTCR","outputs":[{"internalType":"uint256","name":"TCR","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"redeemer","type":"address"}],"name":"hasEnqueuedEscrow","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"hasPendingRewards","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_collIncrease","type":"uint256"}],"name":"increasePositionColl","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_debtIncrease","type":"uint256"}],"name":"increasePositionDebt","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isRedemptionRestricted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isSunset","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastCollateralError_Redistribution","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastFeeOperationTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastStableDebtError_Redistribution","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"liquidate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_n","type":"uint256"}],"name":"liquidatePositions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"liquidationManagerAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceFeed","outputs":[{"internalType":"contract IPriceFeed","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_stableAmount","type":"uint256"}],"name":"queueRedemption","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_stableAmount","type":"uint256"},{"internalType":"address","name":"_firstRedemptionHint","type":"address"},{"internalType":"address","name":"_upperPartialRedemptionHint","type":"address"},{"internalType":"address","name":"_lowerPartialRedemptionHint","type":"address"},{"internalType":"uint256","name":"_partialRedemptionHintNICR","type":"uint256"},{"internalType":"uint256","name":"_maxIterations","type":"uint256"},{"internalType":"uint256","name":"_maxFeePercentage","type":"uint256"}],"name":"redeemCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"redemptionWhitelistOnAndUserWithoutRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"removeStake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewardSnapshots","outputs":[{"internalType":"uint256","name":"Collateral","type":"uint256"},{"internalType":"uint256","name":"stableDebt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_num","type":"uint256"}],"name":"setPositionStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sortedPositions","outputs":[{"internalType":"contract ISortedPositions","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stableToken","outputs":[{"internalType":"contract IStable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalCollateralSnapshot","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalStakes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalStakesSnapshot","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"updatePositionRewardSnapshots","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_borrower","type":"address"}],"name":"updateStakeAndTotalStakes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}]

0x60806040523480156200001157600080fd5b50604051620097223803806200972283398101604081905262000034916200021a565b620000416000336200014a565b600980546001600160a01b03199081166001600160a01b03848116919091179092556000805482168e84161790556007805482168f84161790556004805482168d84161790556005805482168c84161790556006805482168b84161790556001805482168a8416179055600a8054821689841617905560038054821688841617905560028054821687841617905560088054821686841617905560198054909116918416919091179055604051620000f990620001ef565b604051809103906000f08015801562000116573d6000803e3d6000fd5b50601a80546001600160a01b0319166001600160a01b0392909216919091179055506200030f9a5050505050505050505050565b60008281526017602090815260408083206001600160a01b038516845290915290205460ff16620001eb5760008281526017602090815260408083206001600160a01b03851684529091529020805460ff19166001179055620001aa3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45b5050565b61353a80620061e883390190565b80516001600160a01b03811681146200021557600080fd5b919050565b6000806000806000806000806000806000806101808d8f0312156200023e57600080fd5b620002498d620001fd565b9b506200025960208e01620001fd565b9a506200026960408e01620001fd565b99506200027960608e01620001fd565b98506200028960808e01620001fd565b97506200029960a08e01620001fd565b9650620002a960c08e01620001fd565b9550620002b960e08e01620001fd565b9450620002ca6101008e01620001fd565b9350620002db6101208e01620001fd565b9250620002ec6101408e01620001fd565b9150620002fd6101608e01620001fd565b90509295989b509295989b509295989b565b615ec9806200031f6000396000f3fe608060405234801561001057600080fd5b50600436106103f35760003560e01c806301ffc9a7146103f857806305618592146104205780630b076557146104375780630e55d5151461044c578063139f2e8c1461045f578063151535b91461046f5780631673c79a1461048257806318f2817a146104be5780631983fb40146104d15780631bf43555146104e45780631f68f20a146104f45780631faa3a65146104fc578063207ace811461050f578063248a9ca314610522578063257aa696146105355780632f2ff15d1461053d5780632f865568146105505780632f86e2dd14610563578063340c07801461057657806336568abe146105895780633cc742251461059c5780633cf1b05b146105bc578063432ddab9146105c45780634840fb37146105cd5780634a3c95c4146105d65780634ab77ab0146105e95780634e443d9e1461062e57806350b29ca514610641578063516eda3d1461064957806354e89adc146106725780635733d58f1461068557806358b8a5d61461068d578063598f54c9146106a05780635dba4c4a146106a85780635f94c327146106b057806369076788146106c35780636a593018146106d657806372fe25aa146106e9578063741bef1a146106f8578063758ab4001461070b57806375d54cb114610737578063794e57241461074a5780637e5b4c6d146107525780637f7dde4a146107655780637fa46ab414610778578063807d138d1461078d5780638200bfe6146107965780638697d4da146107a957806390b8b0c8146107bc57806391571384146107c457806391d14854146107d7578063927b26b9146107ea578063948ba6d2146107f357806396d711ff1461080657806396e620651461080f5780639eef064014610822578063a20baee6146106e9578063a217fddf14610835578063a22b7d681461083d578063a9d75b2b14610850578063acbb08e614610863578063accea38414610876578063ae3726ed14610889578063b0d8e18114610891578063b2016bd4146108a4578063b279906e146108b7578063b36cd07f146108ca578063b82f263d146108dd578063b91af97c146108f0578063bcd3752614610903578063bf88dd7114610916578063bf9befb11461096f578063c045e47d14610978578063c36069cc14610889578063c98eef621461098b578063c9fccede146109b7578063cb5f6240146109ca578063d293c710146109dd578063d347e07b146109f0578063d380a37c146109f9578063d38b055814610a01578063d547741f14610a0a578063d98d91d014610a1d578063e13d277114610a30578063e2ac77b014610a43578063ee266b8714610a56578063f05c7d8914610a5f578063fbf60d4a14610a72578063fe2ba84814610a7c575b600080fd5b61040b61040636600461543a565b610a8f565b60405190151581526020015b60405180910390f35b61042960185481565b604051908152602001610417565b61044a610445366004615479565b610ac6565b005b61044a61045a366004615479565b610aee565b610429680ad78ebc5ac620000081565b61040b61047d366004615479565b610aff565b6104a9610490366004615479565b600b602052600090815260409020805460019091015482565b60408051928352602083019190915201610417565b6104296104cc366004615479565b610b2b565b6104296104df366004615479565b610b3e565b610429686194049f30f720000081565b610429610b6e565b61040b61050a366004615479565b610c88565b61040b61051d366004615479565b610ca8565b610429610530366004615496565b610cdb565b610429610cf0565b61044a61054b3660046154af565b610cff565b61044a61055e366004615479565b610d4c565b61044a610571366004615479565b610db4565b61044a610584366004615496565b610dc7565b61044a6105973660046154af565b610e30565b6005546105af906001600160a01b031681565b60405161041791906154df565b600c54610429565b61042960165481565b61042960145481565b6104296105e4366004615479565b610e78565b61061e6105f7366004615479565b601b6020526000908152604090208054600182015460028301546003909301549192909184565b60405161041794939291906154f3565b61040b61063c366004615496565b610e83565b610429610e8e565b610429610657366004615479565b6001600160a01b03166000908152600d602052604090205490565b610429610680366004615479565b610e98565b610429610ea3565b61042961069b366004615496565b610f83565b61044a6110a0565b61044a6113f8565b6104296106be36600461550e565b6114fc565b6009546105af906001600160a01b031681565b6104296106e4366004615530565b611510565b610429670de0b6b3a764000081565b6003546105af906001600160a01b031681565b610429610719366004615479565b6001600160a01b03166000908152600d602052604090206001015490565b601a546105af906001600160a01b031681565b610429611568565b610429610760366004615530565b6115a9565b6004546105af906001600160a01b031681565b610429600080516020615dff83398151915281565b610429600f5481565b6006546105af906001600160a01b031681565b6019546105af906001600160a01b031681565b61040b6115fb565b6104296107d236600461550e565b611676565b61040b6107e53660046154af565b611684565b61042960155481565b610429610801366004615496565b6116af565b61042960105481565b61044a61081d366004615530565b6116c2565b61044a610830366004615496565b61171a565b610429600081565b61042961084b366004615496565b611a7e565b6002546105af906001600160a01b031681565b600a546105af906001600160a01b031681565b610429610884366004615479565b611a91565b610429611ab3565b61042961089f366004615479565b611ad5565b6007546105af906001600160a01b031681565b6105af6108c5366004615496565b611b73565b6104296108d8366004615496565b611ba3565b6104296108eb366004615496565b611cb9565b61061e6108fe366004615479565b611cc4565b61044a61091136600461555c565b611ce2565b61095e610924366004615479565b600d6020526000908152604090208054600182015460028301546003909301549192909160ff81169061010090046001600160801b031685565b6040516104179594939291906155e0565b610429600e5481565b6008546105af906001600160a01b031681565b610429610999366004615479565b6001600160a01b03166000908152600d602052604090206002015490565b6104296109c536600461550e565b6126b1565b6105af6109d8366004615496565b6126c5565b6104296109eb366004615530565b6126ef565b61042960125481565b6104296126fb565b61042960135481565b61044a610a183660046154af565b6127eb565b61044a610a2b3660046156a3565b612833565b610429610a3e366004615530565b6128fd565b61040b610a51366004615479565b61292b565b61042960115481565b610429610a6d366004615530565b61298e565b601854151561040b565b61044a610a8a366004615479565b6129bf565b60006001600160e01b03198216637965db0b60e01b1480610ac057506301ffc9a760e01b6001600160e01b03198316145b92915050565b610ace6129d0565b600454600554610aeb916001600160a01b03908116911683612a38565b50565b610af66129d0565b610aeb81612b40565b6000610b0c601854151590565b1580610ac05750610ac0600080516020615dff83398151915283611684565b6000610b356129d0565b610ac082612b6a565b6001600160a01b0381166000908152600d602052604081206003015460ff166004811115610ac057610ac06155ca565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bc4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be89190615754565b90506000816001811115610bfe57610bfe6155ca565b03610c8057600960009054906101000a90046001600160a01b03166001600160a01b031663b655d0c46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c56573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c7a9190615775565b91505090565b505060155490565b6001600160a01b03166000908152601b6020526040902060010154151590565b6000610cb5601854151590565b8015610ac05750610cd4600080516020615dff83398151915233611684565b1592915050565b60009081526017602052604090206001015490565b6000610cfa612bfd565b905090565b610d098282611684565b158015610d235750600080516020615dff83398151915282145b15610d3e5760188054906000610d38836157a4565b91905055505b610d488282612ce0565b5050565b610d5581612cfc565b604080516001808252818301909252600091602080830190803683370190505090508181600081518110610d8b57610d8b6157bd565b60200260200101906001600160a01b031690816001600160a01b031681525050610d4881612833565b610dbc6129d0565b610aeb816002612d87565b610d4881604051602401610ddd91815260200190565b60408051601f19818403018152918152602080830180516001600160e01b03166268180f60e71b179052815160608101909252602880835290615e4c90830139601a546001600160a01b03169190612eab565b610e3a8282611684565b8015610e535750600080516020615dff83398151915282145b15610e6e5760188054906000610e68836157d3565b91905055505b610d488282612f23565b6000610ac082612f9d565b6000610ac08261304e565b6000610cfa613145565b6000610ac0826131f8565b60095460075460405163c3f82bc360e01b81526000926001600160a01b039081169263e0bbb60b92911690839063c3f82bc390610ee49030906004016154df565b602060405180830381865afa158015610f01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f259190615800565b6040518363ffffffff1660e01b8152600401610f4292919061581b565b602060405180830381865afa158015610f5f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cfa9190615775565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610fd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffd9190615754565b90506000816001811115611013576110136155ca565b036110945760095460408051632d95743160e21b8152905161108d926001600160a01b03169163b655d0c49160048083019260209291908290030181865afa158015611063573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110879190615775565b84613224565b9392505050565b61108d60155484613224565b600354604051636785806360e11b81526000916001600160a01b03169063cf0b00c6906110d7908490819081908190600401615837565b60408051808303816000875af11580156110f5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111199190615856565b5060095460075460405163c3f82bc360e01b81529293506000926001600160a01b039283169263368bceed921690839063c3f82bc39061115d9030906004016154df565b602060405180830381865afa15801561117a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119e9190615800565b6040518363ffffffff1660e01b81526004016111bb92919061581b565b602060405180830381865afa1580156111d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111fc9190615775565b905080611208836132a1565b1080611218575061121833610ca8565b61127c5760405162461bcd60e51b815260206004820152602a60248201527f544352206d7573742062652062656c6f77204d435220746f20656d657267656e6044820152696379206465717565756560b01b60648201526084015b60405180910390fd5b336000908152601b6020526040812060018101549091036112d65760405162461bcd60e51b8152602060048201526014602482015273139bc81c9959195b5c1d1a5bdb881c5d595d595960621b6044820152606401611273565b805460025460405163a9059cbb60e01b81526001600160a01b039091169063a9059cbb9061130a903390859060040161587a565b6020604051808303816000875af1158015611329573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061134d91906158a3565b6113925760405162461bcd60e51b815260206004820152601660248201527514dd18589b19481d1c985b9cd9995c8819985a5b195960521b6044820152606401611273565b336000818152601b6020526040808220828155600181018390556002810183905560030191909155517f7a5dd2b1e375db96da69d227292334441da925766453994078862d5cad386b24906113ea9084815260200190565b60405180910390a250505050565b6114006129d0565b60095460408051630f5114eb60e01b815290516000926001600160a01b031691630f5114eb9160048083019260209291908290030181865afa15801561144a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146e9190615754565b90506000816001811115611484576114846155ca565b036114f457600960009054906101000a90046001600160a01b03166001600160a01b0316635dba4c4a6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156114d957600080fd5b505af11580156114ed573d6000803e3d6000fd5b5050505050565b610aeb613344565b600061108d61150a836116af565b84613396565b600061151a6129d0565b6001600160a01b0383166000908152600d60205260408120600101546115419084906158be565b6001600160a01b0385166000908152600d6020526040902060010181905591505092915050565b60095460075460405163c3f82bc360e01b81526000926001600160a01b039081169263368bceed92911690839063c3f82bc390610ee49030906004016154df565b60006115b36129d0565b6001600160a01b0383166000908152600d60205260408120546115d79084906158be565b6001600160a01b0385166000908152600d6020526040902081905591505092915050565b600954600754604051631a36c27160e11b81523060048201526001600160a01b039182166024820152600092919091169063346d84e290604401602060405180830381865afa158015611652573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cfa91906158a3565b600061108d61150a83611ba3565b60009182526017602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6000610ac06116bc6133b5565b836134a5565b6116ca6129d0565b8060048111156116dc576116dc6155ca565b6001600160a01b0383166000908152600d60205260409020600301805460ff19166001836004811115611711576117116155ca565b02179055505050565b61172333610aff565b61173f5760405162461bcd60e51b8152600401611273906158d1565b6000811161175f5760405162461bcd60e51b81526004016112739061591b565b60095460405163c3f82bc360e01b81526000916001600160a01b03169063c3f82bc3906117909030906004016154df565b602060405180830381865afa1580156117ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d19190615800565b600954600754604051636975d4f160e11b81529293506001600160a01b039182169263d2eba9e292611809921690859060040161581b565b61012060405180830381865afa158015611827573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061184b919061595b565b50336000908152601b602052604090206001810154156118a95760405162461bcd60e51b8152602060048201526019602482015278149959195b5c1d1a5bdb88185b1c9958591e481c5d595d5959603a1b6044820152606401611273565b6009546007546040516307eb2c2560e41b81526000926001600160a01b0390811692637eb2c250926118e39290911690879060040161581b565b6060604051808303816000875af1158015611902573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119269190615a11565b505090506000811161198e5760405162461bcd60e51b815260206004820152602b60248201527f436f6f6c646f776e20726571756972656d656e74206d7573742062652067726560448201526a061746572207468616e20360ac1b6064820152608401611273565b600254604051630e0960cd60e31b81526001600160a01b039091169063704b0668906119c290339030908990600401615a3f565b600060405180830381600087803b1580156119dc57600080fd5b505af11580156119f0573d6000803e3d6000fd5b5050508483555042600183015560095460405163615c98e160e11b8152600481018690526001600160a01b039091169063c2b931c29060240160408051808303816000875af1158015611a47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a6b9190615856565b6003840155600290920191909155505050565b6000610ac0611a8b6133b5565b83613224565b6000611a9b6129d0565b611aa4826134e1565b6001600160801b031692915050565b611ac76103e8670de0b6b3a7640000615a79565b611ad2906005615a8d565b81565b6000806000611ae38461357a565b915091506000611b6a8383600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b41573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b659190615800565b6135f6565b95945050505050565b6000600c8281548110611b8857611b886157bd565b6000918252602090912001546001600160a01b031692915050565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bf9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1d9190615754565b90506000816001811115611c3357611c336155ca565b03611cad5760095460408051632d95743160e21b8152905161108d926001600160a01b03169163b655d0c49160048083019260209291908290030181865afa158015611c83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca79190615775565b846134a5565b61108d601554846134a5565b6000610ac0826132a1565b600080600080611cd385613638565b93509350935093509193509193565b611ceb33610aff565b611d075760405162461bcd60e51b8152600401611273906158d1565b611d0f61534e565b6040805160c081018252600480546001600160a01b039081168352600554811660208401526002548116838501526019548116606084015260085481166080840152600a54811660a0840152600954935163c3f82bc360e01b81529293169163c3f82bc391611d80913091016154df565b602060405180830381865afa158015611d9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dc19190615800565b60ff16610220830181905261014083018490526009546007546040516307eb2c2560e41b81526001600160a01b0392831693637eb2c25093611e0793169160040161581b565b6060604051808303816000875af1158015611e26573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e4a9190615a11565b610240850181905261020085018290526101e08501839052611e6f9284928d92613690565b1580156101c08701526101208601919091526101008501919091526101a0840191909152611e9e5750506126a8565b611eac826101a00151613794565b600354610120830151610100840151604051636785806360e11b81526001600160a01b039093169263cf0b00c692611eed9290916001908190600401615837565b60408051808303816000875af1158015611f0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f2f9190615856565b610160840181905260c0840191909152610140830151611f4e916137b4565b60095460075461022084015160405163368bceed60e01b81526000936001600160a01b039081169363368bceed93611f8d93929091169160040161581b565b602060405180830381865afa158015611faa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fce9190615775565b9050611fde8360c001518261395a565b600260009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612031573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120559190615775565b60e0840181905260408084015190516370a0823160e01b81526001600160a01b03909116906370a082319061208e9033906004016154df565b602060405180830381865afa1580156120ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120cf9190615775565b11156120dd576120dd615aa4565b6101a08301518352608082015160c08401516000916120fe918c90856139b1565b1561210a575088612214565b82608001516001600160a01b0316634d6228316040518163ffffffff1660e01b8152600401602060405180830381865afa15801561214c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121709190615aba565b90505b6001600160a01b03811615801590612197575081612195828660c001516126ef565b105b156122145782608001516001600160a01b031663b72703ac826040518263ffffffff1660e01b81526004016121cc91906154df565b602060405180830381865afa1580156121e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061220d9190615aba565b9050612173565b856000036122225760001995505b60016102608501525b6001600160a01b038116158015906122435750835115155b801561224f5750600086115b1561236d578561225e816157d3565b965050600083608001516001600160a01b031663b72703ac836040518263ffffffff1660e01b815260040161229391906154df565b602060405180830381865afa1580156122b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122d49190615aba565b90506122e98460000151856020015184612a38565b6000612308858488600001518960c001518f8f8f8d6102600151613aec565b600061026088015260408101519091501561232457505061236d565b805160208701516123359190615ad7565b60208088019190915281015160408701516123509190615ad7565b60408701528051865161236391906158be565b865250905061222b565b60008460400151116123bf5760405162461bcd60e51b815260206004820152601b60248201527a155b98589b19481d1bc81c995919595b48185b9e48185b5bdd5b9d602a1b6044820152606401611273565b6101e0840151156123d55783516123d590613c05565b6123ec84604001518560c001518660e00151613cd7565b506124008460400151856101600151613dfc565b60608501819052604085015161014086015161241d929190613e0a565b825160608085015190860151604051636250216960e01b81526001600160a01b039093169263625021699261245692909160040161587a565b600060405180830381600087803b15801561247057600080fd5b505af1158015612484573d6000803e3d6000fd5b505050506060838101516007546102208701519287015160405163184cbcb360e11b81526001600160a01b03928316600482015260ff909416602485015260448401521690633099796690606401600060405180830381600087803b1580156124ec57600080fd5b505af1158015612500573d6000803e3d6000fd5b5050506060850151604086015161251792506158be565b60808501526101a08401516020850151604080870151606088015191517f43a3f4082a4dbc33d78e317d2497d3a730bc7fc3574159dcea1056e62e5d9ad8946125649490939092916154f3565b60405180910390a182604001516001600160a01b0316639dc29fac3386602001516040518363ffffffff1660e01b81526004016125a292919061587a565b600060405180830381600087803b1580156125bc57600080fd5b505af11580156125d0573d6000803e3d6000fd5b5050845160208701516040516302038d2560e11b81526001600160a01b0390921693506304071a4a925061260a9160040190815260200190565b600060405180830381600087803b15801561262457600080fd5b505af1158015612638573d6000803e3d6000fd5b505084516080870151604051636250216960e01b81526001600160a01b039092169350636250216992506126719133919060040161587a565b600060405180830381600087803b15801561268b57600080fd5b505af115801561269f573d6000803e3d6000fd5b50505050505050505b50505050505050565b600061108d6126bf83611a7e565b84613e6a565b600c81815481106126d557600080fd5b6000918252602090912001546001600160a01b0316905081565b600061108d8383613eec565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612751573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127759190615754565b9050600081600181111561278b5761278b6155ca565b036127e357600960009054906101000a90046001600160a01b03166001600160a01b031663bc8ec9e36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c56573d6000803e3d6000fd5b505060165490565b6127f58282611684565b801561280e5750600080516020615dff83398151915282145b156128295760188054906000612823836157d3565b91905055505b610d488282613f59565b80516000036128955760405162461bcd60e51b815260206004820152602860248201527f43616c6c646174612061646472657373206172726179206d757374206e6f7420604482015267626520656d70747960c01b6064820152608401611273565b610d48816040516024016128a99190615aea565b60408051601f19818403018152918152602080830180516001600160e01b0316630d98d91d60e41b179052815160608101909252602d80835290615e1f90830139601a546001600160a01b03169190612eab565b60006129076129d0565b6001600160a01b0383166000908152600d60205260408120546115d7908490615ad7565b600060016001600160a01b0383166000908152600d602052604090206003015460ff16600481111561295f5761295f6155ca565b1461296c57506000919050565b506011546001600160a01b039091166000908152600b60205260409020541090565b60006129986129d0565b6001600160a01b0383166000908152600d6020526040812060010154611541908490615ad7565b6129c76129d0565b610aeb81613f75565b6000546001600160a01b03163314612a365760405162461bcd60e51b8152602060048201526024808201527f43616c6c6572206973206e6f742074686520506f736974696f6e436f6e74726f604482015263363632b960e11b6064820152608401611273565b565b612a418161292b565b15612b3b57612a4f81612cfc565b6000612a5a82610e78565b90506000612a6783610e98565b6001600160a01b0384166000908152600d6020526040902060010154909150612a91908390615ad7565b6001600160a01b0384166000908152600d60205260409020600181019190915554612abd908290615ad7565b6001600160a01b0384166000908152600d6020526040902055612adf83612b40565b612aeb85858385613fe3565b6001600160a01b0383166000818152600d6020526040808220805460018201546002909201549251600080516020615ddf83398151915294612b309492939291615b37565b60405180910390a250505b505050565b6011546001600160a01b039091166000908152600b60205260409020908155601254600190910155565b6001600160a01b0381166000908152600d60205260408120600101548190612b91906140f8565b6001600160a01b0384166000908152600d60205260409020600201805490829055600e54919250908290612bc69083906158be565b612bd09190615ad7565b600e819055604051908152600080516020615dbf8339815191529060200160405180910390a15092915050565b60055460408051635c1548fb60e01b815290516000926001600160a01b031691635c1548fb9160048083019260209291908290030181865afa158015612c47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6b9190615775565b6004805460408051635c1548fb60e01b815290516001600160a01b0390921692635c1548fb9282820192602092908290030181865afa158015612cb2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cd69190615775565b610cfa9190615ad7565b612ce982610cdb565b612cf28161412e565b612b3b8383614138565b60016001600160a01b0382166000908152600d602052604090206003015460ff166004811115612d2e57612d2e6155ca565b14610aeb5760405162461bcd60e51b8152602060048201526024808201527f506f736974696f6e20646f6573206e6f74206578697374206f7220697320636c6044820152631bdcd95960e21b6064820152608401611273565b6000816004811115612d9b57612d9b6155ca565b14158015612dbb57506001816004811115612db857612db86155ca565b14155b612dc757612dc7615aa4565b600c54612dd3816141be565b6001600160a01b0383166000908152600d60205260409020600301805483919060ff19166001836004811115612e0b57612e0b6155ca565b02179055506001600160a01b0383166000908152600d60209081526040808320600180820185905590849055600b90925282208281550155612e4d8382614285565b600854604051631484968760e11b81526001600160a01b03909116906329092d0e90612e7d9086906004016154df565b600060405180830381600087803b158015612e9757600080fd5b505af11580156126a8573d6000803e3d6000fd5b6060600080856001600160a01b031685604051612ec89190615b79565b600060405180830381855af49150503d8060008114612f03576040519150601f19603f3d011682016040523d82523d6000602084013e612f08565b606091505b5091509150612f1986838387614455565b9695505050505050565b6001600160a01b0381163314612f935760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b6064820152608401611273565b610d4882826144ce565b6001600160a01b0381166000908152600b60205260408120546011548290612fc69083906158be565b9050801580613005575060016001600160a01b0385166000908152600d602052604090206003015460ff166004811115613002576130026155ca565b14155b15613014575060009392505050565b6001600160a01b0384166000908152600d602052604081206002015490670de0b6b3a76400006130448484615a8d565b612f199190615a79565b60095460075460405163c3f82bc360e01b815260009283926001600160a01b039182169263e0bbb60b9290911690839063c3f82bc3906130929030906004016154df565b602060405180830381865afa1580156130af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130d39190615800565b6040518363ffffffff1660e01b81526004016130f092919061581b565b602060405180830381865afa15801561310d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131319190615775565b90508061313d846132a1565b109392505050565b6005546040805162fcf9d160e11b815290516000926001600160a01b0316916301f9f3a29160048083019260209291908290030181865afa15801561318e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131b29190615775565b600480546040805162fcf9d160e11b815290516001600160a01b03909216926301f9f3a29282820192602092908290030181865afa158015612cb2573d6000803e3d6000fd5b6001600160a01b0381166000908152600b60205260408120600101546012548290612fc69083906158be565b60095460075460405163730a02b960e11b81526000926001600160a01b039081169263e614057292613260929091169087908790600401615b95565b602060405180830381865afa15801561327d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061108d9190615775565b6000806132ac612bfd565b905060006132b8613145565b905061333c828286600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613313573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133379190615800565b614535565b949350505050565b600061334e614561565b9050670de0b6b3a764000081111561336857613368615aa4565b6015819055604051818152600080516020615e748339815191529060200160405180910390a1610aeb6145ac565b6000670de0b6b3a76400006133ab8385615a8d565b61108d9190615a79565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561340b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061342f9190615754565b90506000816001811115613445576134456155ca565b0361349d57600960009054906101000a90046001600160a01b03166001600160a01b031663459799786040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c56573d6000803e3d6000fd5b610c7a614561565b600954600754604051633a60466f60e01b81526000926001600160a01b0390811692633a60466f92613260929091169087908790600401615b95565b600c80546001808201835560008381527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c790920180546001600160a01b0319166001600160a01b0386161790559154909161353b916158be565b6001600160a01b03929092166000908152600d602052604090206003018054610100600160881b0319166101006001600160801b038516021790555090565b600080600061358884612f9d565b90506000613595856131f8565b6001600160a01b0386166000908152600d6020526040812060010154919250906135c0908490615ad7565b6001600160a01b0387166000908152600d6020526040812054919250906135e8908490615ad7565b919791965090945050505050565b6000821561362f576136088483614615565b93508261361e68056bc75e2d6310000086615a8d565b6136289190615a79565b905061108d565b5060001961108d565b6001600160a01b0381166000908152600d602052604081208054600190910154909180613664856131f8565b915061366f85612f9d565b905061367b8285615ad7565b93506136878184615ad7565b92509193509193565b600080808086156136d6576136a688888861467d565b60408d0151939750919550935091506136c09033866148b6565b80156136d1576136d18985876149a4565b613788565b6136df33610c88565b156136fe576136ec614ab8565b50600092508291508190506001613788565b60009050879350613714896040015133866148b6565b60095460405163615c98e160e11b8152600481018690526001600160a01b039091169063c2b931c29060240160408051808303816000875af115801561375e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137829190615856565b90935091505b95509550955095915050565b60008111610aeb5760405162461bcd60e51b81526004016112739061591b565b60095460405163c3f82bc360e01b81526000916001600160a01b03169063c3f82bc3906137e59030906004016154df565b602060405180830381865afa158015613802573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138269190615800565b600954600754604051633697f68360e21b81529293506000926001600160a01b039283169263da5fda0c9261386292911690869060040161581b565b602060405180830381865afa15801561387f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138a39190615775565b9050826138ce6138bd6103e8670de0b6b3a7640000615a79565b6138c8906005615a8d565b83614bb5565b6138d89190615ad7565b84101580156138ef5750670de0b6b3a76400008411155b6139545760405162461bcd60e51b815260206004820152603060248201527f4d6178206665652070657263656e74616765206d75737420626520626574776560448201526f656e20302e352520616e64203130302560801b6064820152608401611273565b50505050565b80613964836132a1565b1015610d485760405162461bcd60e51b815260206004820152601c60248201527b21b0b73737ba103932b232b2b6903bb432b7102a21a9101e1026a1a960211b6044820152606401611273565b60006001600160a01b0384161580613a335750604051630bb7c8fd60e31b81526001600160a01b03861690635dbe47e8906139f09087906004016154df565b602060405180830381865afa158015613a0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a3191906158a3565b155b80613a46575081613a4485856126ef565b105b15613a535750600061333c565b60405163765e015960e01b81526000906001600160a01b0387169063765e015990613a829088906004016154df565b602060405180830381865afa158015613a9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ac39190615aba565b90506001600160a01b0381161580612f19575082613ae182866126ef565b109695505050505050565b613af4615417565b6001600160a01b0388166000908152600d6020526040902054613b2c908890613b2790680ad78ebc5ac6200000906158be565b614bcc565b8082528690613b4490670de0b6b3a764000090615a8d565b613b4e9190615a79565b60208083019190915281516001600160a01b038a166000908152600d9092526040822054613b7c91906158be565b6020808401516001600160a01b038c166000908152600d90925260408220600101549293509091613bad91906158be565b9050680ad78ebc5ac62000008203613bd957613bd48b8b680ad78ebc5ac620000084614bdb565b613bf7565b613bf4838c8c8a8a8a8888680ad78ebc5ac62000008d614c2a565b92505b505098975050505050505050565b336000908152601b6020526040902081158015613c2157508054155b15613c4e57336000908152601b602052604081208181556001810182905560028101829055600301555050565b8115610d4857600254604051630e0960cd60e31b81526001600160a01b039091169063704b066890613c8890339030908790600401615a3f565b600060405180830381600087803b158015613ca257600080fd5b505af1158015613cb6573d6000803e3d6000fd5b5050505081816000016000828254613cce9190615ad7565b90915550505050565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613d2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d519190615754565b90506000816001811115613d6757613d676155ca565b03613df157600954604051633f0486c160e21b81526004810187905260248101869052604481018590526001600160a01b039091169063fc121b04906064016020604051808303816000875af1158015613dc5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613de99190615775565b91505061108d565b613de9858585614dc9565b600061108d6126bf83610f83565b600082613e1f670de0b6b3a764000086615a8d565b613e299190615a79565b9050818111156139545760405162461bcd60e51b815260206004820152600c60248201526b11995948195e18d95959195960a21b6044820152606401611273565b600080670de0b6b3a7640000613e808486615a8d565b613e8a9190615a79565b905082811061108d5760405162461bcd60e51b815260206004820152602860248201527f46656520776f756c642065617420757020616c6c2072657475726e656420636f6044820152671b1b185d195c985b60c21b6064820152608401611273565b6000806000613efa8561357a565b915091506000612f19838387600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613313573d6000803e3d6000fd5b613f6282610cdb565b613f6b8161412e565b612b3b83836144ce565b6001600160a01b0381166000908152600d6020526040902060020154600e54613f9f9082906158be565b600e819055604051908152600080516020615dbf8339815191529060200160405180910390a1506001600160a01b03166000908152600d6020526040812060020155565b6040516302038d2560e11b8152600481018390526001600160a01b038416906304071a4a90602401600060405180830381600087803b15801561402557600080fd5b505af1158015614039573d6000803e3d6000fd5b5050604051634ba6322b60e11b8152600481018590526001600160a01b038716925063974c64569150602401600060405180830381600087803b15801561407f57600080fd5b505af1158015614093573d6000803e3d6000fd5b5050604051633ef8ba8160e11b8152600481018490526001600160a01b0386169250637df1750291506024015b600060405180830381600087803b1580156140da57600080fd5b505af11580156140ee573d6000803e3d6000fd5b5050505050505050565b60008060105460000361410c575081610ac0565b6000600f541161411e5761411e615aa4565b601054600f546133ab9085615a8d565b610aeb8133614e5a565b6141428282611684565b610d485760008281526017602090815260408083206001600160a01b03851684529091529020805460ff1916600117905561417a3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60018111801561423957506008546040805163de8fa43160e01b815290516001926001600160a01b03169163de8fa4319160048083019260209291908290030181865afa158015614213573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906142379190615775565b115b610aeb5760405162461bcd60e51b815260206004820152601f60248201527f4f6e6c79206f6e6520706f736974696f6e20696e207468652073797374656d006044820152606401611273565b6001600160a01b0382166000908152600d602052604081206003015460ff16908160048111156142b7576142b76155ca565b141580156142d7575060018160048111156142d4576142d46155ca565b14155b6142e3576142e3615aa4565b6001600160a01b0383166000908152600d602052604081206003015461010090046001600160801b031690839061431b6001836158be565b905080836001600160801b0316111561433657614336615aa4565b6000600c828154811061434b5761434b6157bd565b600091825260209091200154600c80546001600160a01b03909216925082916001600160801b038716908110614383576143836157bd565b600091825260208083209190910180546001600160a01b0319166001600160a01b03948516179055918316808252600d83526040918290206003018054610100600160881b0319166101006001600160801b038a16908102919091179091558251918252928101929092527f18866c04f256504f718fa0e2d2926b02c454fa1cabd9664493cc1389db93e5fb910160405180910390a1600c80548061442a5761442a615bb6565b600082815260209020810160001990810180546001600160a01b031916905501905550505050505050565b606083156144c45782516000036144bd576001600160a01b0385163b6144bd5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611273565b508161333c565b61333c8383614eb3565b6144d88282611684565b15610d485760008281526017602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b600083600003614548575060001961333c565b6145528583614615565b94506000846130448588615a8d565b60008061456c614edd565b90506000614582670ddd4b8c6c7d70d883614ef9565b9050670de0b6b3a76400008160155461459b9190615a8d565b6145a59190615a79565b9250505090565b60006145b6614edd565b90508015610aeb576145c9603c82615a8d565b601660008282546145da9190615ad7565b90915550506040514281527f860f8d2f0c74dd487e89e2883e3b25b8159ce1e1b3433a291cba7b82c508f3bc9060200160405180910390a150565b600060128260ff16101561464a5761462e826012615bcc565b61463990600a615cc9565b6146439084615a8d565b9050610ac0565b60128260ff16111561467657614661601283615bcc565b61466c90600a615cc9565b6146439084615a79565b5081610ac0565b336000908152601b6020526040812060018101548291829182919082036146de5760405162461bcd60e51b8152602060048201526015602482015274149959195b5c1d1a5bdb881b9bdd081c5d595d5959605a1b6044820152606401611273565b805488111561474a5760405162461bcd60e51b815260206004820152603260248201527f43616e6e6f742072656465656d206d6f7265207468616e2072656d61696e696e604482015271672071756575656420696e20657363726f7760701b6064820152608401611273565b600087826001015461475c9190615ad7565b9050600061476a8883615ad7565b6002840154600385015490975095509050428111801561480b57428311156147e55760405162461bcd60e51b815260206004820152602860248201527f526564656d7074696f6e20657363726f772074696d656c6f636b206e6f742073604482015267185d1a5cd99a595960c21b6064820152608401611273565b600094508a97508784600001600082825461480091906158be565b909155506148189050565b8354600085559750600194505b60025460405163a9059cbb60e01b81526001600160a01b039091169063a9059cbb9061484a9033908c9060040161587a565b6020604051808303816000875af1158015614869573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061488d91906158a3565b6148a95760405162461bcd60e51b815260040161127390615cd8565b5050505093509350935093565b6040516370a0823160e01b815281906001600160a01b038516906370a08231906148e49086906004016154df565b602060405180830381865afa158015614901573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906149259190615775565b1015612b3b5760405162461bcd60e51b815260206004820152604260248201527f52657175657374656420726564656d7074696f6e20616d6f756e74206d75737460448201527f206265203c3d2075736572277320737461626c6520746f6b656e2062616c616e606482015261636560f01b608482015260a401611273565b6000670de0b6b3a76400006149b98484615a8d565b6149c39190615a79565b6060850151604051636fd32add60e01b8152600481018390529192506001600160a01b031690636fd32add90602401600060405180830381600087803b158015614a0c57600080fd5b505af1158015614a20573d6000803e3d6000fd5b5050505083604001516001600160a01b031663704b0668338660600151846040518463ffffffff1660e01b8152600401614a5c93929190615a3f565b600060405180830381600087803b158015614a7657600080fd5b505af1158015614a8a573d6000803e3d6000fd5b5050336000908152601b60205260408120818155600181018290556002810182905560030155505050505050565b336000908152601b6020908152604091829020825160808101845281548152600182015492810183905260028201549381019390935260030154606083015215610aeb57600254815160405163a9059cbb60e01b81526001600160a01b039092169163a9059cbb91614b2f9133919060040161587a565b6020604051808303816000875af1158015614b4e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614b7291906158a3565b614b8e5760405162461bcd60e51b815260040161127390615cd8565b336000908152601b6020526040812081815560018101829055600281018290556003015550565b600081831015614bc5578161108d565b5090919050565b6000818310614bc5578161108d565b614be483613f75565b614bef836004612d87565b614bfb84848484614fa4565b6001600160a01b038316600080516020615ddf8339815191526000808060036040516113ea9493929190615b37565b614c32615417565b6000614c8c8587600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b41573d6000803e3d6000fd5b9050686194049f30f7200000614ca285886158be565b1080614cb75750868114158015614cb7575082155b15614ccb575050600160408b015289614dbb565b60808b015160405163015f109360e51b81526001600160a01b038c81166004830152602482018490528b811660448301528a8116606483015290911690632be2126090608401600060405180830381600087803b158015614d2b57600080fd5b505af1158015614d3f573d6000803e3d6000fd5b5050506001600160a01b038b166000908152600d6020526040902087815560010186905550614d6d8a612b6a565b506001600160a01b038a166000818152600d602052604090819020600201549051600080516020615ddf83398151915291614dae918a918a91600390615b37565b60405180910390a28b9150505b9a9950505050505050505050565b600080614dd4614561565b9050600083614de38688615a8d565b614ded9190615a79565b90506000614dfc600283615a79565b614e069084615ad7565b9050614e1a81670de0b6b3a7640000614bcc565b905060008111614e2c57614e2c615aa4565b6015819055604051818152600080516020615e748339815191529060200160405180910390a1612f196145ac565b614e648282611684565b610d4857614e718161516a565b614e7c83602061517c565b604051602001614e8d929190615d08565b60408051601f198184030181529082905262461bcd60e51b825261127391600401615d77565b815115614ec35781518083602001fd5b8060405162461bcd60e51b81526004016112739190615d77565b6000603c60165442614eef91906158be565b610cfa9190615a79565b6000631f540500821115614f0f57631f54050091505b81600003614f265750670de0b6b3a7640000610ac0565b670de0b6b3a764000083835b6001811115614f9a57614f46600282615daa565b600003614f6b57614f578283615317565b9150614f64600282615a79565b9050614f32565b614f758284615317565b9250614f818283615317565b91506002614f906001836158be565b614f649190615a79565b612f198284615317565b600254600154604051632770a7eb60e21b81526001600160a01b0392831692639dc29fac92614fda92911690869060040161587a565b600060405180830381600087803b158015614ff457600080fd5b505af1158015615008573d6000803e3d6000fd5b505085516040516302038d2560e11b8152600481018690526001600160a01b0390911692506304071a4a9150602401600060405180830381600087803b15801561505157600080fd5b505af1158015615065573d6000803e3d6000fd5b505050508360a001516001600160a01b0316633f10abab84836040518363ffffffff1660e01b815260040161509b92919061587a565b600060405180830381600087803b1580156150b557600080fd5b505af11580156150c9573d6000803e3d6000fd5b5050855160a0870151604051636250216960e01b81526001600160a01b0390921693506362502169925061510191859060040161587a565b600060405180830381600087803b15801561511b57600080fd5b505af115801561512f573d6000803e3d6000fd5b50505060a08501516007546040516302e3067760e21b81526001600160a01b039283169350630b8c19dc926140c0921690859060040161587a565b6060610ac06001600160a01b03831660145b6060600061518b836002615a8d565b615196906002615ad7565b6001600160401b038111156151ad576151ad615634565b6040519080825280601f01601f1916602001820160405280156151d7576020820181803683370190505b509050600360fc1b816000815181106151f2576151f26157bd565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110615221576152216157bd565b60200101906001600160f81b031916908160001a9053506000615245846002615a8d565b615250906001615ad7565b90505b60018111156152c8576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110615284576152846157bd565b1a60f81b82828151811061529a5761529a6157bd565b60200101906001600160f81b031916908160001a90535060049490941c936152c1816157d3565b9050615253565b50831561108d5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401611273565b6000806153248385615a8d565b9050670de0b6b3a764000061533a600282615a79565b6153449083615ad7565b61333c9190615a79565b6040518061028001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016153d96040518060800160405280600081526020016000815260200160008152602001600081525090565b8152602001600081526020016000151581526020016000815260200160008152602001600060ff168152602001600081526020016000151581525090565b604051806060016040528060008152602001600081526020016000151581525090565b60006020828403121561544c57600080fd5b81356001600160e01b03198116811461108d57600080fd5b6001600160a01b0381168114610aeb57600080fd5b60006020828403121561548b57600080fd5b813561108d81615464565b6000602082840312156154a857600080fd5b5035919050565b600080604083850312156154c257600080fd5b8235915060208301356154d481615464565b809150509250929050565b6001600160a01b0391909116815260200190565b93845260208401929092526040830152606082015260800190565b6000806040838503121561552157600080fd5b50508035926020909101359150565b6000806040838503121561554357600080fd5b823561554e81615464565b946020939093013593505050565b600080600080600080600060e0888a03121561557757600080fd5b87359650602088013561558981615464565b9550604088013561559981615464565b945060608801356155a981615464565b9699959850939660808101359560a0820135955060c0909101359350915050565b634e487b7160e01b600052602160045260246000fd5b858152602081018590526040810184905260a081016005841061561357634e487b7160e01b600052602160045260246000fd5b60608201939093526001600160801b03919091166080909101529392505050565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b038111828210171561566d5761566d615634565b60405290565b604051601f8201601f191681016001600160401b038111828210171561569b5761569b615634565b604052919050565b600060208083850312156156b657600080fd5b82356001600160401b03808211156156cd57600080fd5b818501915085601f8301126156e157600080fd5b8135818111156156f3576156f3615634565b8060051b9150615704848301615673565b818152918301840191848101908884111561571e57600080fd5b938501935b83851015615748578435925061573883615464565b8282529385019390850190615723565b98975050505050505050565b60006020828403121561576657600080fd5b81516002811061108d57600080fd5b60006020828403121561578757600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b6000600182016157b6576157b661578e565b5060010190565b634e487b7160e01b600052603260045260246000fd5b6000816157e2576157e261578e565b506000190190565b805160ff811681146157fb57600080fd5b919050565b60006020828403121561581257600080fd5b61108d826157ea565b6001600160a01b0392909216825260ff16602082015260400190565b9384526020840192909252151560408301521515606082015260800190565b6000806040838503121561586957600080fd5b505080516020909101519092909150565b6001600160a01b03929092168252602082015260400190565b805180151581146157fb57600080fd5b6000602082840312156158b557600080fd5b61108d82615893565b81810381811115610ac057610ac061578e565b6020808252602a908201527f43616c6c657220646f6573206e6f74206861766520726564656d7074696f6e2060408201526970726976696c6567657360b01b606082015260800190565b6020808252818101527f416d6f756e74206d7573742062652067726561746572207468616e207a65726f604082015260600190565b80516157fb81615464565b6000610120828403121561596e57600080fd5b61597661564a565b61597f836157ea565b815261598d60208401615950565b602082015261599e60408401615950565b60408201526159af60608401615950565b60608201526159c060808401615950565b60808201526159d160a08401615950565b60a08201526159e260c08401615950565b60c08201526159f360e08401615950565b60e0820152610100615a06818501615893565b908201529392505050565b600080600060608486031215615a2657600080fd5b8351925060208401519150604084015190509250925092565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b600052601260045260246000fd5b600082615a8857615a88615a63565b500490565b8082028115828204841417610ac057610ac061578e565b634e487b7160e01b600052600160045260246000fd5b600060208284031215615acc57600080fd5b815161108d81615464565b80820180821115610ac057610ac061578e565b6020808252825182820181905260009190848201906040850190845b81811015615b2b5783516001600160a01b031683529284019291840191600101615b06565b50909695505050505050565b9384526020840192909252604083015260ff16606082015260800190565b60005b83811015615b70578181015183820152602001615b58565b50506000910152565b60008251615b8b818460208701615b55565b9190910192915050565b6001600160a01b039390931683526020830191909152604082015260600190565b634e487b7160e01b600052603160045260246000fd5b60ff8281168282160390811115610ac057610ac061578e565b600181815b80851115615c20578160001904821115615c0657615c0661578e565b80851615615c1357918102915b93841c9390800290615bea565b509250929050565b600082615c3757506001610ac0565b81615c4457506000610ac0565b8160018114615c5a5760028114615c6457615c80565b6001915050610ac0565b60ff841115615c7557615c7561578e565b50506001821b610ac0565b5060208310610133831016604e8410600b8410161715615ca3575081810a610ac0565b615cad8383615be5565b8060001904821115615cc157615cc161578e565b029392505050565b600061108d60ff841683615c28565b6020808252601690820152751cdd18589b19481d1c985b9cd9995c8819985a5b195960521b604082015260600190565b76020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b815260008351615d3a816017850160208801615b55565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351615d6b816028840160208801615b55565b01602801949350505050565b6020815260008251806020840152615d96816040850160208701615b55565b601f01601f19169190910160400192915050565b600082615db957615db9615a63565b50069056fe54edc0b4728c3923cb75a7e36b998c5eb1c6ca744db9015f495191569e0421d04fe7fb62190647b8a7596709832f68a365082b18206e55ae330b95593c369aff44ac9762eec3a11893fefb11d028bb3102560094137c3ed4518712475b2577cc62617463684c6971756964617465506f736974696f6e733a2064656c65676174652063616c6c206661696c65646c6971756964617465506f736974696f6e733a2064656c65676174652063616c6c206661696c6564c454ee9b76c52f782a256af821b857ca6e125d1e3333bcede402fec2bed9600ca2646970667358221220ef82721b49fb2a3e1462976a0c5f7b87b554cb4e3581f89c1997f26c6f68ea7464736f6c63430008150033608060405234801561001057600080fd5b5061351a806100206000396000f3fe608060405234801561001057600080fd5b50600436106101495760003560e01c8063139f2e8c1461014e5780631673c79a146101715780631bf43555146101ad578063340c0780146101bd5780633cc74225146101d25780634840fb37146101f257806369076788146101fb57806372fe25aa1461020e578063741bef1a1461021d5780637f7dde4a14610230578063807d138d146102435780638200bfe61461024c57806396d711ff1461025f578063a20baee61461020e578063a9d75b2b14610268578063acbb08e61461027b578063ae3726ed1461028e578063b2016bd414610296578063bf88dd71146102a9578063bf9befb114610302578063c045e47d1461030b578063c36069cc1461028e578063cb5f62401461031e578063d347e07b14610331578063d38b05581461033a578063d98d91d014610343578063ee266b8714610356575b600080fd5b61015e680ad78ebc5ac620000081565b6040519081526020015b60405180910390f35b61019861017f366004612fe3565b600b602052600090815260409020805460019091015482565b60408051928352602083019190915201610168565b61015e686194049f30f720000081565b6101d06101cb366004613000565b61035f565b005b6005546101e5906001600160a01b031681565b6040516101689190613019565b61015e60145481565b6009546101e5906001600160a01b031681565b61015e670de0b6b3a764000081565b6003546101e5906001600160a01b031681565b6004546101e5906001600160a01b031681565b61015e600f5481565b6006546101e5906001600160a01b031681565b61015e60105481565b6002546101e5906001600160a01b031681565b600a546101e5906001600160a01b031681565b61015e610970565b6007546101e5906001600160a01b031681565b6102f16102b7366004612fe3565b600d6020526000908152604090208054600182015460028301546003909301549192909160ff81169061010090046001600160801b031685565b604051610168959493929190613043565b61015e600e5481565b6008546101e5906001600160a01b031681565b6101e561032c366004613000565b610992565b61015e60125481565b61015e60135481565b6101d06103513660046130ad565b6109bc565b61015e60115481565b6040805160c0810182526004546001600160a01b039081168252600554811660208301526000928201839052606082018390526008548116608083015260a08201929092526006549091166103b2612ed8565b6103ba612f09565b60095460405163c3f82bc360e01b81526000916001600160a01b03169063c3f82bc3906103eb903090600401613019565b602060405180830381865afa158015610408573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061042c9190613171565b600354604051635ab3550d60e11b815260016004820152600060248201529192506001600160a01b03169063b566aa1a906044016020604051808303816000875af115801561047f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104a39190613194565b836000018181525050836001600160a01b031663adf188096040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050e9190613194565b6020840152825161051e90610fdf565b1515604080850191909152600954600754915163c3f82bc360e01b81526000926001600160a01b039283169263368bceed92911690839063c3f82bc390610569903090600401613019565b602060405180830381865afa158015610586573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105aa9190613171565b6040518363ffffffff1660e01b81526004016105c79291906131ad565b602060405180830381865afa1580156105e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106089190613194565b60095460075460405163c3f82bc360e01b81529293506000926001600160a01b039283169263e0bbb60b921690839063c3f82bc39061064b903090600401613019565b602060405180830381865afa158015610668573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061068c9190613171565b6040518363ffffffff1660e01b81526004016106a99291906131ad565b602060405180830381865afa1580156106c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106ea9190613194565b90508460400151156107135761070c87866000015187602001518b86866110d6565b9350610734565b61073187600001518860200151876000015188602001518c8761139b565b93505b60008460200151116107615760405162461bcd60e51b8152600401610758906131c9565b60405180910390fd5b600754608085015160a08601516040516358ed511760e11b81526001600160a01b038a81169463b1daa22e946107a19492909116928992906004016131f7565b600060405180830381600087803b1580156107bb57600080fd5b505af11580156107cf573d6000803e3d6000fd5b505050506107ef876000015188602001518660c001518760e001516114b7565b610100840151156108d3578651600a54610100860151604051636250216960e01b81526001600160a01b039384169363625021699361083393911691600401613220565b600060405180830381600087803b15801561084d57600080fd5b505af1158015610861573d6000803e3d6000fd5b5050600a546007546101008801516040516302e3067760e21b81526001600160a01b039384169550630b8c19dc94506108a09390921691600401613220565b600060405180830381600087803b1580156108ba57600080fd5b505af11580156108ce573d6000803e3d6000fd5b505050505b6108e587600001518560400151611715565b6020840151606086015261010084015160408501518551610906919061324f565b610910919061324f565b608086018190526060808701516040808801519288015190516000805160206134a5833981519152946109469490929091613262565b60405180910390a16109668760000151338660600151876040015161181d565b5050505050505050565b6109846103e8670de0b6b3a764000061327d565b61098f90600561329f565b81565b600c81815481106109a257600080fd5b6000918252602090912001546001600160a01b0316905081565b8051600003610a1e5760405162461bcd60e51b815260206004820152602860248201527f43616c6c646174612061646472657373206172726179206d757374206e6f7420604482015267626520656d70747960c01b6064820152608401610758565b6004546005546006546001600160a01b03928316929182169116610a40612ed8565b610a48612f09565b60095460405163c3f82bc360e01b81526000916001600160a01b03169063c3f82bc390610a79903090600401613019565b602060405180830381865afa158015610a96573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aba9190613171565b600354604051635ab3550d60e11b815260016004820152600060248201529192506001600160a01b03169063b566aa1a906044016020604051808303816000875af1158015610b0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b319190613194565b836000018181525050836001600160a01b031663adf188096040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9c9190613194565b60208401528251610bac90610fdf565b1515604080850191909152600954600754915163c3f82bc360e01b81526000926001600160a01b039283169263368bceed92911690839063c3f82bc390610bf7903090600401613019565b602060405180830381865afa158015610c14573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c389190613171565b6040518363ffffffff1660e01b8152600401610c559291906131ad565b602060405180830381865afa158015610c72573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c969190613194565b60095460075460405163c3f82bc360e01b81529293506000926001600160a01b039283169263e0bbb60b921690839063c3f82bc390610cd9903090600401613019565b602060405180830381865afa158015610cf6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d1a9190613171565b6040518363ffffffff1660e01b8152600401610d379291906131ad565b602060405180830381865afa158015610d54573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d789190613194565b9050846040015115610da257610d9b8888876000015188602001518d87876118f6565b9350610dbb565b610db88888876000015188602001518d87611b8d565b93505b6000846020015111610ddf5760405162461bcd60e51b8152600401610758906131c9565b600754608085015160a08601516040516358ed511760e11b81526001600160a01b038a81169463b1daa22e94610e1f9492909116928992906004016131f7565b600060405180830381600087803b158015610e3957600080fd5b505af1158015610e4d573d6000803e3d6000fd5b50505050610e6588888660c001518760e001516114b7565b61010084015115610f4957600a54610100850151604051636250216960e01b81526001600160a01b038b811693636250216993610ea9939290911691600401613220565b600060405180830381600087803b158015610ec357600080fd5b505af1158015610ed7573d6000803e3d6000fd5b5050600a546007546101008801516040516302e3067760e21b81526001600160a01b039384169550630b8c19dc9450610f169390921691600401613220565b600060405180830381600087803b158015610f3057600080fd5b505af1158015610f44573d6000803e3d6000fd5b505050505b610f57888560400151611715565b6020840151606086015261010084015160408501518551610f78919061324f565b610f82919061324f565b608086018190526060808701516040808801519288015190516000805160206134a583398151915294610fb89490929091613262565b60405180910390a1610fd488338660600151876040015161181d565b505050505050505050565b60095460075460405163c3f82bc360e01b815260009283926001600160a01b039182169263e0bbb60b9290911690839063c3f82bc390611023903090600401613019565b602060405180830381865afa158015611040573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110649190613171565b6040518363ffffffff1660e01b81526004016110819291906131ad565b602060405180830381865afa15801561109e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110c29190613194565b9050806110ce84611c60565b109392505050565b6110de612f09565b6110e6612f55565b6110ee612f09565b86825260006080830152611100611cda565b60a083015261110d611dc0565b8260c001818152505088608001516001600160a01b0316634d6228316040518163ffffffff1660e01b8152600401602060405180830381865afa158015611158573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117c91906132b6565b82606001906001600160a01b031690816001600160a01b031681525050600089608001516001600160a01b0316631e2231436040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111dd573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061120191906132b6565b6000602085015290505b8683602001511080156112345750806001600160a01b031683606001516001600160a01b031614155b1561138e5760808a01516060840151604051632dc9c0eb60e21b81526000926001600160a01b03169163b72703ac916112709190600401613019565b602060405180830381865afa15801561128d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112b191906132b6565b90506112c184606001518b611e75565b6040850152608084015161130757868460400151101580156112e257508351155b156112ed575061138e565b6112fb848c85888e8b611eee565b96509094509250611368565b8360800151801561131b5750868460400151105b156113625761133c8b600001518c6020015186606001518760000151612029565b6080810151855191945061134f9161324f565b845261135b8584612153565b9450611368565b5061138e565b6001600160a01b0316606084015260208301805190611386826132d3565b90525061120b565b5050509695505050505050565b6113a3612f09565b6113ab612f55565b6113b3612f09565b600854868352600060208401526001600160a01b03165b858360200151101561138e57806001600160a01b0316634d6228316040518163ffffffff1660e01b8152600401602060405180830381865afa158015611414573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061143891906132b6565b6001600160a01b0316606084018190526114529089611e75565b6040840181905285111561149a576114748a8a85606001518660000151612029565b608081015184519193506114879161324f565b83526114938483612153565b935061149f565b61138e565b602083018051906114af826132d3565b9052506113ca565b811561170f576013546000906114d5670de0b6b3a76400008461329f565b6114df91906132ec565b90506000601454670de0b6b3a7640000856114fa919061329f565b61150491906132ec565b90506000600e5483611516919061327d565b90506000600e5483611528919061327d565b9050600e5482611538919061329f565b611542908561324f565b601355600e54611552908261329f565b61155c908461324f565b601481905550816011600082825461157491906132ec565b92505081905550806012600082825461158d91906132ec565b90915550506040516302038d2560e11b8152600481018790526001600160a01b038916906304071a4a90602401600060405180830381600087803b1580156115d457600080fd5b505af11580156115e8573d6000803e3d6000fd5b5050604051634ba6322b60e11b8152600481018990526001600160a01b038a16925063974c64569150602401600060405180830381600087803b15801561162e57600080fd5b505af1158015611642573d6000803e3d6000fd5b5050604051636250216960e01b81526001600160a01b038b16925063625021699150611674908a908990600401613220565b600060405180830381600087803b15801561168e57600080fd5b505af11580156116a2573d6000803e3d6000fd5b50506007546040516302e3067760e21b81526001600160a01b03808c169450630b8c19dc93506116d89216908990600401613220565b600060405180830381600087803b1580156116f257600080fd5b505af1158015611706573d6000803e3d6000fd5b50505050505050505b50505050565b600e54600f819055506000826001600160a01b0316635c1548fb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561175e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117829190613194565b90506000600560009054906101000a90046001600160a01b03166001600160a01b0316635c1548fb6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117fd9190613194565b90508061180a848461324f565b61181491906132ec565b60105550505050565b811561189457600254600154604051631062c15f60e11b81526001600160a01b0391821660048201528582166024820152604481018590529116906320c582be90606401600060405180830381600087803b15801561187b57600080fd5b505af115801561188f573d6000803e3d6000fd5b505050505b801561170f57604051636250216960e01b81526001600160a01b038516906362502169906118c89086908590600401613220565b600060405180830381600087803b1580156118e257600080fd5b505af1158015610966573d6000803e3d6000fd5b6118fe612f09565b611906612f55565b61190e612f09565b86825260006080830152611920611cda565b60a083015261192d611dc0565b60c0830152600060208301525b855182602001511015611b80578582602001518151811061195d5761195d6132ff565b6020908102919091018101516001600160a01b0316606084018190526000908152600d909152604090206003015460019060ff1660048111156119a2576119a261302d565b03611b68576119b5826060015189611e75565b60408301526080820151611b1957848260400151101580156119d657508151155b611b68576000611a668360c001518460a001518b600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a619190613171565b61223d565b9050611a838b8b856060015186604001518760000151868f61227d565b60808101518451919350611a969161324f565b8352608082015160a0840151611aac919061324f565b8360a001818152505081610100015182604001518360a001518560c00151611ad4919061324f565b611ade919061324f565b611ae8919061324f565b60c0840152611af78483612153565b9350611b0d8360c001518460a001518b88612633565b15608084015250611b68565b81608001518015611b2d5750848260400151105b15611b6857611b468a8a84606001518560000151612029565b60808101518351919250611b599161324f565b8252611b658382612153565b92505b60208201805190611b78826132d3565b90525061193a565b5050979650505050505050565b611b95612f09565b611b9d612f55565b611ba5612f09565b858252600060208301525b845182602001511015611c545784826020015181518110611bd357611bd36132ff565b60209081029190910101516001600160a01b031660608301819052611bf89088611e75565b60408301819052841115611c3c57611c1a898984606001518560000151612029565b60808101518351919250611c2d9161324f565b8252611c398382612153565b92505b60208201805190611c4c826132d3565b905250611bb0565b50509695505050505050565b600080611c6b611dc0565b90506000611c77611cda565b9050611cd2828286600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3d573d6000803e3d6000fd5b949350505050565b6005546040805162fcf9d160e11b815290516000926001600160a01b0316916301f9f3a29160048083019260209291908290030181865afa158015611d23573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d479190613194565b600480546040805162fcf9d160e11b815290516001600160a01b03909216926301f9f3a29282820192602092908290030181865afa158015611d8d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611db19190613194565b611dbb91906132ec565b905090565b60055460408051635c1548fb60e01b815290516000926001600160a01b031691635c1548fb9160048083019260209291908290030181865afa158015611e0a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e2e9190613194565b6004805460408051635c1548fb60e01b815290516001600160a01b0390921692635c1548fb9282820192602092908290030181865afa158015611d8d573d6000803e3d6000fd5b6000806000611e838561269b565b915091506000611ee2838387600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3d573d6000803e3d6000fd5b93505050505b92915050565b611ef6612f55565b611efe612f09565b611f06612f09565b6000611f698a60c001518b60a0015188600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3d573d6000803e3d6000fd5b895160208b015160608d015160408e01518e51949550611f8a94868c61227d565b60808101518b51919950611f9d9161324f565b8a52608088015160a08b0151611fb3919061324f565b8a60a001818152505087610100015188604001518960a001518c60c00151611fdb919061324f565b611fe5919061324f565b611fef919061324f565b60c08b0152611ffe8789612153565b96506120148a60c001518b60a001518888612633565b1560808b015250979895975093955050505050565b612031612f09565b612039612f9d565b61204284612717565b6040850190815260208581019283528601929092529184529051905161206c91889188919061276f565b61207584612850565b61208282602001516128d0565b60408301819052680ad78ebc5ac6200000606084015260208301516000916120a99161324f565b90506120ba836000015182866128dd565b60e087015260c086015260a085015260808401526120d985600361293e565b825160208401516040516001600160a01b038816926000805160206134858339815191529261210a92600190613315565b60405180910390a26001600160a01b0385166000805160206134c5833981519152600080806001604051612141949392919061332e565b60405180910390a25050949350505050565b61215b612f09565b8160400151836040015161216f91906132ec565b60408201526060808301519084015161218891906132ec565b60608201528151602084015161219e91906132ec565b60208083019190915282015183516121b691906132ec565b8152608080830151908401516121cc91906132ec565b608082015260a080830151908401516121e591906132ec565b60a082015260c080830151908401516121fe91906132ec565b60c082015260e0808301519084015161221791906132ec565b60e0820152610100808301519084015161223191906132ec565b61010082015292915050565b6000836000036122505750600019611cd2565b61225a8583612a6b565b9450600084612269858861329f565b612273919061327d565b9695505050505050565b612285612f09565b61228d612f9d565b600c5460011061229d5750612628565b6122a687612717565b604085015260208481019190915284018190529083526122c5906128d0565b60408301819052680ad78ebc5ac6200000606084015260208301516122ea919061324f565b815260095460075460405163c3f82bc360e01b81526000926001600160a01b039081169263368bceed92911690839063c3f82bc39061232d903090600401613019565b602060405180830381865afa15801561234a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061236e9190613171565b6040518363ffffffff1660e01b815260040161238b9291906131ad565b602060405180830381865afa1580156123a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123cc9190613194565b9050670de0b6b3a76400008711612499576123f18a8a8460200151856040015161276f565b6123fa88612850565b60006080840181905260a0840152825160c0840152815160e084015261242188600361293e565b825160208401516001600160a01b038a16916000805160206134858339815191529160025b60405161245593929190613315565b60405180910390a26001600160a01b0388166000805160206134c583398151915260008080600260405161248c949392919061332e565b60405180910390a2611b80565b670de0b6b3a7640000871180156124af57508087105b156124ff576124c88a8a8460200151856040015161276f565b6124d188612850565b825182516124e09190886128dd565b60e087015260c086015260a0850152608084015261242188600361293e565b80871015801561250e57508487105b801561251b575082518610155b15612616576125348a8a8460200151856040015161276f565b856000036125445761254461334c565b61254d88612850565b61256b836000015184602001518684680ad78ebc5ac6200000612ad3565b925061257888600361293e565b610100830151156125ed57600a54610100840151604051633f10abab60e01b81526001600160a01b0390921691633f10abab916125ba918c9190600401613220565b600060405180830381600087803b1580156125d457600080fd5b505af11580156125e8573d6000803e3d6000fd5b505050505b825160a08401516001600160a01b038a1691600080516020613485833981519152916002612446565b61261e612f09565b9250612628915050565b979650505050505050565b60008061268f868686600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3d573d6000803e3d6000fd5b90921195945050505050565b60008060006126a984612b53565b905060006126b685612bfa565b6001600160a01b0386166000908152600d6020526040812060010154919250906126e19084906132ec565b6001600160a01b0387166000908152600d6020526040812054919250906127099084906132ec565b919791965090945050505050565b6001600160a01b0381166000908152600d60205260408120805460019091015490918061274385612bfa565b915061274e85612b53565b905061275a82856132ec565b935061276681846132ec565b92509193509193565b6040516302038d2560e11b8152600481018390526001600160a01b038416906304071a4a90602401600060405180830381600087803b1580156127b157600080fd5b505af11580156127c5573d6000803e3d6000fd5b5050604051634ba6322b60e11b8152600481018590526001600160a01b038716925063974c64569150602401600060405180830381600087803b15801561280b57600080fd5b505af115801561281f573d6000803e3d6000fd5b5050604051633ef8ba8160e11b8152600481018490526001600160a01b0386169250637df1750291506024016118c8565b6001600160a01b0381166000908152600d6020526040902060020154600e5461287a90829061324f565b600e8190556040519081527f54edc0b4728c3923cb75a7e36b998c5eb1c6ca744db9015f495191569e0421d09060200160405180910390a1506001600160a01b03166000908152600d6020526040812060020155565b6000611ee860c88361327d565b60008080808415612928576128f28786612c26565b9350866128ff858861329f565b612909919061327d565b9250612915848861324f565b9150612921838761324f565b9050612935565b5060009250829150859050845b93509350935093565b60008160048111156129525761295261302d565b141580156129725750600181600481111561296f5761296f61302d565b14155b61297e5761297e61334c565b600c5461298a81612c3e565b6001600160a01b0383166000908152600d60205260409020600301805483919060ff191660018360048111156129c2576129c261302d565b02179055506001600160a01b0383166000908152600d60209081526040808320600180820185905590849055600b90925282208281550155612a048382612d08565b600854604051631484968760e11b81526001600160a01b03909116906329092d0e90612a34908690600401613019565b600060405180830381600087803b158015612a4e57600080fd5b505af1158015612a62573d6000803e3d6000fd5b50505050505050565b600060128260ff161015612aa057612a84826012613362565b612a8f90600a61345f565b612a99908461329f565b9050611ee8565b60128260ff161115612acc57612ab7601283613362565b612ac290600a61345f565b612a99908461327d565b5081611ee8565b612adb612f09565b85815260208101859052600084612af2858961329f565b612afc919061327d565b9050612b07816128d0565b604083018190526060830184905260808301889052612b26908261324f565b60a0830152612b35818761324f565b61010083015250600060c0820181905260e082015295945050505050565b6001600160a01b0381166000908152600b60205260408120546011548290612b7c90839061324f565b9050801580612bbb575060016001600160a01b0385166000908152600d602052604090206003015460ff166004811115612bb857612bb861302d565b14155b15612bca575060009392505050565b6001600160a01b0384166000908152600d602052604081206002015490670de0b6b3a7640000612269848461329f565b6001600160a01b0381166000908152600b60205260408120600101546012548290612b7c90839061324f565b6000818310612c355781612c37565b825b9392505050565b600181118015612cb957506008546040805163de8fa43160e01b815290516001926001600160a01b03169163de8fa4319160048083019260209291908290030181865afa158015612c93573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cb79190613194565b115b612d055760405162461bcd60e51b815260206004820152601f60248201527f4f6e6c79206f6e6520706f736974696f6e20696e207468652073797374656d006044820152606401610758565b50565b6001600160a01b0382166000908152600d602052604081206003015460ff1690816004811115612d3a57612d3a61302d565b14158015612d5a57506001816004811115612d5757612d5761302d565b14155b612d6657612d6661334c565b6001600160a01b0383166000908152600d602052604081206003015461010090046001600160801b0316908390612d9e60018361324f565b905080836001600160801b03161115612db957612db961334c565b6000600c8281548110612dce57612dce6132ff565b600091825260209091200154600c80546001600160a01b03909216925082916001600160801b038716908110612e0657612e066132ff565b600091825260208083209190910180546001600160a01b0319166001600160a01b03948516179055918316808252600d83526040918290206003018054610100600160881b0319166101006001600160801b038a16908102919091179091558251918252928101929092527f18866c04f256504f718fa0e2d2926b02c454fa1cabd9664493cc1389db93e5fb910160405180910390a1600c805480612ead57612ead61346e565b600082815260209020810160001990810180546001600160a01b031916905501905550505050505050565b6040518060a00160405280600081526020016000815260200160001515815260200160008152602001600081525090565b6040518061012001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6040518060e0016040528060008152602001600081526020016000815260200160006001600160a01b0316815260200160001515815260200160008152602001600081525090565b60405180606001604052806000815260200160008152602001600081525090565b6001600160a01b0381168114612d0557600080fd5b8035612fde81612fbe565b919050565b600060208284031215612ff557600080fd5b8135612c3781612fbe565b60006020828403121561301257600080fd5b5035919050565b6001600160a01b0391909116815260200190565b634e487b7160e01b600052602160045260246000fd5b858152602081018590526040810184905260a081016005841061307657634e487b7160e01b600052602160045260246000fd5b60608201939093526001600160801b03919091166080909101529392505050565b634e487b7160e01b600052604160045260246000fd5b600060208083850312156130c057600080fd5b82356001600160401b03808211156130d757600080fd5b818501915085601f8301126130eb57600080fd5b8135818111156130fd576130fd613097565b8060051b604051601f19603f8301168101818110858211171561312257613122613097565b60405291825284820192508381018501918883111561314057600080fd5b938501935b828510156131655761315685612fd3565b84529385019392850192613145565b98975050505050505050565b60006020828403121561318357600080fd5b815160ff81168114612c3757600080fd5b6000602082840312156131a657600080fd5b5051919050565b6001600160a01b0392909216825260ff16602082015260400190565b6020808252601490820152734e6f7468696e6720746f206c697175696461746560601b604082015260600190565b6001600160a01b0394909416845260ff9290921660208401526040830152606082015260800190565b6001600160a01b03929092168252602082015260400190565b634e487b7160e01b600052601160045260246000fd5b81810381811115611ee857611ee8613239565b93845260208401929092526040830152606082015260800190565b60008261329a57634e487b7160e01b600052601260045260246000fd5b500490565b8082028115828204841417611ee857611ee8613239565b6000602082840312156132c857600080fd5b8151612c3781612fbe565b6000600182016132e5576132e5613239565b5060010190565b80820180821115611ee857611ee8613239565b634e487b7160e01b600052603260045260246000fd5b928352602083019190915260ff16604082015260600190565b9384526020840192909252604083015260ff16606082015260800190565b634e487b7160e01b600052600160045260246000fd5b60ff8281168282160390811115611ee857611ee8613239565b600181815b808511156133b657816000190482111561339c5761339c613239565b808516156133a957918102915b93841c9390800290613380565b509250929050565b6000826133cd57506001611ee8565b816133da57506000611ee8565b81600181146133f057600281146133fa57613416565b6001915050611ee8565b60ff84111561340b5761340b613239565b50506001821b611ee8565b5060208310610133831016604e8410600b8410161715613439575081810a611ee8565b613443838361337b565b806000190482111561345757613457613239565b029392505050565b6000612c3760ff8416836133be565b634e487b7160e01b600052603160045260246000fdfe97cbd0b7198794c3ce3d682748bd80fde9867879dae3650f2e70dd2ed572ceb74152c73dd2614c4f9fc35e8c9cf16013cd588c75b49a4c1673ecffdcbcda94034fe7fb62190647b8a7596709832f68a365082b18206e55ae330b95593c369affa264697066735822122071c60c316ad44074472a354c9bab9ebe2f1f61639a2c89585cfaffe72fa79b2864736f6c6343000815003300000000000000000000000096a5399d07896f757bd4c6ef56461f58db951862000000000000000000000000ad29b3738ea37f1eb8a8f6745aeef51399fce57b000000000000000000000000ec8cedf0b25bb6b6de492b9ed702a76e0503af8e000000000000000000000000d6ae358f8bd4001e264d81020ddcb4eee794b15400000000000000000000000011be18370b2937e011fd5c853f5b9aeea797fd540000000000000000000000005f01015f80552397455deea35eea78e1b1f71bcc000000000000000000000000855866eaf136d942cf3e72be9ffdea66453d5ffe0000000000000000000000009d8c056e503bb5d1206c3aa36b71f3d15589962f000000000000000000000000ddf73eacb2218377fc38679ad14dfce51b651dd1000000000000000000000000be5ef1183732d374f2d4f229333eea9a0cd4f5b9000000000000000000000000e293dfd4720308c048b63afe885f5971e135eb1e0000000000000000000000001e7460c8527282fd15b4bc7bbc451cd20d95b14e

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106103f35760003560e01c806301ffc9a7146103f857806305618592146104205780630b076557146104375780630e55d5151461044c578063139f2e8c1461045f578063151535b91461046f5780631673c79a1461048257806318f2817a146104be5780631983fb40146104d15780631bf43555146104e45780631f68f20a146104f45780631faa3a65146104fc578063207ace811461050f578063248a9ca314610522578063257aa696146105355780632f2ff15d1461053d5780632f865568146105505780632f86e2dd14610563578063340c07801461057657806336568abe146105895780633cc742251461059c5780633cf1b05b146105bc578063432ddab9146105c45780634840fb37146105cd5780634a3c95c4146105d65780634ab77ab0146105e95780634e443d9e1461062e57806350b29ca514610641578063516eda3d1461064957806354e89adc146106725780635733d58f1461068557806358b8a5d61461068d578063598f54c9146106a05780635dba4c4a146106a85780635f94c327146106b057806369076788146106c35780636a593018146106d657806372fe25aa146106e9578063741bef1a146106f8578063758ab4001461070b57806375d54cb114610737578063794e57241461074a5780637e5b4c6d146107525780637f7dde4a146107655780637fa46ab414610778578063807d138d1461078d5780638200bfe6146107965780638697d4da146107a957806390b8b0c8146107bc57806391571384146107c457806391d14854146107d7578063927b26b9146107ea578063948ba6d2146107f357806396d711ff1461080657806396e620651461080f5780639eef064014610822578063a20baee6146106e9578063a217fddf14610835578063a22b7d681461083d578063a9d75b2b14610850578063acbb08e614610863578063accea38414610876578063ae3726ed14610889578063b0d8e18114610891578063b2016bd4146108a4578063b279906e146108b7578063b36cd07f146108ca578063b82f263d146108dd578063b91af97c146108f0578063bcd3752614610903578063bf88dd7114610916578063bf9befb11461096f578063c045e47d14610978578063c36069cc14610889578063c98eef621461098b578063c9fccede146109b7578063cb5f6240146109ca578063d293c710146109dd578063d347e07b146109f0578063d380a37c146109f9578063d38b055814610a01578063d547741f14610a0a578063d98d91d014610a1d578063e13d277114610a30578063e2ac77b014610a43578063ee266b8714610a56578063f05c7d8914610a5f578063fbf60d4a14610a72578063fe2ba84814610a7c575b600080fd5b61040b61040636600461543a565b610a8f565b60405190151581526020015b60405180910390f35b61042960185481565b604051908152602001610417565b61044a610445366004615479565b610ac6565b005b61044a61045a366004615479565b610aee565b610429680ad78ebc5ac620000081565b61040b61047d366004615479565b610aff565b6104a9610490366004615479565b600b602052600090815260409020805460019091015482565b60408051928352602083019190915201610417565b6104296104cc366004615479565b610b2b565b6104296104df366004615479565b610b3e565b610429686194049f30f720000081565b610429610b6e565b61040b61050a366004615479565b610c88565b61040b61051d366004615479565b610ca8565b610429610530366004615496565b610cdb565b610429610cf0565b61044a61054b3660046154af565b610cff565b61044a61055e366004615479565b610d4c565b61044a610571366004615479565b610db4565b61044a610584366004615496565b610dc7565b61044a6105973660046154af565b610e30565b6005546105af906001600160a01b031681565b60405161041791906154df565b600c54610429565b61042960165481565b61042960145481565b6104296105e4366004615479565b610e78565b61061e6105f7366004615479565b601b6020526000908152604090208054600182015460028301546003909301549192909184565b60405161041794939291906154f3565b61040b61063c366004615496565b610e83565b610429610e8e565b610429610657366004615479565b6001600160a01b03166000908152600d602052604090205490565b610429610680366004615479565b610e98565b610429610ea3565b61042961069b366004615496565b610f83565b61044a6110a0565b61044a6113f8565b6104296106be36600461550e565b6114fc565b6009546105af906001600160a01b031681565b6104296106e4366004615530565b611510565b610429670de0b6b3a764000081565b6003546105af906001600160a01b031681565b610429610719366004615479565b6001600160a01b03166000908152600d602052604090206001015490565b601a546105af906001600160a01b031681565b610429611568565b610429610760366004615530565b6115a9565b6004546105af906001600160a01b031681565b610429600080516020615dff83398151915281565b610429600f5481565b6006546105af906001600160a01b031681565b6019546105af906001600160a01b031681565b61040b6115fb565b6104296107d236600461550e565b611676565b61040b6107e53660046154af565b611684565b61042960155481565b610429610801366004615496565b6116af565b61042960105481565b61044a61081d366004615530565b6116c2565b61044a610830366004615496565b61171a565b610429600081565b61042961084b366004615496565b611a7e565b6002546105af906001600160a01b031681565b600a546105af906001600160a01b031681565b610429610884366004615479565b611a91565b610429611ab3565b61042961089f366004615479565b611ad5565b6007546105af906001600160a01b031681565b6105af6108c5366004615496565b611b73565b6104296108d8366004615496565b611ba3565b6104296108eb366004615496565b611cb9565b61061e6108fe366004615479565b611cc4565b61044a61091136600461555c565b611ce2565b61095e610924366004615479565b600d6020526000908152604090208054600182015460028301546003909301549192909160ff81169061010090046001600160801b031685565b6040516104179594939291906155e0565b610429600e5481565b6008546105af906001600160a01b031681565b610429610999366004615479565b6001600160a01b03166000908152600d602052604090206002015490565b6104296109c536600461550e565b6126b1565b6105af6109d8366004615496565b6126c5565b6104296109eb366004615530565b6126ef565b61042960125481565b6104296126fb565b61042960135481565b61044a610a183660046154af565b6127eb565b61044a610a2b3660046156a3565b612833565b610429610a3e366004615530565b6128fd565b61040b610a51366004615479565b61292b565b61042960115481565b610429610a6d366004615530565b61298e565b601854151561040b565b61044a610a8a366004615479565b6129bf565b60006001600160e01b03198216637965db0b60e01b1480610ac057506301ffc9a760e01b6001600160e01b03198316145b92915050565b610ace6129d0565b600454600554610aeb916001600160a01b03908116911683612a38565b50565b610af66129d0565b610aeb81612b40565b6000610b0c601854151590565b1580610ac05750610ac0600080516020615dff83398151915283611684565b6000610b356129d0565b610ac082612b6a565b6001600160a01b0381166000908152600d602052604081206003015460ff166004811115610ac057610ac06155ca565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bc4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be89190615754565b90506000816001811115610bfe57610bfe6155ca565b03610c8057600960009054906101000a90046001600160a01b03166001600160a01b031663b655d0c46040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c56573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c7a9190615775565b91505090565b505060155490565b6001600160a01b03166000908152601b6020526040902060010154151590565b6000610cb5601854151590565b8015610ac05750610cd4600080516020615dff83398151915233611684565b1592915050565b60009081526017602052604090206001015490565b6000610cfa612bfd565b905090565b610d098282611684565b158015610d235750600080516020615dff83398151915282145b15610d3e5760188054906000610d38836157a4565b91905055505b610d488282612ce0565b5050565b610d5581612cfc565b604080516001808252818301909252600091602080830190803683370190505090508181600081518110610d8b57610d8b6157bd565b60200260200101906001600160a01b031690816001600160a01b031681525050610d4881612833565b610dbc6129d0565b610aeb816002612d87565b610d4881604051602401610ddd91815260200190565b60408051601f19818403018152918152602080830180516001600160e01b03166268180f60e71b179052815160608101909252602880835290615e4c90830139601a546001600160a01b03169190612eab565b610e3a8282611684565b8015610e535750600080516020615dff83398151915282145b15610e6e5760188054906000610e68836157d3565b91905055505b610d488282612f23565b6000610ac082612f9d565b6000610ac08261304e565b6000610cfa613145565b6000610ac0826131f8565b60095460075460405163c3f82bc360e01b81526000926001600160a01b039081169263e0bbb60b92911690839063c3f82bc390610ee49030906004016154df565b602060405180830381865afa158015610f01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f259190615800565b6040518363ffffffff1660e01b8152600401610f4292919061581b565b602060405180830381865afa158015610f5f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cfa9190615775565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610fd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffd9190615754565b90506000816001811115611013576110136155ca565b036110945760095460408051632d95743160e21b8152905161108d926001600160a01b03169163b655d0c49160048083019260209291908290030181865afa158015611063573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110879190615775565b84613224565b9392505050565b61108d60155484613224565b600354604051636785806360e11b81526000916001600160a01b03169063cf0b00c6906110d7908490819081908190600401615837565b60408051808303816000875af11580156110f5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111199190615856565b5060095460075460405163c3f82bc360e01b81529293506000926001600160a01b039283169263368bceed921690839063c3f82bc39061115d9030906004016154df565b602060405180830381865afa15801561117a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119e9190615800565b6040518363ffffffff1660e01b81526004016111bb92919061581b565b602060405180830381865afa1580156111d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111fc9190615775565b905080611208836132a1565b1080611218575061121833610ca8565b61127c5760405162461bcd60e51b815260206004820152602a60248201527f544352206d7573742062652062656c6f77204d435220746f20656d657267656e6044820152696379206465717565756560b01b60648201526084015b60405180910390fd5b336000908152601b6020526040812060018101549091036112d65760405162461bcd60e51b8152602060048201526014602482015273139bc81c9959195b5c1d1a5bdb881c5d595d595960621b6044820152606401611273565b805460025460405163a9059cbb60e01b81526001600160a01b039091169063a9059cbb9061130a903390859060040161587a565b6020604051808303816000875af1158015611329573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061134d91906158a3565b6113925760405162461bcd60e51b815260206004820152601660248201527514dd18589b19481d1c985b9cd9995c8819985a5b195960521b6044820152606401611273565b336000818152601b6020526040808220828155600181018390556002810183905560030191909155517f7a5dd2b1e375db96da69d227292334441da925766453994078862d5cad386b24906113ea9084815260200190565b60405180910390a250505050565b6114006129d0565b60095460408051630f5114eb60e01b815290516000926001600160a01b031691630f5114eb9160048083019260209291908290030181865afa15801561144a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146e9190615754565b90506000816001811115611484576114846155ca565b036114f457600960009054906101000a90046001600160a01b03166001600160a01b0316635dba4c4a6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156114d957600080fd5b505af11580156114ed573d6000803e3d6000fd5b5050505050565b610aeb613344565b600061108d61150a836116af565b84613396565b600061151a6129d0565b6001600160a01b0383166000908152600d60205260408120600101546115419084906158be565b6001600160a01b0385166000908152600d6020526040902060010181905591505092915050565b60095460075460405163c3f82bc360e01b81526000926001600160a01b039081169263368bceed92911690839063c3f82bc390610ee49030906004016154df565b60006115b36129d0565b6001600160a01b0383166000908152600d60205260408120546115d79084906158be565b6001600160a01b0385166000908152600d6020526040902081905591505092915050565b600954600754604051631a36c27160e11b81523060048201526001600160a01b039182166024820152600092919091169063346d84e290604401602060405180830381865afa158015611652573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cfa91906158a3565b600061108d61150a83611ba3565b60009182526017602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6000610ac06116bc6133b5565b836134a5565b6116ca6129d0565b8060048111156116dc576116dc6155ca565b6001600160a01b0383166000908152600d60205260409020600301805460ff19166001836004811115611711576117116155ca565b02179055505050565b61172333610aff565b61173f5760405162461bcd60e51b8152600401611273906158d1565b6000811161175f5760405162461bcd60e51b81526004016112739061591b565b60095460405163c3f82bc360e01b81526000916001600160a01b03169063c3f82bc3906117909030906004016154df565b602060405180830381865afa1580156117ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d19190615800565b600954600754604051636975d4f160e11b81529293506001600160a01b039182169263d2eba9e292611809921690859060040161581b565b61012060405180830381865afa158015611827573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061184b919061595b565b50336000908152601b602052604090206001810154156118a95760405162461bcd60e51b8152602060048201526019602482015278149959195b5c1d1a5bdb88185b1c9958591e481c5d595d5959603a1b6044820152606401611273565b6009546007546040516307eb2c2560e41b81526000926001600160a01b0390811692637eb2c250926118e39290911690879060040161581b565b6060604051808303816000875af1158015611902573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119269190615a11565b505090506000811161198e5760405162461bcd60e51b815260206004820152602b60248201527f436f6f6c646f776e20726571756972656d656e74206d7573742062652067726560448201526a061746572207468616e20360ac1b6064820152608401611273565b600254604051630e0960cd60e31b81526001600160a01b039091169063704b0668906119c290339030908990600401615a3f565b600060405180830381600087803b1580156119dc57600080fd5b505af11580156119f0573d6000803e3d6000fd5b5050508483555042600183015560095460405163615c98e160e11b8152600481018690526001600160a01b039091169063c2b931c29060240160408051808303816000875af1158015611a47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a6b9190615856565b6003840155600290920191909155505050565b6000610ac0611a8b6133b5565b83613224565b6000611a9b6129d0565b611aa4826134e1565b6001600160801b031692915050565b611ac76103e8670de0b6b3a7640000615a79565b611ad2906005615a8d565b81565b6000806000611ae38461357a565b915091506000611b6a8383600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b41573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b659190615800565b6135f6565b95945050505050565b6000600c8281548110611b8857611b886157bd565b6000918252602090912001546001600160a01b031692915050565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bf9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1d9190615754565b90506000816001811115611c3357611c336155ca565b03611cad5760095460408051632d95743160e21b8152905161108d926001600160a01b03169163b655d0c49160048083019260209291908290030181865afa158015611c83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca79190615775565b846134a5565b61108d601554846134a5565b6000610ac0826132a1565b600080600080611cd385613638565b93509350935093509193509193565b611ceb33610aff565b611d075760405162461bcd60e51b8152600401611273906158d1565b611d0f61534e565b6040805160c081018252600480546001600160a01b039081168352600554811660208401526002548116838501526019548116606084015260085481166080840152600a54811660a0840152600954935163c3f82bc360e01b81529293169163c3f82bc391611d80913091016154df565b602060405180830381865afa158015611d9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dc19190615800565b60ff16610220830181905261014083018490526009546007546040516307eb2c2560e41b81526001600160a01b0392831693637eb2c25093611e0793169160040161581b565b6060604051808303816000875af1158015611e26573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e4a9190615a11565b610240850181905261020085018290526101e08501839052611e6f9284928d92613690565b1580156101c08701526101208601919091526101008501919091526101a0840191909152611e9e5750506126a8565b611eac826101a00151613794565b600354610120830151610100840151604051636785806360e11b81526001600160a01b039093169263cf0b00c692611eed9290916001908190600401615837565b60408051808303816000875af1158015611f0b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f2f9190615856565b610160840181905260c0840191909152610140830151611f4e916137b4565b60095460075461022084015160405163368bceed60e01b81526000936001600160a01b039081169363368bceed93611f8d93929091169160040161581b565b602060405180830381865afa158015611faa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fce9190615775565b9050611fde8360c001518261395a565b600260009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612031573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120559190615775565b60e0840181905260408084015190516370a0823160e01b81526001600160a01b03909116906370a082319061208e9033906004016154df565b602060405180830381865afa1580156120ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120cf9190615775565b11156120dd576120dd615aa4565b6101a08301518352608082015160c08401516000916120fe918c90856139b1565b1561210a575088612214565b82608001516001600160a01b0316634d6228316040518163ffffffff1660e01b8152600401602060405180830381865afa15801561214c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121709190615aba565b90505b6001600160a01b03811615801590612197575081612195828660c001516126ef565b105b156122145782608001516001600160a01b031663b72703ac826040518263ffffffff1660e01b81526004016121cc91906154df565b602060405180830381865afa1580156121e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061220d9190615aba565b9050612173565b856000036122225760001995505b60016102608501525b6001600160a01b038116158015906122435750835115155b801561224f5750600086115b1561236d578561225e816157d3565b965050600083608001516001600160a01b031663b72703ac836040518263ffffffff1660e01b815260040161229391906154df565b602060405180830381865afa1580156122b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122d49190615aba565b90506122e98460000151856020015184612a38565b6000612308858488600001518960c001518f8f8f8d6102600151613aec565b600061026088015260408101519091501561232457505061236d565b805160208701516123359190615ad7565b60208088019190915281015160408701516123509190615ad7565b60408701528051865161236391906158be565b865250905061222b565b60008460400151116123bf5760405162461bcd60e51b815260206004820152601b60248201527a155b98589b19481d1bc81c995919595b48185b9e48185b5bdd5b9d602a1b6044820152606401611273565b6101e0840151156123d55783516123d590613c05565b6123ec84604001518560c001518660e00151613cd7565b506124008460400151856101600151613dfc565b60608501819052604085015161014086015161241d929190613e0a565b825160608085015190860151604051636250216960e01b81526001600160a01b039093169263625021699261245692909160040161587a565b600060405180830381600087803b15801561247057600080fd5b505af1158015612484573d6000803e3d6000fd5b505050506060838101516007546102208701519287015160405163184cbcb360e11b81526001600160a01b03928316600482015260ff909416602485015260448401521690633099796690606401600060405180830381600087803b1580156124ec57600080fd5b505af1158015612500573d6000803e3d6000fd5b5050506060850151604086015161251792506158be565b60808501526101a08401516020850151604080870151606088015191517f43a3f4082a4dbc33d78e317d2497d3a730bc7fc3574159dcea1056e62e5d9ad8946125649490939092916154f3565b60405180910390a182604001516001600160a01b0316639dc29fac3386602001516040518363ffffffff1660e01b81526004016125a292919061587a565b600060405180830381600087803b1580156125bc57600080fd5b505af11580156125d0573d6000803e3d6000fd5b5050845160208701516040516302038d2560e11b81526001600160a01b0390921693506304071a4a925061260a9160040190815260200190565b600060405180830381600087803b15801561262457600080fd5b505af1158015612638573d6000803e3d6000fd5b505084516080870151604051636250216960e01b81526001600160a01b039092169350636250216992506126719133919060040161587a565b600060405180830381600087803b15801561268b57600080fd5b505af115801561269f573d6000803e3d6000fd5b50505050505050505b50505050505050565b600061108d6126bf83611a7e565b84613e6a565b600c81815481106126d557600080fd5b6000918252602090912001546001600160a01b0316905081565b600061108d8383613eec565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612751573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127759190615754565b9050600081600181111561278b5761278b6155ca565b036127e357600960009054906101000a90046001600160a01b03166001600160a01b031663bc8ec9e36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c56573d6000803e3d6000fd5b505060165490565b6127f58282611684565b801561280e5750600080516020615dff83398151915282145b156128295760188054906000612823836157d3565b91905055505b610d488282613f59565b80516000036128955760405162461bcd60e51b815260206004820152602860248201527f43616c6c646174612061646472657373206172726179206d757374206e6f7420604482015267626520656d70747960c01b6064820152608401611273565b610d48816040516024016128a99190615aea565b60408051601f19818403018152918152602080830180516001600160e01b0316630d98d91d60e41b179052815160608101909252602d80835290615e1f90830139601a546001600160a01b03169190612eab565b60006129076129d0565b6001600160a01b0383166000908152600d60205260408120546115d7908490615ad7565b600060016001600160a01b0383166000908152600d602052604090206003015460ff16600481111561295f5761295f6155ca565b1461296c57506000919050565b506011546001600160a01b039091166000908152600b60205260409020541090565b60006129986129d0565b6001600160a01b0383166000908152600d6020526040812060010154611541908490615ad7565b6129c76129d0565b610aeb81613f75565b6000546001600160a01b03163314612a365760405162461bcd60e51b8152602060048201526024808201527f43616c6c6572206973206e6f742074686520506f736974696f6e436f6e74726f604482015263363632b960e11b6064820152608401611273565b565b612a418161292b565b15612b3b57612a4f81612cfc565b6000612a5a82610e78565b90506000612a6783610e98565b6001600160a01b0384166000908152600d6020526040902060010154909150612a91908390615ad7565b6001600160a01b0384166000908152600d60205260409020600181019190915554612abd908290615ad7565b6001600160a01b0384166000908152600d6020526040902055612adf83612b40565b612aeb85858385613fe3565b6001600160a01b0383166000818152600d6020526040808220805460018201546002909201549251600080516020615ddf83398151915294612b309492939291615b37565b60405180910390a250505b505050565b6011546001600160a01b039091166000908152600b60205260409020908155601254600190910155565b6001600160a01b0381166000908152600d60205260408120600101548190612b91906140f8565b6001600160a01b0384166000908152600d60205260409020600201805490829055600e54919250908290612bc69083906158be565b612bd09190615ad7565b600e819055604051908152600080516020615dbf8339815191529060200160405180910390a15092915050565b60055460408051635c1548fb60e01b815290516000926001600160a01b031691635c1548fb9160048083019260209291908290030181865afa158015612c47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6b9190615775565b6004805460408051635c1548fb60e01b815290516001600160a01b0390921692635c1548fb9282820192602092908290030181865afa158015612cb2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cd69190615775565b610cfa9190615ad7565b612ce982610cdb565b612cf28161412e565b612b3b8383614138565b60016001600160a01b0382166000908152600d602052604090206003015460ff166004811115612d2e57612d2e6155ca565b14610aeb5760405162461bcd60e51b8152602060048201526024808201527f506f736974696f6e20646f6573206e6f74206578697374206f7220697320636c6044820152631bdcd95960e21b6064820152608401611273565b6000816004811115612d9b57612d9b6155ca565b14158015612dbb57506001816004811115612db857612db86155ca565b14155b612dc757612dc7615aa4565b600c54612dd3816141be565b6001600160a01b0383166000908152600d60205260409020600301805483919060ff19166001836004811115612e0b57612e0b6155ca565b02179055506001600160a01b0383166000908152600d60209081526040808320600180820185905590849055600b90925282208281550155612e4d8382614285565b600854604051631484968760e11b81526001600160a01b03909116906329092d0e90612e7d9086906004016154df565b600060405180830381600087803b158015612e9757600080fd5b505af11580156126a8573d6000803e3d6000fd5b6060600080856001600160a01b031685604051612ec89190615b79565b600060405180830381855af49150503d8060008114612f03576040519150601f19603f3d011682016040523d82523d6000602084013e612f08565b606091505b5091509150612f1986838387614455565b9695505050505050565b6001600160a01b0381163314612f935760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b6064820152608401611273565b610d4882826144ce565b6001600160a01b0381166000908152600b60205260408120546011548290612fc69083906158be565b9050801580613005575060016001600160a01b0385166000908152600d602052604090206003015460ff166004811115613002576130026155ca565b14155b15613014575060009392505050565b6001600160a01b0384166000908152600d602052604081206002015490670de0b6b3a76400006130448484615a8d565b612f199190615a79565b60095460075460405163c3f82bc360e01b815260009283926001600160a01b039182169263e0bbb60b9290911690839063c3f82bc3906130929030906004016154df565b602060405180830381865afa1580156130af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130d39190615800565b6040518363ffffffff1660e01b81526004016130f092919061581b565b602060405180830381865afa15801561310d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131319190615775565b90508061313d846132a1565b109392505050565b6005546040805162fcf9d160e11b815290516000926001600160a01b0316916301f9f3a29160048083019260209291908290030181865afa15801561318e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131b29190615775565b600480546040805162fcf9d160e11b815290516001600160a01b03909216926301f9f3a29282820192602092908290030181865afa158015612cb2573d6000803e3d6000fd5b6001600160a01b0381166000908152600b60205260408120600101546012548290612fc69083906158be565b60095460075460405163730a02b960e11b81526000926001600160a01b039081169263e614057292613260929091169087908790600401615b95565b602060405180830381865afa15801561327d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061108d9190615775565b6000806132ac612bfd565b905060006132b8613145565b905061333c828286600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613313573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133379190615800565b614535565b949350505050565b600061334e614561565b9050670de0b6b3a764000081111561336857613368615aa4565b6015819055604051818152600080516020615e748339815191529060200160405180910390a1610aeb6145ac565b6000670de0b6b3a76400006133ab8385615a8d565b61108d9190615a79565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561340b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061342f9190615754565b90506000816001811115613445576134456155ca565b0361349d57600960009054906101000a90046001600160a01b03166001600160a01b031663459799786040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c56573d6000803e3d6000fd5b610c7a614561565b600954600754604051633a60466f60e01b81526000926001600160a01b0390811692633a60466f92613260929091169087908790600401615b95565b600c80546001808201835560008381527fdf6966c971051c3d54ec59162606531493a51404a002842f56009d7e5cf4a8c790920180546001600160a01b0319166001600160a01b0386161790559154909161353b916158be565b6001600160a01b03929092166000908152600d602052604090206003018054610100600160881b0319166101006001600160801b038516021790555090565b600080600061358884612f9d565b90506000613595856131f8565b6001600160a01b0386166000908152600d6020526040812060010154919250906135c0908490615ad7565b6001600160a01b0387166000908152600d6020526040812054919250906135e8908490615ad7565b919791965090945050505050565b6000821561362f576136088483614615565b93508261361e68056bc75e2d6310000086615a8d565b6136289190615a79565b905061108d565b5060001961108d565b6001600160a01b0381166000908152600d602052604081208054600190910154909180613664856131f8565b915061366f85612f9d565b905061367b8285615ad7565b93506136878184615ad7565b92509193509193565b600080808086156136d6576136a688888861467d565b60408d0151939750919550935091506136c09033866148b6565b80156136d1576136d18985876149a4565b613788565b6136df33610c88565b156136fe576136ec614ab8565b50600092508291508190506001613788565b60009050879350613714896040015133866148b6565b60095460405163615c98e160e11b8152600481018690526001600160a01b039091169063c2b931c29060240160408051808303816000875af115801561375e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137829190615856565b90935091505b95509550955095915050565b60008111610aeb5760405162461bcd60e51b81526004016112739061591b565b60095460405163c3f82bc360e01b81526000916001600160a01b03169063c3f82bc3906137e59030906004016154df565b602060405180830381865afa158015613802573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138269190615800565b600954600754604051633697f68360e21b81529293506000926001600160a01b039283169263da5fda0c9261386292911690869060040161581b565b602060405180830381865afa15801561387f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138a39190615775565b9050826138ce6138bd6103e8670de0b6b3a7640000615a79565b6138c8906005615a8d565b83614bb5565b6138d89190615ad7565b84101580156138ef5750670de0b6b3a76400008411155b6139545760405162461bcd60e51b815260206004820152603060248201527f4d6178206665652070657263656e74616765206d75737420626520626574776560448201526f656e20302e352520616e64203130302560801b6064820152608401611273565b50505050565b80613964836132a1565b1015610d485760405162461bcd60e51b815260206004820152601c60248201527b21b0b73737ba103932b232b2b6903bb432b7102a21a9101e1026a1a960211b6044820152606401611273565b60006001600160a01b0384161580613a335750604051630bb7c8fd60e31b81526001600160a01b03861690635dbe47e8906139f09087906004016154df565b602060405180830381865afa158015613a0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a3191906158a3565b155b80613a46575081613a4485856126ef565b105b15613a535750600061333c565b60405163765e015960e01b81526000906001600160a01b0387169063765e015990613a829088906004016154df565b602060405180830381865afa158015613a9f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ac39190615aba565b90506001600160a01b0381161580612f19575082613ae182866126ef565b109695505050505050565b613af4615417565b6001600160a01b0388166000908152600d6020526040902054613b2c908890613b2790680ad78ebc5ac6200000906158be565b614bcc565b8082528690613b4490670de0b6b3a764000090615a8d565b613b4e9190615a79565b60208083019190915281516001600160a01b038a166000908152600d9092526040822054613b7c91906158be565b6020808401516001600160a01b038c166000908152600d90925260408220600101549293509091613bad91906158be565b9050680ad78ebc5ac62000008203613bd957613bd48b8b680ad78ebc5ac620000084614bdb565b613bf7565b613bf4838c8c8a8a8a8888680ad78ebc5ac62000008d614c2a565b92505b505098975050505050505050565b336000908152601b6020526040902081158015613c2157508054155b15613c4e57336000908152601b602052604081208181556001810182905560028101829055600301555050565b8115610d4857600254604051630e0960cd60e31b81526001600160a01b039091169063704b066890613c8890339030908790600401615a3f565b600060405180830381600087803b158015613ca257600080fd5b505af1158015613cb6573d6000803e3d6000fd5b5050505081816000016000828254613cce9190615ad7565b90915550505050565b600080600960009054906101000a90046001600160a01b03166001600160a01b0316630f5114eb6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613d2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d519190615754565b90506000816001811115613d6757613d676155ca565b03613df157600954604051633f0486c160e21b81526004810187905260248101869052604481018590526001600160a01b039091169063fc121b04906064016020604051808303816000875af1158015613dc5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613de99190615775565b91505061108d565b613de9858585614dc9565b600061108d6126bf83610f83565b600082613e1f670de0b6b3a764000086615a8d565b613e299190615a79565b9050818111156139545760405162461bcd60e51b815260206004820152600c60248201526b11995948195e18d95959195960a21b6044820152606401611273565b600080670de0b6b3a7640000613e808486615a8d565b613e8a9190615a79565b905082811061108d5760405162461bcd60e51b815260206004820152602860248201527f46656520776f756c642065617420757020616c6c2072657475726e656420636f6044820152671b1b185d195c985b60c21b6064820152608401611273565b6000806000613efa8561357a565b915091506000612f19838387600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015613313573d6000803e3d6000fd5b613f6282610cdb565b613f6b8161412e565b612b3b83836144ce565b6001600160a01b0381166000908152600d6020526040902060020154600e54613f9f9082906158be565b600e819055604051908152600080516020615dbf8339815191529060200160405180910390a1506001600160a01b03166000908152600d6020526040812060020155565b6040516302038d2560e11b8152600481018390526001600160a01b038416906304071a4a90602401600060405180830381600087803b15801561402557600080fd5b505af1158015614039573d6000803e3d6000fd5b5050604051634ba6322b60e11b8152600481018590526001600160a01b038716925063974c64569150602401600060405180830381600087803b15801561407f57600080fd5b505af1158015614093573d6000803e3d6000fd5b5050604051633ef8ba8160e11b8152600481018490526001600160a01b0386169250637df1750291506024015b600060405180830381600087803b1580156140da57600080fd5b505af11580156140ee573d6000803e3d6000fd5b5050505050505050565b60008060105460000361410c575081610ac0565b6000600f541161411e5761411e615aa4565b601054600f546133ab9085615a8d565b610aeb8133614e5a565b6141428282611684565b610d485760008281526017602090815260408083206001600160a01b03851684529091529020805460ff1916600117905561417a3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60018111801561423957506008546040805163de8fa43160e01b815290516001926001600160a01b03169163de8fa4319160048083019260209291908290030181865afa158015614213573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906142379190615775565b115b610aeb5760405162461bcd60e51b815260206004820152601f60248201527f4f6e6c79206f6e6520706f736974696f6e20696e207468652073797374656d006044820152606401611273565b6001600160a01b0382166000908152600d602052604081206003015460ff16908160048111156142b7576142b76155ca565b141580156142d7575060018160048111156142d4576142d46155ca565b14155b6142e3576142e3615aa4565b6001600160a01b0383166000908152600d602052604081206003015461010090046001600160801b031690839061431b6001836158be565b905080836001600160801b0316111561433657614336615aa4565b6000600c828154811061434b5761434b6157bd565b600091825260209091200154600c80546001600160a01b03909216925082916001600160801b038716908110614383576143836157bd565b600091825260208083209190910180546001600160a01b0319166001600160a01b03948516179055918316808252600d83526040918290206003018054610100600160881b0319166101006001600160801b038a16908102919091179091558251918252928101929092527f18866c04f256504f718fa0e2d2926b02c454fa1cabd9664493cc1389db93e5fb910160405180910390a1600c80548061442a5761442a615bb6565b600082815260209020810160001990810180546001600160a01b031916905501905550505050505050565b606083156144c45782516000036144bd576001600160a01b0385163b6144bd5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611273565b508161333c565b61333c8383614eb3565b6144d88282611684565b15610d485760008281526017602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b600083600003614548575060001961333c565b6145528583614615565b94506000846130448588615a8d565b60008061456c614edd565b90506000614582670ddd4b8c6c7d70d883614ef9565b9050670de0b6b3a76400008160155461459b9190615a8d565b6145a59190615a79565b9250505090565b60006145b6614edd565b90508015610aeb576145c9603c82615a8d565b601660008282546145da9190615ad7565b90915550506040514281527f860f8d2f0c74dd487e89e2883e3b25b8159ce1e1b3433a291cba7b82c508f3bc9060200160405180910390a150565b600060128260ff16101561464a5761462e826012615bcc565b61463990600a615cc9565b6146439084615a8d565b9050610ac0565b60128260ff16111561467657614661601283615bcc565b61466c90600a615cc9565b6146439084615a79565b5081610ac0565b336000908152601b6020526040812060018101548291829182919082036146de5760405162461bcd60e51b8152602060048201526015602482015274149959195b5c1d1a5bdb881b9bdd081c5d595d5959605a1b6044820152606401611273565b805488111561474a5760405162461bcd60e51b815260206004820152603260248201527f43616e6e6f742072656465656d206d6f7265207468616e2072656d61696e696e604482015271672071756575656420696e20657363726f7760701b6064820152608401611273565b600087826001015461475c9190615ad7565b9050600061476a8883615ad7565b6002840154600385015490975095509050428111801561480b57428311156147e55760405162461bcd60e51b815260206004820152602860248201527f526564656d7074696f6e20657363726f772074696d656c6f636b206e6f742073604482015267185d1a5cd99a595960c21b6064820152608401611273565b600094508a97508784600001600082825461480091906158be565b909155506148189050565b8354600085559750600194505b60025460405163a9059cbb60e01b81526001600160a01b039091169063a9059cbb9061484a9033908c9060040161587a565b6020604051808303816000875af1158015614869573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061488d91906158a3565b6148a95760405162461bcd60e51b815260040161127390615cd8565b5050505093509350935093565b6040516370a0823160e01b815281906001600160a01b038516906370a08231906148e49086906004016154df565b602060405180830381865afa158015614901573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906149259190615775565b1015612b3b5760405162461bcd60e51b815260206004820152604260248201527f52657175657374656420726564656d7074696f6e20616d6f756e74206d75737460448201527f206265203c3d2075736572277320737461626c6520746f6b656e2062616c616e606482015261636560f01b608482015260a401611273565b6000670de0b6b3a76400006149b98484615a8d565b6149c39190615a79565b6060850151604051636fd32add60e01b8152600481018390529192506001600160a01b031690636fd32add90602401600060405180830381600087803b158015614a0c57600080fd5b505af1158015614a20573d6000803e3d6000fd5b5050505083604001516001600160a01b031663704b0668338660600151846040518463ffffffff1660e01b8152600401614a5c93929190615a3f565b600060405180830381600087803b158015614a7657600080fd5b505af1158015614a8a573d6000803e3d6000fd5b5050336000908152601b60205260408120818155600181018290556002810182905560030155505050505050565b336000908152601b6020908152604091829020825160808101845281548152600182015492810183905260028201549381019390935260030154606083015215610aeb57600254815160405163a9059cbb60e01b81526001600160a01b039092169163a9059cbb91614b2f9133919060040161587a565b6020604051808303816000875af1158015614b4e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614b7291906158a3565b614b8e5760405162461bcd60e51b815260040161127390615cd8565b336000908152601b6020526040812081815560018101829055600281018290556003015550565b600081831015614bc5578161108d565b5090919050565b6000818310614bc5578161108d565b614be483613f75565b614bef836004612d87565b614bfb84848484614fa4565b6001600160a01b038316600080516020615ddf8339815191526000808060036040516113ea9493929190615b37565b614c32615417565b6000614c8c8587600760009054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b41573d6000803e3d6000fd5b9050686194049f30f7200000614ca285886158be565b1080614cb75750868114158015614cb7575082155b15614ccb575050600160408b015289614dbb565b60808b015160405163015f109360e51b81526001600160a01b038c81166004830152602482018490528b811660448301528a8116606483015290911690632be2126090608401600060405180830381600087803b158015614d2b57600080fd5b505af1158015614d3f573d6000803e3d6000fd5b5050506001600160a01b038b166000908152600d6020526040902087815560010186905550614d6d8a612b6a565b506001600160a01b038a166000818152600d602052604090819020600201549051600080516020615ddf83398151915291614dae918a918a91600390615b37565b60405180910390a28b9150505b9a9950505050505050505050565b600080614dd4614561565b9050600083614de38688615a8d565b614ded9190615a79565b90506000614dfc600283615a79565b614e069084615ad7565b9050614e1a81670de0b6b3a7640000614bcc565b905060008111614e2c57614e2c615aa4565b6015819055604051818152600080516020615e748339815191529060200160405180910390a1612f196145ac565b614e648282611684565b610d4857614e718161516a565b614e7c83602061517c565b604051602001614e8d929190615d08565b60408051601f198184030181529082905262461bcd60e51b825261127391600401615d77565b815115614ec35781518083602001fd5b8060405162461bcd60e51b81526004016112739190615d77565b6000603c60165442614eef91906158be565b610cfa9190615a79565b6000631f540500821115614f0f57631f54050091505b81600003614f265750670de0b6b3a7640000610ac0565b670de0b6b3a764000083835b6001811115614f9a57614f46600282615daa565b600003614f6b57614f578283615317565b9150614f64600282615a79565b9050614f32565b614f758284615317565b9250614f818283615317565b91506002614f906001836158be565b614f649190615a79565b612f198284615317565b600254600154604051632770a7eb60e21b81526001600160a01b0392831692639dc29fac92614fda92911690869060040161587a565b600060405180830381600087803b158015614ff457600080fd5b505af1158015615008573d6000803e3d6000fd5b505085516040516302038d2560e11b8152600481018690526001600160a01b0390911692506304071a4a9150602401600060405180830381600087803b15801561505157600080fd5b505af1158015615065573d6000803e3d6000fd5b505050508360a001516001600160a01b0316633f10abab84836040518363ffffffff1660e01b815260040161509b92919061587a565b600060405180830381600087803b1580156150b557600080fd5b505af11580156150c9573d6000803e3d6000fd5b5050855160a0870151604051636250216960e01b81526001600160a01b0390921693506362502169925061510191859060040161587a565b600060405180830381600087803b15801561511b57600080fd5b505af115801561512f573d6000803e3d6000fd5b50505060a08501516007546040516302e3067760e21b81526001600160a01b039283169350630b8c19dc926140c0921690859060040161587a565b6060610ac06001600160a01b03831660145b6060600061518b836002615a8d565b615196906002615ad7565b6001600160401b038111156151ad576151ad615634565b6040519080825280601f01601f1916602001820160405280156151d7576020820181803683370190505b509050600360fc1b816000815181106151f2576151f26157bd565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110615221576152216157bd565b60200101906001600160f81b031916908160001a9053506000615245846002615a8d565b615250906001615ad7565b90505b60018111156152c8576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110615284576152846157bd565b1a60f81b82828151811061529a5761529a6157bd565b60200101906001600160f81b031916908160001a90535060049490941c936152c1816157d3565b9050615253565b50831561108d5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401611273565b6000806153248385615a8d565b9050670de0b6b3a764000061533a600282615a79565b6153449083615ad7565b61333c9190615a79565b6040518061028001604052806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016153d96040518060800160405280600081526020016000815260200160008152602001600081525090565b8152602001600081526020016000151581526020016000815260200160008152602001600060ff168152602001600081526020016000151581525090565b604051806060016040528060008152602001600081526020016000151581525090565b60006020828403121561544c57600080fd5b81356001600160e01b03198116811461108d57600080fd5b6001600160a01b0381168114610aeb57600080fd5b60006020828403121561548b57600080fd5b813561108d81615464565b6000602082840312156154a857600080fd5b5035919050565b600080604083850312156154c257600080fd5b8235915060208301356154d481615464565b809150509250929050565b6001600160a01b0391909116815260200190565b93845260208401929092526040830152606082015260800190565b6000806040838503121561552157600080fd5b50508035926020909101359150565b6000806040838503121561554357600080fd5b823561554e81615464565b946020939093013593505050565b600080600080600080600060e0888a03121561557757600080fd5b87359650602088013561558981615464565b9550604088013561559981615464565b945060608801356155a981615464565b9699959850939660808101359560a0820135955060c0909101359350915050565b634e487b7160e01b600052602160045260246000fd5b858152602081018590526040810184905260a081016005841061561357634e487b7160e01b600052602160045260246000fd5b60608201939093526001600160801b03919091166080909101529392505050565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b038111828210171561566d5761566d615634565b60405290565b604051601f8201601f191681016001600160401b038111828210171561569b5761569b615634565b604052919050565b600060208083850312156156b657600080fd5b82356001600160401b03808211156156cd57600080fd5b818501915085601f8301126156e157600080fd5b8135818111156156f3576156f3615634565b8060051b9150615704848301615673565b818152918301840191848101908884111561571e57600080fd5b938501935b83851015615748578435925061573883615464565b8282529385019390850190615723565b98975050505050505050565b60006020828403121561576657600080fd5b81516002811061108d57600080fd5b60006020828403121561578757600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b6000600182016157b6576157b661578e565b5060010190565b634e487b7160e01b600052603260045260246000fd5b6000816157e2576157e261578e565b506000190190565b805160ff811681146157fb57600080fd5b919050565b60006020828403121561581257600080fd5b61108d826157ea565b6001600160a01b0392909216825260ff16602082015260400190565b9384526020840192909252151560408301521515606082015260800190565b6000806040838503121561586957600080fd5b505080516020909101519092909150565b6001600160a01b03929092168252602082015260400190565b805180151581146157fb57600080fd5b6000602082840312156158b557600080fd5b61108d82615893565b81810381811115610ac057610ac061578e565b6020808252602a908201527f43616c6c657220646f6573206e6f74206861766520726564656d7074696f6e2060408201526970726976696c6567657360b01b606082015260800190565b6020808252818101527f416d6f756e74206d7573742062652067726561746572207468616e207a65726f604082015260600190565b80516157fb81615464565b6000610120828403121561596e57600080fd5b61597661564a565b61597f836157ea565b815261598d60208401615950565b602082015261599e60408401615950565b60408201526159af60608401615950565b60608201526159c060808401615950565b60808201526159d160a08401615950565b60a08201526159e260c08401615950565b60c08201526159f360e08401615950565b60e0820152610100615a06818501615893565b908201529392505050565b600080600060608486031215615a2657600080fd5b8351925060208401519150604084015190509250925092565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b600052601260045260246000fd5b600082615a8857615a88615a63565b500490565b8082028115828204841417610ac057610ac061578e565b634e487b7160e01b600052600160045260246000fd5b600060208284031215615acc57600080fd5b815161108d81615464565b80820180821115610ac057610ac061578e565b6020808252825182820181905260009190848201906040850190845b81811015615b2b5783516001600160a01b031683529284019291840191600101615b06565b50909695505050505050565b9384526020840192909252604083015260ff16606082015260800190565b60005b83811015615b70578181015183820152602001615b58565b50506000910152565b60008251615b8b818460208701615b55565b9190910192915050565b6001600160a01b039390931683526020830191909152604082015260600190565b634e487b7160e01b600052603160045260246000fd5b60ff8281168282160390811115610ac057610ac061578e565b600181815b80851115615c20578160001904821115615c0657615c0661578e565b80851615615c1357918102915b93841c9390800290615bea565b509250929050565b600082615c3757506001610ac0565b81615c4457506000610ac0565b8160018114615c5a5760028114615c6457615c80565b6001915050610ac0565b60ff841115615c7557615c7561578e565b50506001821b610ac0565b5060208310610133831016604e8410600b8410161715615ca3575081810a610ac0565b615cad8383615be5565b8060001904821115615cc157615cc161578e565b029392505050565b600061108d60ff841683615c28565b6020808252601690820152751cdd18589b19481d1c985b9cd9995c8819985a5b195960521b604082015260600190565b76020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b815260008351615d3a816017850160208801615b55565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351615d6b816028840160208801615b55565b01602801949350505050565b6020815260008251806020840152615d96816040850160208701615b55565b601f01601f19169190910160400192915050565b600082615db957615db9615a63565b50069056fe54edc0b4728c3923cb75a7e36b998c5eb1c6ca744db9015f495191569e0421d04fe7fb62190647b8a7596709832f68a365082b18206e55ae330b95593c369aff44ac9762eec3a11893fefb11d028bb3102560094137c3ed4518712475b2577cc62617463684c6971756964617465506f736974696f6e733a2064656c65676174652063616c6c206661696c65646c6971756964617465506f736974696f6e733a2064656c65676174652063616c6c206661696c6564c454ee9b76c52f782a256af821b857ca6e125d1e3333bcede402fec2bed9600ca2646970667358221220ef82721b49fb2a3e1462976a0c5f7b87b554cb4e3581f89c1997f26c6f68ea7464736f6c63430008150033

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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