ETH Price: $2,944.76 (-4.00%)
Gas: 2 Gwei

Contract

0xF6374AEfb1e69a21ee516ea4B803b2eA96d06f29
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Value
Set Addresses184248172023-10-25 4:15:23256 days ago1698207323IN
Threshold Network : Stability Pool
0 ETH0.0024832111.43672835
0x60806040184246292023-10-25 3:37:35256 days ago1698205055IN
 Contract Creation
0 ETH0.039169715.0234718

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

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

Contract Name:
StabilityPool

Compiler Version
v0.8.17+commit.8df45f5f

Optimization Enabled:
Yes with 100 runs

Other Settings:
default evmVersion
File 1 of 24 : StabilityPool.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import './Interfaces/IBorrowerOperations.sol';
import './Interfaces/IStabilityPool.sol';
import './Interfaces/IBorrowerOperations.sol';
import './Interfaces/ITroveManager.sol';
import './Interfaces/ITHUSDToken.sol';
import './Interfaces/ISortedTroves.sol';
import "./Dependencies/LiquityBase.sol";
import "./Dependencies/Ownable.sol";
import "./Dependencies/CheckContract.sol";
import "./Dependencies/SendCollateral.sol";

/*
 * The Stability Pool holds THUSD tokens deposited by Stability Pool depositors.
 *
 * When a trove is liquidated, then depending on system conditions, some of its THUSD debt gets offset with
 * THUSD in the Stability Pool:  that is, the offset debt evaporates, and an equal amount of THUSD tokens in the Stability Pool is burned.
 *
 * Thus, a liquidation causes each depositor to receive a THUSD loss, in proportion to their deposit as a share of total deposits.
 * They also receive a collateral gain, as the collateral of the liquidated trove is distributed among Stability depositors,
 * in the same proportion.
 *
 * When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
 * of the total THUSD in the Stability Pool, depletes 40% of each deposit.
 *
 * A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
 * multiplying it by some factor in range ]0,1[
 *
 *
 * --- IMPLEMENTATION ---
 *
 * We use a highly scalable method of tracking deposits and collateral gains that has O(1) complexity.
 *
 * When a liquidation occurs, rather than updating each depositor's deposit and collateral gain, we simply update two state variables:
 * a product P, and a sum S.
 *
 * A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits
 * and accumulated collateral gains over time, as liquidations occur, using just these two variables P and S. When depositors join the
 * Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively.
 *
 * The formula for a depositor's accumulated collateral gain is derived here:
 * https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf
 *
 * For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool,
 * and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated collateral gain.
 *
 * Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding collateral gain
 * can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S.
 *
 * Any time a depositor updates their deposit (withdrawal, top-up) their accumulated collateral gain is paid out, their new deposit is recorded
 * (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S.
 * Essentially, they make a fresh deposit that overwrites the old one.
 *
 *
 * --- SCALE FACTOR ---
 *
 * Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[.
 * Unfortunately, Solidity floor division always reaches 0, sooner or later.
 *
 * A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P
 * to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking.
 *
 * So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity),
 * we first multiply P by 1e9, and increment a currentScale factor by 1.
 *
 * The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the
 * scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the
 * order of 1e-9.
 *
 * --- EPOCHS ---
 *
 * Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0
 * forever, and break all future reward calculations.
 *
 * So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1.
 *
 * --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS ---
 *
 * When a deposit is made, it gets snapshots of the currentEpoch and the currentScale.
 *
 * When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer,
 * then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0.
 *
 * Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t.
 * If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit
 * as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion THUSD has depleted to < 1 THUSD).
 *
 *
 *  --- TRACKING DEPOSITOR'S collateral GAIN OVER SCALE CHANGES AND EPOCHS ---
 *
 * In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch.
 *
 * This allows us to calculate a deposit's accumulated collateral gain, during the epoch in which the deposit was non-zero and earned collateral.
 *
 * We calculate the depositor's accumulated collateral gain for the scale at which they made the deposit, using the collateral gain formula:
 * e_1 = d_t * (S - S_t) / P_t
 *
 * and also for scale after, taking care to divide the latter by a factor of 1e9:
 * e_2 = d_t * S / (P_t * 1e9)
 *
 * The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything.
 * The deposit therefore was present for reward events from the beginning of that second scale.
 *
 *        S_i-S_t + S_{i+1}
 *      .<--------.------------>
 *      .         .
 *      . S_i     .   S_{i+1}
 *   <--.-------->.<----------->
 *   S_t.         .
 *   <->.         .
 *      t         .
 *  |---+---------|-------------|-----...
 *         i            i+1
 *
 * The sum of (e_1 + e_2) captures the depositor's total accumulated collateral gain, handling the case where their
 * deposit spanned one scale change. We only care about gains across one scale change, since the compounded
 * deposit is defined as being 0 once it has spanned more than one scale change.
 *
 *
 * --- UPDATING P WHEN A LIQUIDATION OCCURS ---
 *
 * Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / collateral gain derivations:
 * https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
 *
 */
contract StabilityPool is LiquityBase, Ownable, CheckContract, SendCollateral, IStabilityPool {

    string constant public NAME = "StabilityPool";

    address public collateralAddress;

    IBorrowerOperations public borrowerOperations;

    ITroveManager public troveManager;

    ITHUSDToken public thusdToken;

    // Needed to check if there are pending liquidations
    ISortedTroves public sortedTroves;

    uint256 internal collateral;  // deposited collateral tracker

    // Tracker for THUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
    uint256 internal totalTHUSDDeposits;

   // --- Data structures ---

    struct Snapshots {
        uint256 S;
        uint256 P;
        uint128 scale;
        uint128 epoch;
    }

    mapping (address => uint256) public deposits;  // depositor address -> initial value
    mapping (address => Snapshots) public depositSnapshots;  // depositor address -> snapshots struct

    /*  Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit,
    * after a series of liquidations have occurred, each of which cancel some THUSD debt with the deposit.
    *
    * During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t
    * is the snapshot of P taken at the instant the deposit was made. 18-digit decimal.
    */
    uint256 public P = DECIMAL_PRECISION;

    uint256 public constant SCALE_FACTOR = 1e9;

    // Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1
    uint128 public currentScale;

    // With each offset that fully empties the Pool, the epoch is incremented by 1
    uint128 public currentEpoch;

    /* collateral Gain sum 'S': During its lifetime, each deposit d_t earns an collateral gain of ( d_t * [S - S_t] )/P_t, where S_t
    * is the depositor's snapshot of S taken at the time t when the deposit was made.
    *
    * The 'S' sums are stored in a nested mapping (epoch => scale => sum):
    *
    * - The inner mapping records the sum S at different scales
    * - The outer mapping records the (scale => sum) mappings, for different epochs.
    */
    mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum;

    // Error trackers for the error correction in the offset calculation
    uint256 public lastCollateralError_Offset;
    uint256 public lastTHUSDLossError_Offset;

    // --- Contract setters ---

    function setAddresses(
        address _borrowerOperationsAddress,
        address _troveManagerAddress,
        address _activePoolAddress,
        address _thusdTokenAddress,
        address _sortedTrovesAddress,
        address _priceFeedAddress,
        address _collateralAddress
    )
        external
        override
        onlyOwner
    {
        checkContract(_borrowerOperationsAddress);
        checkContract(_troveManagerAddress);
        checkContract(_activePoolAddress);
        checkContract(_thusdTokenAddress);
        checkContract(_sortedTrovesAddress);
        checkContract(_priceFeedAddress);
        if (_collateralAddress != address(0)) {
            checkContract(_collateralAddress);
        }

        borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress);
        troveManager = ITroveManager(_troveManagerAddress);
        activePool = IActivePool(_activePoolAddress);
        thusdToken = ITHUSDToken(_thusdTokenAddress);
        sortedTroves = ISortedTroves(_sortedTrovesAddress);
        priceFeed = IPriceFeed(_priceFeedAddress);
        collateralAddress = _collateralAddress;
        
        require(
            (Ownable(_borrowerOperationsAddress).owner() != address(0) || 
            borrowerOperations.collateralAddress() == _collateralAddress) &&
            (Ownable(_activePoolAddress).owner() != address(0) || 
            activePool.collateralAddress() == _collateralAddress),
            "The same collateral address must be used for the entire set of contracts"
        );

        emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
        emit TroveManagerAddressChanged(_troveManagerAddress);
        emit ActivePoolAddressChanged(_activePoolAddress);
        emit THUSDTokenAddressChanged(_thusdTokenAddress);
        emit SortedTrovesAddressChanged(_sortedTrovesAddress);
        emit PriceFeedAddressChanged(_priceFeedAddress);
        emit CollateralAddressChanged(_collateralAddress);

        _renounceOwnership();
    }

    // --- Getters for public variables. Required by IPool interface ---

    function getCollateralBalance() external view override returns (uint) {
        return collateral;
    }

    function getTotalTHUSDDeposits() external view override returns (uint) {
        return totalTHUSDDeposits;
    }

    // --- External Depositor Functions ---

    /*  provideToSP():
     *
     * - Sends depositor's accumulated gains (collateral) to depositor
     */
    function provideToSP(uint256 _amount) external override {
        _requireNonZeroAmount(_amount);

        uint256 initialDeposit = deposits[msg.sender];

        uint256 depositorCollateralGain = getDepositorCollateralGain(msg.sender);
        uint256 compoundedTHUSDDeposit = getCompoundedTHUSDDeposit(msg.sender);
        uint256 THUSDLoss = initialDeposit - compoundedTHUSDDeposit; // Needed only for event log

        _sendTHUSDtoStabilityPool(msg.sender, _amount);

        uint256 newDeposit = compoundedTHUSDDeposit + _amount;
        _updateDepositAndSnapshots(msg.sender, newDeposit);
        emit UserDepositChanged(msg.sender, newDeposit);

        emit CollateralGainWithdrawn(msg.sender, depositorCollateralGain, THUSDLoss); // THUSD Loss required for event log

        _sendCollateralGainToDepositor(depositorCollateralGain);
     }

    /*  withdrawFromSP():
    *
    * - Sends all depositor's accumulated gains (collateral) to depositor
    *
    * If _amount > userDeposit, the user withdraws all of their compounded deposit.
    */
    function withdrawFromSP(uint256 _amount) external override {
        if (_amount !=0) {_requireNoUnderCollateralizedTroves();}
        uint256 initialDeposit = deposits[msg.sender];
        _requireUserHasDeposit(initialDeposit);

        uint256 depositorCollateralGain = getDepositorCollateralGain(msg.sender);

        uint256 compoundedTHUSDDeposit = getCompoundedTHUSDDeposit(msg.sender);
        uint256 THUSDtoWithdraw = LiquityMath._min(_amount, compoundedTHUSDDeposit);
        uint256 THUSDLoss = initialDeposit - compoundedTHUSDDeposit; // Needed only for event log

        _sendTHUSDToDepositor(msg.sender, THUSDtoWithdraw);

        // Update deposit
        uint256 newDeposit = compoundedTHUSDDeposit - THUSDtoWithdraw;
        _updateDepositAndSnapshots(msg.sender, newDeposit);
        emit UserDepositChanged(msg.sender, newDeposit);

        emit CollateralGainWithdrawn(msg.sender, depositorCollateralGain, THUSDLoss);  // THUSD Loss required for event log

        _sendCollateralGainToDepositor(depositorCollateralGain);
    }

    /* withdrawCollateralGainToTrove:
    * - Transfers the depositor's entire collateral gain from the Stability Pool to the caller's trove
    * - Leaves their compounded deposit in the Stability Pool
    * - Updates snapshots for deposit */
    function withdrawCollateralGainToTrove(address _upperHint, address _lowerHint) external override {
        uint256 initialDeposit = deposits[msg.sender];
        _requireUserHasDeposit(initialDeposit);
        _requireUserHasTrove(msg.sender);
        _requireUserHasCollateralGain(msg.sender);

        uint256 depositorCollateralGain = getDepositorCollateralGain(msg.sender);

        uint256 compoundedTHUSDDeposit = getCompoundedTHUSDDeposit(msg.sender);
        uint256 THUSDLoss = initialDeposit - compoundedTHUSDDeposit; // Needed only for event log

        _updateDepositAndSnapshots(msg.sender, compoundedTHUSDDeposit);

        /* Emit events before transferring collateral gain to Trove.
         This lets the event log make more sense (i.e. so it appears that first the collateral gain is withdrawn
        and then it is deposited into the Trove, not the other way around). */
        emit CollateralGainWithdrawn(msg.sender, depositorCollateralGain, THUSDLoss);
        emit UserDepositChanged(msg.sender, compoundedTHUSDDeposit);

        collateral -= depositorCollateralGain;
        emit StabilityPoolCollateralBalanceUpdated(collateral);
        emit CollateralSent(msg.sender, depositorCollateralGain);

        if (collateralAddress == address(0)) {
          borrowerOperations.moveCollateralGainToTrove{ value: depositorCollateralGain }(msg.sender, 0, _upperHint, _lowerHint);
        } else {
          borrowerOperations.moveCollateralGainToTrove{ value: 0 }(msg.sender, depositorCollateralGain, _upperHint, _lowerHint);
        }
    }

    // --- Liquidation functions ---

    /*
    * Cancels out the specified debt against the THUSD contained in the Stability Pool (as far as possible)
    * and transfers the Trove's collateral from ActivePool to StabilityPool.
    * Only called by liquidation functions in the TroveManager.
    */
    function offset(uint256 _debtToOffset, uint256 _collToAdd) external override {
        _requireCallerIsTroveManager();
        uint256 totalTHUSD = totalTHUSDDeposits; // cached to save an SLOAD
        if (totalTHUSD == 0 || _debtToOffset == 0) { return; }

        (uint256 collateralGainPerUnitStaked,
            uint256 THUSDLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalTHUSD);

        _updateRewardSumAndProduct(collateralGainPerUnitStaked, THUSDLossPerUnitStaked);  // updates S and P

        _moveOffsetCollAndDebt(_collToAdd, _debtToOffset);
    }

    // --- Offset helper functions ---

    function _computeRewardsPerUnitStaked(
        uint256 _collToAdd,
        uint256 _debtToOffset,
        uint256 _totalTHUSDDeposits
    )
        internal
        returns (uint256 collateralGainPerUnitStaked, uint256 THUSDLossPerUnitStaked)
    {
        /*
        * Compute the THUSD and collateral rewards. Uses a "feedback" error correction, to keep
        * the cumulative error in the P and S state variables low:
        *
        * 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.
        */
        uint256 collateralNumerator = _collToAdd * DECIMAL_PRECISION + lastCollateralError_Offset;

        assert(_debtToOffset <= _totalTHUSDDeposits);
        if (_debtToOffset == _totalTHUSDDeposits) {
            THUSDLossPerUnitStaked = DECIMAL_PRECISION;  // When the Pool depletes to 0, so does each deposit
            lastTHUSDLossError_Offset = 0;
        } else {
            uint256 THUSDLossNumerator = _debtToOffset * DECIMAL_PRECISION - lastTHUSDLossError_Offset;
            /*
            * Add 1 to make error in quotient positive. We want "slightly too much" THUSD loss,
            * which ensures the error in any given compoundedTHUSDDeposit favors the Stability Pool.
            */
            THUSDLossPerUnitStaked = THUSDLossNumerator / _totalTHUSDDeposits + 1;
            lastTHUSDLossError_Offset = THUSDLossPerUnitStaked * _totalTHUSDDeposits - THUSDLossNumerator;
        }

        collateralGainPerUnitStaked = collateralNumerator / _totalTHUSDDeposits;
        lastCollateralError_Offset = collateralNumerator - (collateralGainPerUnitStaked * _totalTHUSDDeposits);

        return (collateralGainPerUnitStaked, THUSDLossPerUnitStaked);
    }

    // Update the Stability Pool reward sum S and product P
    function _updateRewardSumAndProduct(uint256 _collateralGainPerUnitStaked, uint256 _THUSDLossPerUnitStaked) internal {
        uint256 currentP = P;
        uint256 newP;

        assert(_THUSDLossPerUnitStaked <= DECIMAL_PRECISION);
        /*
        * The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool THUSD in the liquidation.
        * We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - THUSDLossPerUnitStaked)
        */
        uint256 newProductFactor = DECIMAL_PRECISION - _THUSDLossPerUnitStaked;

        uint128 currentScaleCached = currentScale;
        uint128 currentEpochCached = currentEpoch;
        uint256 currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];

        /*
        * Calculate the new S first, before we update P.
        * The collateral gain for any given depositor from a liquidation depends on the value of their deposit
        * (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation.
        *
        * Since S corresponds to collateral gain, and P to deposit loss, we update S first.
        */
        uint256 marginalCollateralGain = _collateralGainPerUnitStaked * currentP;
        uint256 newS = currentS + marginalCollateralGain;
        epochToScaleToSum[currentEpochCached][currentScaleCached] = newS;
        emit S_Updated(newS, currentEpochCached, currentScaleCached);

        // If the Stability Pool was emptied, increment the epoch, and reset the scale and product P
        if (newProductFactor == 0) {
            currentEpoch = currentEpochCached + 1;
            emit EpochUpdated(currentEpoch);
            currentScale = 0;
            emit ScaleUpdated(currentScale);
            newP = DECIMAL_PRECISION;

        // If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale
        } else if (currentP * newProductFactor / DECIMAL_PRECISION < SCALE_FACTOR) {
            newP = currentP * newProductFactor * SCALE_FACTOR / DECIMAL_PRECISION;
            currentScale = currentScaleCached + 1;
            emit ScaleUpdated(currentScale);
        } else {
            newP = currentP * newProductFactor / DECIMAL_PRECISION;
        }

        assert(newP > 0);
        P = newP;

        emit P_Updated(newP);
    }

    function _moveOffsetCollAndDebt(uint256 _collToAdd, uint256 _debtToOffset) internal {
        IActivePool activePoolCached = activePool;

        // Cancel the liquidated THUSD debt with the THUSD in the stability pool
        activePoolCached.decreaseTHUSDDebt(_debtToOffset);
        _decreaseTHUSD(_debtToOffset);

        // Burn the debt that was successfully offset
        thusdToken.burn(address(this), _debtToOffset);

        activePoolCached.sendCollateral(address(this), _collToAdd);
    }

    function _decreaseTHUSD(uint256 _amount) internal {
        uint256 newTotalTHUSDDeposits = totalTHUSDDeposits - _amount;
        totalTHUSDDeposits = newTotalTHUSDDeposits;
        emit StabilityPoolTHUSDBalanceUpdated(newTotalTHUSDDeposits);
    }

    // --- Reward calculator functions for depositor ---

    /* Calculates the collateral gain earned by the deposit since its last snapshots were taken.
    * Given by the formula:  E = d0 * (S - S(0))/P(0)
    * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively.
    * d0 is the last recorded deposit value.
    */
    function getDepositorCollateralGain(address _depositor) public view override returns (uint) {
        uint256 initialDeposit = deposits[_depositor];

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

        Snapshots memory snapshots = depositSnapshots[_depositor];

        uint256 collateralGain = _getCollateralGainFromSnapshots(initialDeposit, snapshots);
        return collateralGain;
    }

    function _getCollateralGainFromSnapshots(uint256 initialDeposit, Snapshots memory snapshots) internal view returns (uint) {
        /*
        * Grab the sum 'S' from the epoch at which the stake was made. The collateral gain may span up to one scale change.
        * If it does, the second portion of the collateral gain is scaled by 1e9.
        * If the gain spans no scale change, the second portion will be 0.
        */
        uint128 epochSnapshot = snapshots.epoch;
        uint128 scaleSnapshot = snapshots.scale;
        uint256 S_Snapshot = snapshots.S;
        uint256 P_Snapshot = snapshots.P;

        uint256 firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot] - S_Snapshot;
        uint256 secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot + 1] / SCALE_FACTOR;

        uint256 collateralGain = initialDeposit * (firstPortion + secondPortion) / P_Snapshot / DECIMAL_PRECISION;

        return collateralGain;
    }

    // --- Compounded deposit ---

    /*
    * Return the user's compounded deposit. Given by the formula:  d = d0 * P/P(0)
    * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit.
    */
    function getCompoundedTHUSDDeposit(address _depositor) public view override returns (uint) {
        uint256 initialDeposit = deposits[_depositor];
        if (initialDeposit == 0) { return 0; }

        Snapshots memory snapshots = depositSnapshots[_depositor];

        uint256 compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots);
        return compoundedDeposit;
    }

    // Internal function, used to calculcate compounded deposits.
    function _getCompoundedStakeFromSnapshots(
        uint256 initialStake,
        Snapshots memory snapshots
    )
        internal
        view
        returns (uint)
    {
        uint256 snapshot_P = snapshots.P;
        uint128 scaleSnapshot = snapshots.scale;
        uint128 epochSnapshot = snapshots.epoch;

        // If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0
        if (epochSnapshot < currentEpoch) { return 0; }

        uint256 compoundedStake;
        uint128 scaleDiff = currentScale - scaleSnapshot;

        /* Compute the compounded stake. If a scale change in P was made during the stake's lifetime,
        * account for it. If more than one scale change was made, then the stake has decreased by a factor of
        * at least 1e-9 -- so return 0.
        */
        if (scaleDiff == 0) {
            compoundedStake = initialStake * P / snapshot_P;
        } else if (scaleDiff == 1) {
            compoundedStake = initialStake * P / snapshot_P / SCALE_FACTOR;
        } else { // if scaleDiff >= 2
            compoundedStake = 0;
        }

        /*
        * If compounded deposit is less than a billionth of the initial deposit, return 0.
        *
        * NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error
        * corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less
        * than it's theoretical value.
        *
        * Thus it's unclear whether this line is still really needed.
        */
        if (compoundedStake < initialStake / 1e9) {return 0;}

        return compoundedStake;
    }

    // --- Sender functions for THUSD deposit, collateral gains ---

    // Transfer the THUSD tokens from the user to the Stability Pool's address, and update its recorded THUSD
    function _sendTHUSDtoStabilityPool(address _address, uint256 _amount) internal {
        thusdToken.transferFrom(_address, address(this), _amount);
        uint256 newTotalTHUSDDeposits = totalTHUSDDeposits + _amount;
        totalTHUSDDeposits = newTotalTHUSDDeposits;
        emit StabilityPoolTHUSDBalanceUpdated(newTotalTHUSDDeposits);
    }

    function _sendCollateralGainToDepositor(uint256 _amount) internal {
        if (_amount == 0) {return;}
        uint256 newCollateral = collateral - _amount;
        collateral = newCollateral;
        emit StabilityPoolCollateralBalanceUpdated(newCollateral);
        emit CollateralSent(msg.sender, _amount);

        sendCollateral(IERC20(collateralAddress), msg.sender, _amount);
    }

    // Send THUSD to user and decrease THUSD in Pool
    function _sendTHUSDToDepositor(address _depositor, uint256 THUSDWithdrawal) internal {
        if (THUSDWithdrawal == 0) {return;}

        thusdToken.transfer(_depositor, THUSDWithdrawal);
        _decreaseTHUSD(THUSDWithdrawal);
    }

    // --- Stability Pool Deposit Functionality ---

    function _updateDepositAndSnapshots(address _depositor, uint256 _newValue) internal {
        deposits[_depositor] = _newValue;

        if (_newValue == 0) {
            delete depositSnapshots[_depositor];
            emit DepositSnapshotUpdated(_depositor, 0, 0);
            return;
        }
        uint128 currentScaleCached = currentScale;
        uint128 currentEpochCached = currentEpoch;
        uint256 currentP = P;

        // Get S and G for the current epoch and current scale
        uint256 currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];

        // Record new snapshots of the latest running product P, sum S, and sum G, for the depositor
        depositSnapshots[_depositor].P = currentP;
        depositSnapshots[_depositor].S = currentS;
        depositSnapshots[_depositor].scale = currentScaleCached;
        depositSnapshots[_depositor].epoch = currentEpochCached;

        emit DepositSnapshotUpdated(_depositor, currentP, currentS);
    }

    // --- 'require' functions ---

    function _requireCallerIsActivePool() internal view {
        require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool");
    }

    function _requireCallerIsTroveManager() internal view {
        require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager");
    }

    function _requireNoUnderCollateralizedTroves() internal {
        uint256 price = priceFeed.fetchPrice();
        address lowestTrove = sortedTroves.getLast();
        uint256 ICR = troveManager.getCurrentICR(lowestTrove, price);
        require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR");
    }

    function _requireUserHasDeposit(uint256 _initialDeposit) internal pure {
        require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit');
    }

    function _requireNonZeroAmount(uint256 _amount) internal pure {
        require(_amount > 0, 'StabilityPool: Amount must be non-zero');
    }

    function _requireUserHasTrove(address _depositor) internal view {
        require(
            troveManager.getTroveStatus(_depositor) == ITroveManager.Status.active, 
            "StabilityPool: caller must have an active trove to withdraw collateralGain to"
        );
    }

    function _requireUserHasCollateralGain(address _depositor) internal view {
        uint256 collateralGain = getDepositorCollateralGain(_depositor);
        require(collateralGain > 0, "StabilityPool: caller must have non-zero collateral Gain");
    }

    // When ERC20 token collateral is received this function needs to be called
    function updateCollateralBalance(uint256 _amount) external override {
        _requireCallerIsActivePool();
        collateral += _amount;
        emit StabilityPoolCollateralBalanceUpdated(collateral);
  	}

    // --- Fallback function ---

    receive() external payable {
        _requireCallerIsActivePool();
        collateral += msg.value;
        emit StabilityPoolCollateralBalanceUpdated(collateral);
    }
}

File 2 of 24 : IERC20Metadata.sol
// 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);
}

File 3 of 24 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 5 of 24 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 6 of 24 : Address.sol
// 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);
        }
    }
}

File 7 of 24 : BaseMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;


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

File 8 of 24 : CheckContract.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;


contract CheckContract {
    /**
     * Check that the account is an already deployed non-destroyed contract.
     * See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12
     */
    function checkContract(address _account) internal view {
        require(_account != address(0), "Account cannot be zero address");

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(_account) }
        require(size > 0, "Account code size cannot be zero");
    }
}

File 9 of 24 : IERC2612.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

/**
 * @dev Interface of the ERC2612 standard as defined in the EIP.
 *
 * Adds the {permit} method, which can be used to change one's
 * {IERC20-allowance} without having to send a transaction, by signing a
 * message. This allows users to spend tokens without having to hold Ether.
 *
 * See https://eips.ethereum.org/EIPS/eip-2612.
 * 
 * Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
 */
interface IERC2612 {
    /**
     * @dev Sets `amount` 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:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(address owner, address spender, uint256 amount, 
                    uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
    
    /**
     * @dev Returns the current ERC2612 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.
     *
     * `owner` can limit the time a Permit is valid for by setting `deadline` to 
     * a value in the near future. The deadline argument can be set to uint(-1) to 
     * create Permits that effectively never expire.
     */
    function nonces(address owner) external view returns (uint256);
    
    function version() external view returns (string memory);
    function permitTypeHash() external view returns (bytes32);
    function domainSeparator() external view returns (bytes32);
}

File 10 of 24 : LiquityBase.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

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

/*
* Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and
* common functions.
*/
contract LiquityBase is BaseMath, ILiquityBase {

    uint256 constant public _100pct = 1e18; // 1e18 == 100%

    // Minimum collateral ratio for individual troves
    uint256 constant public MCR = 1.1e18; // 110%

    // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.
    uint256 constant public CCR = 1.5e18; // 150%

    // Amount of THUSD to be locked in gas pool on opening troves
    uint256 constant public THUSD_GAS_COMPENSATION = 200e18;

    // Minimum amount of net THUSD debt a trove must have
    uint256 constant public MIN_NET_DEBT = 1800e18;
    // uint256 constant public MIN_NET_DEBT = 0;

    uint256 constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%

    uint256 constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%

    IActivePool public activePool;

    IDefaultPool public defaultPool;

    IPriceFeed public override priceFeed;

    // --- Gas compensation functions ---

    // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
    function _getCompositeDebt(uint256 _debt) internal pure returns (uint) {
        return _debt + THUSD_GAS_COMPENSATION;
    }

    function _getNetDebt(uint256 _debt) internal pure returns (uint) {
        return _debt - THUSD_GAS_COMPENSATION;
    }

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

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

        return activeColl + liquidatedColl;
    }

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

        return activeDebt + closedDebt;
    }

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

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

    function _checkRecoveryMode(uint256 _price) internal view returns (bool) {
        uint256 TCR = _getTCR(_price);
        return TCR < CCR;
    }

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

File 11 of 24 : LiquityMath.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

library LiquityMath {

    uint256 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.
     *
     */
    uint256 internal constant NICR_PRECISION = 1e20;

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

    function _max(uint256 _a, uint256 _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(uint256 x, uint256 y) internal pure returns (uint256 decProd) {
        uint256 prod_xy = x * y;

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

    /*
    * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
    *
    * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
    *
    * Called by one function that represent time in units of minutes:
    * 1) TroveManager._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(uint256 _base, uint256 _minutes) internal pure returns (uint) {

        if (_minutes > 525600000) {_minutes = 525600000;}  // cap to avoid overflow

        if (_minutes == 0) {return DECIMAL_PRECISION;}

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

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

        return decMul(x, y);
  }

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

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

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

            return newCollRatio;
        }
        // Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
        else { // if (_debt == 0)
            return type(uint256).max;
        }
    }
}

File 12 of 24 : Ownable.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

/**
 * Based on OpenZeppelin's Ownable contract:
 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.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.
 *
 * 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.
 */
contract Ownable {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        _owner = msg.sender;
        emit OwnershipTransferred(address(0), msg.sender);
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(isOwner(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Returns true if the caller is the current owner.
     */
    function isOwner() public view returns (bool) {
        return msg.sender == _owner;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     *
     * NOTE: This function is not safe, as it doesn’t check owner is calling it.
     * Make sure you check it before calling it.
     */
    function _renounceOwnership() internal {
        emit OwnershipTransferred(_owner, address(0));
        _owner = 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 13 of 24 : SendCollateral.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;


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


contract SendCollateral {
    using SafeERC20 for IERC20;

    /**
     * Sends collateral to recipient
     */
    function sendCollateral(IERC20 _collateralERC20, address _recipient, uint256 _amount) internal {
        if (address(_collateralERC20) == address(0)) {
            // ETH
            // require(_amount <= address(this).balance, "Not enough ETH");
            (bool success, ) = _recipient.call{ value: _amount }(""); // re-entry is fine here
            require(success, "Sending ETH failed");
        } else {
            // ERC20
            // require(_amount <= _collateralERC20.balanceOf(address(this)), "Not enough collateral");
            _collateralERC20.safeTransfer(_recipient, _amount); 
        }
    }
    
    /**
     * Sends collateral to recipient
     */
    function sendCollateralFrom(IERC20 _collateralERC20, address _from, address _recipient, uint256 _amount) internal {
        if (address(_collateralERC20) == address(0)) {
            // ETH
            // require(_amount <= address(this).balance, "Not enough ETH");
            (bool success, ) = _recipient.call{ value: _amount }(""); // re-entry is fine here
            require(success, "Sending ETH failed");
        } else {
            // ERC20
            // require(_amount <= _collateralERC20.balanceOf(address(this)), "Not enough collateral");
            _collateralERC20.safeTransferFrom(_from, _recipient, _amount);
        }
    }
}

File 14 of 24 : IActivePool.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

import "./IPool.sol";


interface IActivePool is IPool {
    // --- Events ---
    event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
    event TroveManagerAddressChanged(address _newTroveManagerAddress);
    event ActivePoolTHUSDDebtUpdated(uint256 _THUSDDebt);
    event ActivePoolCollateralBalanceUpdated(uint256 _collateral);
    event CollateralAddressChanged(address _newCollateralAddress);
    event CollSurplusPoolAddressChanged(address _newCollSurplusPoolAddress);

    // --- Functions ---
    function sendCollateral(address _account, uint256 _amount) external;
    function updateCollateralBalance(uint256 _amount) external;
    function collateralAddress() external view returns(address);
}

File 15 of 24 : IBorrowerOperations.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

// Common interface for the Trove Manager.
interface IBorrowerOperations {

    // --- Events ---

    event TroveManagerAddressChanged(address _newTroveManagerAddress);
    event ActivePoolAddressChanged(address _activePoolAddress);
    event DefaultPoolAddressChanged(address _defaultPoolAddress);
    event StabilityPoolAddressChanged(address _stabilityPoolAddress);
    event GasPoolAddressChanged(address _gasPoolAddress);
    event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
    event PriceFeedAddressChanged(address  _newPriceFeedAddress);
    event SortedTrovesAddressChanged(address _sortedTrovesAddress);
    event THUSDTokenAddressChanged(address _thusdTokenAddress);
    event PCVAddressChanged(address _pcvAddress);
    event CollateralAddressChanged(address _newCollateralAddress);

    event TroveCreated(address indexed _borrower, uint256 arrayIndex);
    event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);
    event THUSDBorrowingFeePaid(address indexed _borrower, uint256 _THUSDFee);

    // --- Functions ---

    function setAddresses(
        address _troveManagerAddress,
        address _activePoolAddress,
        address _defaultPoolAddress,
        address _stabilityPoolAddress,
        address _gasPoolAddress,
        address _collSurplusPoolAddress,
        address _priceFeedAddress,
        address _sortedTrovesAddress,
        address _thusdTokenAddress,
        address _pcvAddress,
        address _collateralAddress

    ) external;

    function openTrove(uint256 _maxFee, uint256 _THUSDAmount, uint256 _assetAmount, address _upperHint, address _lowerHint) external payable;

    function addColl(uint256 _assetAmount, address _upperHint, address _lowerHint) external payable;

    function moveCollateralGainToTrove(address _user, uint256 _assetAmount, address _upperHint, address _lowerHint) external payable;

    function withdrawColl(uint256 _amount, address _upperHint, address _lowerHint) external;

    function withdrawTHUSD(uint256 _maxFee, uint256 _amount, address _upperHint, address _lowerHint) external;

    function repayTHUSD(uint256 _amount, address _upperHint, address _lowerHint) external;

    function closeTrove() external;

    function adjustTrove(uint256 _maxFee, uint256 _collWithdrawal, uint256 _debtChange, bool isDebtIncrease, uint256 _assetAmount, address _upperHint, address _lowerHint) external payable;

    function claimCollateral() external;

    function getCompositeDebt(uint256 _debt) external pure returns (uint);

    function collateralAddress() external view returns(address);
}

File 16 of 24 : IDefaultPool.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

import "./IPool.sol";


interface IDefaultPool is IPool {
    // --- Events ---
    event TroveManagerAddressChanged(address _newTroveManagerAddress);
    event DefaultPoolTHUSDDebtUpdated(uint256 _THUSDDebt);
    event DefaultPoolCollateralBalanceUpdated(uint256 _collateral);
    event CollateralAddressChanged(address _newCollateralAddress);

    // --- Functions ---
    function sendCollateralToActivePool(uint256 _amount) external;
    function updateCollateralBalance(uint256 _amount) external;
    function collateralAddress() external view returns(address);
}

File 17 of 24 : ILiquityBase.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

import "./IPriceFeed.sol";


interface ILiquityBase {
    function priceFeed() external view returns (IPriceFeed);
}

File 18 of 24 : IPCV.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

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

interface IPCV {

    // --- Events --
    event THUSDTokenAddressSet(address _thusdTokenAddress);
    event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
    event CollateralAddressSet(address _collateralAddress);
    event BAMMAddressSet(address _bammAddress);
    event RolesSet(address _council, address _treasury);

    event BAMMDeposit(uint256 _thusdAmount);
    event BAMMWithdraw(uint256 _numShares);
    event THUSDWithdraw(address _recipient, uint256 _thusdAmount);
    event CollateralWithdraw(address _recipient, uint256 _collateralAmount);

    event PCVDebtPaid(uint256 _paidDebt);
    
    event RecipientAdded(address _recipient);
    event RecipientRemoved(address _recipient);

    // --- Functions ---

    function debtToPay() external returns(uint256);
    function payDebt(uint256 _thusdToBurn) external;

    function setAddresses(
        address _thusdTokenAddress, 
        address _borrowerOperations, 
        address payable _bammAddress,
        address _collateralERC20
    ) external;
    function initialize() external;

    function depositToBAMM(uint256 _thusdAmount) external;
    function withdrawFromBAMM(uint256 _numShares) external;
    function withdrawTHUSD(address _recipient, uint256 _thusdAmount) external;
    function withdrawCollateral(address _recipient, uint256 _collateralAmount) external;

    function addRecipientToWhitelist(address _recipient) external;
    function addRecipientsToWhitelist(address[] calldata _recipients) external;
    function removeRecipientFromWhitelist(address _recipient) external;
    function removeRecipientsFromWhitelist(address[] calldata _recipients) external;

    function startChangingRoles(address _council, address _treasury) external;
    function cancelChangingRoles() external;
    function finalizeChangingRoles() external;
    
    function collateralERC20() external view returns(IERC20);
    function thusdToken() external view returns(ITHUSDToken);

}

File 19 of 24 : IPool.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

// Common interface for the Pools.
interface IPool {

    // --- Events ---

    event CollateralBalanceUpdated(uint256 _newBalance);
    event THUSDBalanceUpdated(uint256 _newBalance);
    event ActivePoolAddressChanged(address _newActivePoolAddress);
    event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
    event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
    event CollateralSent(address _to, uint256 _amount);

    // --- Functions ---

    function getCollateralBalance() external view returns (uint);

    function getTHUSDDebt() external view returns (uint);

    function increaseTHUSDDebt(uint256 _amount) external;

    function decreaseTHUSDDebt(uint256 _amount) external;
}

File 20 of 24 : IPriceFeed.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

interface IPriceFeed {

    // --- Events ---
    event LastGoodPriceUpdated(uint256 _lastGoodPrice);
   
    // --- Function ---
    function fetchPrice() external returns (uint);
}

File 21 of 24 : ISortedTroves.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

// Common interface for the SortedTroves Doubly Linked List.
interface ISortedTroves {

    // --- Events ---
    
    event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
    event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
    event NodeAdded(address _id, uint256 _NICR);
    event NodeRemoved(address _id);

    // --- Functions ---
    
    function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;

    function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;

    function remove(address _id) external;

    function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;

    function contains(address _id) external view returns (bool);

    function isFull() external view returns (bool);

    function isEmpty() external view returns (bool);

    function getSize() external view returns (uint256);

    function getMaxSize() external view returns (uint256);

    function getFirst() external view returns (address);

    function getLast() external view returns (address);

    function getNext(address _id) external view returns (address);

    function getPrev(address _id) external view returns (address);

    function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);

    function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}

File 22 of 24 : IStabilityPool.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

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

    // --- Events ---

    event StabilityPoolCollateralBalanceUpdated(uint256 _newBalance);
    event StabilityPoolTHUSDBalanceUpdated(uint256 _newBalance);

    event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
    event TroveManagerAddressChanged(address _newTroveManagerAddress);
    event ActivePoolAddressChanged(address _newActivePoolAddress);
    event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
    event THUSDTokenAddressChanged(address _newTHUSDTokenAddress);
    event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
    event PriceFeedAddressChanged(address _newPriceFeedAddress);
    event CollateralAddressChanged(address _newCollateralAddress);

    event P_Updated(uint256 _P);
    event S_Updated(uint256 _S, uint128 _epoch, uint128 _scale);
    event EpochUpdated(uint128 _currentEpoch);
    event ScaleUpdated(uint128 _currentScale);

    event DepositSnapshotUpdated(address indexed _depositor, uint256 _P, uint256 _S);
    event UserDepositChanged(address indexed _depositor, uint256 _newDeposit);

    event CollateralGainWithdrawn(address indexed _depositor, uint256 _collateral, uint256 _THUSDLoss);
    event CollateralSent(address _to, uint256 _amount);

    // --- Functions ---

    /*
     * Called only once on init, to set addresses of other Liquity contracts
     * Callable only by owner, renounces ownership at the end
     */
    function setAddresses(
        address _borrowerOperationsAddress,
        address _troveManagerAddress,
        address _activePoolAddress,
        address _thusdTokenAddress,
        address _sortedTrovesAddress,
        address _priceFeedAddress,
        address _collateralAddress
    ) external;

    /*
     * Initial checks:
     * - _amount is not zero
     * ---
     * - Sends depositor's accumulated gains (collateral) to depositor
     */
    function provideToSP(uint256 _amount) external;

    /*
     * Initial checks:
     * - _amount is zero or there are no under collateralized troves left in the system
     * - User has a non zero deposit
     * ---
     * - Sends all depositor's accumulated gains (collateral) to depositor
     * - Decreases deposit stake, and takes new snapshot.
     *
     * If _amount > userDeposit, the user withdraws all of their compounded deposit.
     */
    function withdrawFromSP(uint256 _amount) external;

    /*
     * Initial checks:
     * - User has a non zero deposit
     * - User has an open trove
     * - User has some collateral gain
     * ---
     * - Transfers the depositor's entire collateral gain from the Stability Pool to the caller's trove
     * - Leaves their compounded deposit in the Stability Pool
     * - Updates snapshots for deposit
     */
    function withdrawCollateralGainToTrove(address _upperHint, address _lowerHint) external;

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

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

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

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

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

    /*
     * Only callable by Active Pool, updates ERC20 tokens recieved
     */
    function updateCollateralBalance(uint256 _amount) external;
    /*
     * Fallback function
     * Only callable by Active Pool, it just accounts for ETH received
     * receive() external payable;
     */
    
    function collateralAddress() external view returns(address);
}

File 23 of 24 : ITHUSDToken.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

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

interface ITHUSDToken is IERC20Metadata, IERC2612 {

    // --- Events ---

    event TroveManagerAddressAdded(address _troveManagerAddress);
    event StabilityPoolAddressAdded(address _newStabilityPoolAddress);
    event BorrowerOperationsAddressAdded(address _newBorrowerOperationsAddress);

    event THUSDTokenBalanceUpdated(address _user, uint256 _amount);

    // --- Functions ---
    function mintList(address contractAddress) external view returns (bool);
    function burnList(address contractAddress) external view returns (bool);

    function mint(address _account, uint256 _amount) external;

    function burn(address _account, uint256 _amount) external;

    function increaseAllowance(address spender, uint256 addedValue) external returns (bool);

    function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}

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

pragma solidity ^0.8.17;

import "./ILiquityBase.sol";
import "./IStabilityPool.sol";
import "./ITHUSDToken.sol";
import "./IPCV.sol";


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

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

    // --- Events ---

    event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
    event PriceFeedAddressChanged(address _newPriceFeedAddress);
    event THUSDTokenAddressChanged(address _newTHUSDTokenAddress);
    event ActivePoolAddressChanged(address _activePoolAddress);
    event DefaultPoolAddressChanged(address _defaultPoolAddress);
    event StabilityPoolAddressChanged(address _stabilityPoolAddress);
    event GasPoolAddressChanged(address _gasPoolAddress);
    event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
    event SortedTrovesAddressChanged(address _sortedTrovesAddress);
    event PCVAddressChanged(address _pcvAddress);

    event Liquidation(uint256 _liquidatedDebt, uint256 _liquidatedColl, uint256 _collGasCompensation, uint256 _THUSDGasCompensation);
    event Redemption(uint256 _attemptedTHUSDAmount, uint256 _actualTHUSDAmount, uint256 _collateralSent, uint256 _collateralFee);
    event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);
    event TroveLiquidated(address indexed _borrower, uint256 _debt, uint256 _coll, uint8 operation);
    event BaseRateUpdated(uint256 _baseRate);
    event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);
    event TotalStakesUpdated(uint256 _newTotalStakes);
    event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);
    event LTermsUpdated(uint256 _L_Collateral, uint256 _L_THUSDDebt);
    event TroveSnapshotsUpdated(uint256 _L_Collateral, uint256 _L_THUSDDebt);
    event TroveIndexUpdated(address _borrower, uint256 _newIndex);

    // --- Functions ---

    function setAddresses(
        address _borrowerOperationsAddress,
        address _activePoolAddress,
        address _defaultPoolAddress,
        address _stabilityPoolAddress,
        address _gasPoolAddress,
        address _collSurplusPoolAddress,
        address _priceFeedAddress,
        address _thusdTokenAddress,
        address _sortedTrovesAddress,
        address _pcvAddress
    ) external;

    function stabilityPool() external view returns (IStabilityPool);
    function thusdToken() external view returns (ITHUSDToken);
    function pcv() external view returns (IPCV);

    function getTroveOwnersCount() external view returns (uint);

    function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address);

    function getNominalICR(address _borrower) external view returns (uint);
    function getCurrentICR(address _borrower, uint256 _price) external view returns (uint);

    function liquidate(address _borrower) external;

    function liquidateTroves(uint256 _n) external;

    function batchLiquidateTroves(address[] calldata _troveArray) external;

    function redeemCollateral(
        uint256 _THUSDAmount,
        address _firstRedemptionHint,
        address _upperPartialRedemptionHint,
        address _lowerPartialRedemptionHint,
        uint256 _partialRedemptionHintNICR,
        uint256 _maxIterations,
        uint256 _maxFee
    ) external;

    function updateStakeAndTotalStakes(address _borrower) external returns (uint);

    function updateTroveRewardSnapshots(address _borrower) external;

    function addTroveOwnerToArray(address _borrower) external returns (uint256 index);

    function applyPendingRewards(address _borrower) external;

    function getPendingCollateralReward(address _borrower) external view returns (uint);

    function getPendingTHUSDDebtReward(address _borrower) external view returns (uint);

     function hasPendingRewards(address _borrower) external view returns (bool);

    function getEntireDebtAndColl(address _borrower) external view returns (
        uint256 debt,
        uint256 coll,
        uint256 pendingTHUSDDebtReward,
        uint256 pendingCollateralReward
    );

    function closeTrove(address _borrower) external;

    function removeStake(address _borrower) external;

    function getRedemptionRate() external view returns (uint);
    function getRedemptionRateWithDecay() external view returns (uint);

    function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint);

    function getBorrowingRate() external view returns (uint);
    function getBorrowingRateWithDecay() external view returns (uint);

    function getBorrowingFee(uint256 THUSDDebt) external view returns (uint);
    function getBorrowingFeeWithDecay(uint256 _THUSDDebt) external view returns (uint);

    function decayBaseRateFromBorrowing() external;

    function getTroveStatus(address _borrower) external view returns (Status);

    function getTroveStake(address _borrower) external view returns (uint);

    function getTroveDebt(address _borrower) external view returns (uint);

    function getTroveColl(address _borrower) external view returns (uint);

    function setTroveStatus(address _borrower, Status _status) external;

    function increaseTroveColl(address _borrower, uint256 _collIncrease) external returns (uint);

    function decreaseTroveColl(address _borrower, uint256 _collDecrease) external returns (uint);

    function increaseTroveDebt(address _borrower, uint256 _debtIncrease) external returns (uint);

    function decreaseTroveDebt(address _borrower, uint256 _collDecrease) external returns (uint);

    function getTCR(uint256 _price) external view returns (uint);

    function checkRecoveryMode(uint256 _price) external view returns (bool);
}

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

Contract Security Audit

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newActivePoolAddress","type":"address"}],"name":"ActivePoolAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newBorrowerOperationsAddress","type":"address"}],"name":"BorrowerOperationsAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newCollateralAddress","type":"address"}],"name":"CollateralAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_depositor","type":"address"},{"indexed":false,"internalType":"uint256","name":"_collateral","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_THUSDLoss","type":"uint256"}],"name":"CollateralGainWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_to","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"CollateralSent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newDefaultPoolAddress","type":"address"}],"name":"DefaultPoolAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_depositor","type":"address"},{"indexed":false,"internalType":"uint256","name":"_P","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_S","type":"uint256"}],"name":"DepositSnapshotUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"_currentEpoch","type":"uint128"}],"name":"EpochUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_P","type":"uint256"}],"name":"P_Updated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newPriceFeedAddress","type":"address"}],"name":"PriceFeedAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_S","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"_epoch","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"_scale","type":"uint128"}],"name":"S_Updated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"_currentScale","type":"uint128"}],"name":"ScaleUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newSortedTrovesAddress","type":"address"}],"name":"SortedTrovesAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_newBalance","type":"uint256"}],"name":"StabilityPoolCollateralBalanceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_newBalance","type":"uint256"}],"name":"StabilityPoolTHUSDBalanceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newTHUSDTokenAddress","type":"address"}],"name":"THUSDTokenAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_newTroveManagerAddress","type":"address"}],"name":"TroveManagerAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_depositor","type":"address"},{"indexed":false,"internalType":"uint256","name":"_newDeposit","type":"uint256"}],"name":"UserDepositChanged","type":"event"},{"inputs":[],"name":"BORROWING_FEE_FLOOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CCR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DECIMAL_PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MCR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_NET_DEBT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"NAME","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"P","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERCENT_DIVISOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SCALE_FACTOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"THUSD_GAS_COMPENSATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_100pct","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":[],"name":"borrowerOperations","outputs":[{"internalType":"contract IBorrowerOperations","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentEpoch","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentScale","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"defaultPool","outputs":[{"internalType":"contract IDefaultPool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"depositSnapshots","outputs":[{"internalType":"uint256","name":"S","type":"uint256"},{"internalType":"uint256","name":"P","type":"uint256"},{"internalType":"uint128","name":"scale","type":"uint128"},{"internalType":"uint128","name":"epoch","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint128","name":"","type":"uint128"},{"internalType":"uint128","name":"","type":"uint128"}],"name":"epochToScaleToSum","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCollateralBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_depositor","type":"address"}],"name":"getCompoundedTHUSDDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_depositor","type":"address"}],"name":"getDepositorCollateralGain","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEntireSystemColl","outputs":[{"internalType":"uint256","name":"entireSystemColl","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getEntireSystemDebt","outputs":[{"internalType":"uint256","name":"entireSystemDebt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalTHUSDDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastCollateralError_Offset","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTHUSDLossError_Offset","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_debtToOffset","type":"uint256"},{"internalType":"uint256","name":"_collToAdd","type":"uint256"}],"name":"offset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","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":"_amount","type":"uint256"}],"name":"provideToSP","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_borrowerOperationsAddress","type":"address"},{"internalType":"address","name":"_troveManagerAddress","type":"address"},{"internalType":"address","name":"_activePoolAddress","type":"address"},{"internalType":"address","name":"_thusdTokenAddress","type":"address"},{"internalType":"address","name":"_sortedTrovesAddress","type":"address"},{"internalType":"address","name":"_priceFeedAddress","type":"address"},{"internalType":"address","name":"_collateralAddress","type":"address"}],"name":"setAddresses","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sortedTroves","outputs":[{"internalType":"contract ISortedTroves","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"thusdToken","outputs":[{"internalType":"contract ITHUSDToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"troveManager","outputs":[{"internalType":"contract ITroveManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"updateCollateralBalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_upperHint","type":"address"},{"internalType":"address","name":"_lowerHint","type":"address"}],"name":"withdrawCollateralGainToTrove","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdrawFromSP","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

Deployed Bytecode

0x6080604052600436106102495760003560e01c806377553ad4116101395780638f32d59b116100b6578063ae9187541161007a578063ae91875414610758578063ce4b5bbe14610778578063eaa8ba7f14610790578063f2fde38b146107b0578063f92d3433146107d0578063fc7e286d146107e557600080fd5b80638f32d59b146106a757806398d99ee6146106d2578063a20baee6146104b3578063a3f4df7e146106f2578063a4e59ac81461073857600080fd5b80637f7dde4a116100fd5780637f7dde4a146105bf57806386da0824146105df578063887105d31461065e5780638b8fbd92146106735780638da5cb5b1461068957600080fd5b806377553ad41461052e57806377e16f1e1461054e57806378c77a241461056e578063794e57241461058e578063795d26c3146105aa57600080fd5b80633d83908a116101c75780635914d0c81161018b5780635914d0c81461047d5780635af658b61461049d57806372fe25aa146104b3578063741bef1a146104cf57806376671808146104ef57600080fd5b80633d83908a146103ec5780634870dd9a1461040c57806348d399e7146104215780635205a479146104415780635733d58f1461046157600080fd5b806328a0a04d1161020e57806328a0a04d146103255780632e54bf951461035d578063307d36121461037f578063335525ad1461039f5780633cc74225146103bf57600080fd5b8062ba85b51461029857806301081fda146102c15780631529a639146102d65780631bf43555146102eb5780631fd6a4341461030857600080fd5b3661029357610256610812565b346009600082825461026891906128e5565b9091555050600954604051908152600080516020612d038339815191529060200160405180910390a1005b600080fd5b3480156102a457600080fd5b506102ae60105481565b6040519081526020015b60405180910390f35b3480156102cd57600080fd5b50600a546102ae565b3480156102e257600080fd5b506009546102ae565b3480156102f757600080fd5b506102ae686194049f30f720000081565b34801561031457600080fd5b506102ae680ad78ebc5ac620000081565b34801561033157600080fd5b506102ae610340366004612914565b600f60209081526000928352604080842090915290825290205481565b34801561036957600080fd5b5061037d610378366004612947565b610883565b005b34801561038b57600080fd5b506102ae61039a366004612975565b610960565b3480156103ab57600080fd5b5061037d6103ba366004612999565b6109f3565b3480156103cb57600080fd5b506001546103df906001600160a01b031681565b6040516102b891906129bb565b3480156103f857600080fd5b506006546103df906001600160a01b031681565b34801561041857600080fd5b506102ae60c881565b34801561042d57600080fd5b506004546103df906001600160a01b031681565b34801561044d57600080fd5b506102ae61045c366004612975565b610a40565b34801561046d57600080fd5b506102ae6714d1120d7b16000081565b34801561048957600080fd5b5061037d6104983660046129cf565b610aca565b3480156104a957600080fd5b506102ae60115481565b3480156104bf57600080fd5b506102ae670de0b6b3a764000081565b3480156104db57600080fd5b506002546103df906001600160a01b031681565b3480156104fb57600080fd5b50600e5461051690600160801b90046001600160801b031681565b6040516001600160801b0390911681526020016102b8565b34801561053a57600080fd5b506005546103df906001600160a01b031681565b34801561055a57600080fd5b506007546103df906001600160a01b031681565b34801561057a57600080fd5b5061037d610589366004612947565b610cdb565b34801561059a57600080fd5b506102ae670f43fc2c04ee000081565b3480156105b657600080fd5b506102ae610d92565b3480156105cb57600080fd5b506000546103df906001600160a01b031681565b3480156105eb57600080fd5b5061062f6105fa366004612975565b600c602052600090815260409020805460018201546002909201549091906001600160801b0380821691600160801b90041684565b6040805194855260208501939093526001600160801b03918216928401929092521660608201526080016102b8565b34801561066a57600080fd5b506102ae610e8e565b34801561067f57600080fd5b506102ae600d5481565b34801561069557600080fd5b506003546001600160a01b03166103df565b3480156106b357600080fd5b506003546001600160a01b0316331460405190151581526020016102b8565b3480156106de57600080fd5b5061037d6106ed366004612947565b610f53565b3480156106fe57600080fd5b5061072b6040518060400160405280600d81526020016c14dd18589a5b1a5d1e541bdbdb609a1b81525081565b6040516102b89190612a2c565b34801561074457600080fd5b50600e54610516906001600160801b031681565b34801561076457600080fd5b506008546103df906001600160a01b031681565b34801561078457600080fd5b506102ae633b9aca0081565b34801561079c57600080fd5b5061037d6107ab366004612a5f565b610f99565b3480156107bc57600080fd5b5061037d6107cb366004612975565b611471565b3480156107dc57600080fd5b506102ae61150c565b3480156107f157600080fd5b506102ae610800366004612975565b600b6020526000908152604090205481565b6000546001600160a01b031633146108815760405162461bcd60e51b815260206004820152602760248201527f53746162696c697479506f6f6c3a2043616c6c6572206973206e6f74204163746044820152661a5d99541bdbdb60ca1b60648201526084015b60405180910390fd5b565b80156108915761089161152e565b336000908152600b60205260409020546108aa81611724565b60006108b533610960565b905060006108c233610a40565b905060006108d0858361178d565b905060006108de8386612af5565b90506108ea33836117a7565b60006108f68385612af5565b90506109023382611836565b6040518181523390600080516020612ce38339815191529060200160405180910390a260408051868152602081018490523391600080516020612cc3833981519152910160405180910390a26109578561196d565b50505050505050565b6001600160a01b0381166000908152600b60205260408120548082036109895750600092915050565b6001600160a01b0383166000908152600c60209081526040808320815160808101835281548152600182015493810193909352600201546001600160801b0380821692840192909252600160801b9004166060820152906109ea8383611a01565b95945050505050565b6109fb611ae4565b600a54801580610a09575082155b15610a1357505050565b600080610a21848685611b50565b91509150610a2f8282611c25565b610a398486611efe565b5050505050565b6001600160a01b0381166000908152600b6020526040812054808203610a695750600092915050565b6001600160a01b0383166000908152600c60209081526040808320815160808101835281548152600182015493810193909352600201546001600160801b0380821692840192909252600160801b9004166060820152906109ea8383612027565b336000908152600b6020526040902054610ae381611724565b610aec33612117565b610af533612223565b6000610b0033610960565b90506000610b0d33610a40565b90506000610b1b8285612af5565b9050610b273383611836565b60408051848152602081018390523391600080516020612cc3833981519152910160405180910390a26040518281523390600080516020612ce38339815191529060200160405180910390a28260096000828254610b859190612af5565b9091555050600954604051908152600080516020612d038339815191529060200160405180910390a17f342693d2465f6f44931e41128424a0227e0cbc69d1c3917a839e6de71696d44c3384604051610bdf929190612b08565b60405180910390a16004546001600160a01b0316610c675760055460405163abfad25d60e01b81526001600160a01b039091169063abfad25d908590610c309033906000908c908c90600401612b21565b6000604051808303818588803b158015610c4957600080fd5b505af1158015610c5d573d6000803e3d6000fd5b5050505050610cd3565b60055460405163abfad25d60e01b81526001600160a01b039091169063abfad25d90600090610ca090339088908c908c90600401612b21565b6000604051808303818588803b158015610cb957600080fd5b505af1158015610ccd573d6000803e3d6000fd5b50505050505b505050505050565b610ce4816122a1565b336000818152600b602052604081205491610cfe90610960565b90506000610d0b33610a40565b90506000610d198285612af5565b9050610d253386612300565b6000610d3186846128e5565b9050610d3d3382611836565b6040518181523390600080516020612ce38339815191529060200160405180910390a260408051858152602081018490523391600080516020612cc3833981519152910160405180910390a2610cd38461196d565b600080546040805163f07424e960e01b8152905183926001600160a01b03169163f07424e99160048083019260209291908290030181865afa158015610ddc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e009190612b4c565b90506000600160009054906101000a90046001600160a01b03166001600160a01b031663f07424e96040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e7b9190612b4c565b9050610e8781836128e5565b9250505090565b6000805460408051631529a63960e01b8152905183926001600160a01b031691631529a6399160048083019260209291908290030181865afa158015610ed8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610efc9190612b4c565b90506000600160009054906101000a90046001600160a01b03166001600160a01b0316631529a6396040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e57573d6000803e3d6000fd5b610f5b610812565b8060096000828254610f6d91906128e5565b9091555050600954604051908152600080516020612d038339815191529060200160405180910390a150565b6003546001600160a01b03163314610fc35760405162461bcd60e51b815260040161087890612b65565b610fcc876123ce565b610fd5866123ce565b610fde856123ce565b610fe7846123ce565b610ff0836123ce565b610ff9826123ce565b6001600160a01b0381161561101157611011816123ce565b600580546001600160a01b03199081166001600160a01b038a81169182179093556006805483168a85161790556000805483168985161781556007805484168986161790556008805484168886161790556002805484168786161790556004805490931693851693909317825560408051638da5cb5b60e01b815290519192638da5cb5b9282820192602092908290030181865afa1580156110b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110db9190612b9a565b6001600160a01b03161415806111665750600554604080516348d399e760e01b815290516001600160a01b038085169316916348d399e79160048083019260209291908290030181865afa158015611137573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061115b9190612b9a565b6001600160a01b0316145b8015611265575060006001600160a01b0316856001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111da9190612b9a565b6001600160a01b03161415806112655750600054604080516348d399e760e01b815290516001600160a01b038085169316916348d399e79160048083019260209291908290030181865afa158015611236573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061125a9190612b9a565b6001600160a01b0316145b6112e85760405162461bcd60e51b815260206004820152604860248201527f5468652073616d6520636f6c6c61746572616c2061646472657373206d75737460448201527f206265207573656420666f722074686520656e7469726520736574206f6620636064820152676f6e74726163747360c01b608482015260a401610878565b7f3ca631ffcd2a9b5d9ae18543fc82f58eb4ca33af9e6ab01b7a8e95331e6ed9858760405161131791906129bb565b60405180910390a17f143219c9e69b09e07e095fcc889b43d8f46ca892bba65f08dc3a0050869a56788660405161134e91906129bb565b60405180910390a17f78f058b189175430c48dc02699e3a0031ea4ff781536dc2fab847de4babdd8828560405161138591906129bb565b60405180910390a17fe1e858a66c0bbbcdfa22d58dde1e5d42370be20cdb176e560287f85412e546e0846040516113bc91906129bb565b60405180910390a17f65f4cf077bc01e4742eb5ad98326f6e95b63548ea24b17f8d5e823111fe78800836040516113f391906129bb565b60405180910390a17f8c537274438aa850a330284665d81a85dd38267d09e4050d416bfc94142db2648260405161142a91906129bb565b60405180910390a17ffba7421f3d1a98e80d72491a6e0523133444a5842cc7310951d8b82d075a7dff8160405161146191906129bb565b60405180910390a1610957612473565b6003546001600160a01b0316331461149b5760405162461bcd60e51b815260040161087890612b65565b6001600160a01b0381166115005760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610878565b611509816124bd565b50565b6115206103e8670de0b6b3a7640000612bb7565b61152b906005612bd9565b81565b60025460408051630fdb11cf60e01b815290516000926001600160a01b031691630fdb11cf916004808301926020929190829003018187875af1158015611579573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061159d9190612b4c565b90506000600860009054906101000a90046001600160a01b03166001600160a01b0316634d6228316040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115f4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116189190612b9a565b600654604051630d293c7160e41b81529192506000916001600160a01b039091169063d293c710906116509085908790600401612b08565b602060405180830381865afa15801561166d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116919190612b4c565b9050670f43fc2c04ee000081101561171f5760405162461bcd60e51b8152602060048201526044602482018190527f53746162696c697479506f6f6c3a2043616e6e6f742077697468647261772077908201527f68696c65207468657265206172652074726f766573207769746820494352203c6064820152631026a1a960e11b608482015260a401610878565b505050565b600081116115095760405162461bcd60e51b815260206004820152603060248201527f53746162696c697479506f6f6c3a2055736572206d757374206861766520612060448201526f1b9bdb8b5e995c9bc819195c1bdcda5d60821b6064820152608401610878565b600081831061179c578161179e565b825b90505b92915050565b806000036117b3575050565b60075460405163a9059cbb60e01b81526001600160a01b039091169063a9059cbb906117e59085908590600401612b08565b6020604051808303816000875af1158015611804573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118289190612bf0565b506118328161250f565b5050565b6001600160a01b0382166000908152600b602052604081208290558190036118c4576001600160a01b0382166000818152600c602052604080822082815560018101839055600201829055517fc48943df4095f4f20d171fd2872eafdc0eed4d9014ac3672f3bde7fd425449d5916118b8918190918252602082015260400190565b60405180910390a25050565b600e54600d546001600160801b03600160801b80840482166000818152600f6020908152604080832095909716808352948152868220546001600160a01b038a16808452600c8352928890206001810188905581815594840286176002909501949094558651868152908101849052939591949390917fc48943df4095f4f20d171fd2872eafdc0eed4d9014ac3672f3bde7fd425449d5910160405180910390a2505050505050565b806000036119785750565b6000816009546119889190612af5565b6009819055604051818152909150600080516020612d038339815191529060200160405180910390a17f342693d2465f6f44931e41128424a0227e0cbc69d1c3917a839e6de71696d44c33836040516119e2929190612b08565b60405180910390a1600454611832906001600160a01b0316338461255e565b606081015160408083015183516020808601516001600160801b038087166000908152600f84528681209186168152925293812054909493908590611a47908490612af5565b6001600160801b0386166000908152600f6020526040812091925090633b9aca009082611a75886001612c12565b6001600160801b03166001600160801b0316815260200190815260200160002054611aa09190612bb7565b90506000670de0b6b3a764000084611ab884866128e5565b611ac2908d612bd9565b611acc9190612bb7565b611ad69190612bb7565b9a9950505050505050505050565b6006546001600160a01b031633146108815760405162461bcd60e51b815260206004820152602960248201527f53746162696c697479506f6f6c3a2043616c6c6572206973206e6f742054726f6044820152683b32a6b0b730b3b2b960b91b6064820152608401610878565b6000806000601054670de0b6b3a764000087611b6c9190612bd9565b611b7691906128e5565b905083851115611b8857611b88612c39565b838503611ba4576000601155670de0b6b3a76400009150611bf9565b601154600090611bbc670de0b6b3a764000088612bd9565b611bc69190612af5565b9050611bd28582612bb7565b611bdd9060016128e5565b925080611bea8685612bd9565b611bf49190612af5565b601155505b611c038482612bb7565b9250611c0f8484612bd9565b611c199082612af5565b60105550935093915050565b600d546000670de0b6b3a7640000831115611c4257611c42612c39565b6000611c5684670de0b6b3a7640000612af5565b600e546001600160801b03600160801b820481166000818152600f60209081526040808320949095168083529390529283205493945090929091611c9a878a612bd9565b90506000611ca882846128e5565b6001600160801b038581166000818152600f60209081526040808320948b16808452948252918290208590558151858152908101929092528101919091529091507fe12e2cd2c9afa8069203ca07e7eff1edce4a075686d0736a8e7e0d593597b2079060600160405180910390a185600003611dd257611d29846001612c12565b600e80546001600160801b03908116600160801b93821684021791829055604051929091041681527fb50f0f59e7cb5b421dc77581c3a9919e3806e076e5fa78a874c3f120cb7d874d9060200160405180910390a1600e80546001600160801b0319169055604051600081527f1f9dfc70cd666adb18a39d60a797518f7b4febf4b6e24ef37d44f6e1e7219fbe9060200160405180910390a1670de0b6b3a76400009650611eaa565b633b9aca00670de0b6b3a7640000611dea888b612bd9565b611df49190612bb7565b1015611e8a57670de0b6b3a7640000633b9aca00611e12888b612bd9565b611e1c9190612bd9565b611e269190612bb7565b9650611e33856001612c12565b600e80546001600160801b0319166001600160801b039290921691821790556040519081527f1f9dfc70cd666adb18a39d60a797518f7b4febf4b6e24ef37d44f6e1e7219fbe9060200160405180910390a1611eaa565b670de0b6b3a7640000611e9d878a612bd9565b611ea79190612bb7565b96505b60008711611eba57611eba612c39565b600d8790556040518781527fc1a9618cb59ebca77cbdbc2949f126823c407ff13edb285fd0262519a9c18e8c9060200160405180910390a150505050505050505050565b600054604051637b7fc9eb60e11b8152600481018390526001600160a01b0390911690819063f6ff93d690602401600060405180830381600087803b158015611f4657600080fd5b505af1158015611f5a573d6000803e3d6000fd5b50505050611f678261250f565b600754604051632770a7eb60e21b81526001600160a01b0390911690639dc29fac90611f999030908690600401612b08565b600060405180830381600087803b158015611fb357600080fd5b505af1158015611fc7573d6000803e3d6000fd5b5050604051636250216960e01b81526001600160a01b038416925063625021699150611ff99030908790600401612b08565b600060405180830381600087803b15801561201357600080fd5b505af1158015610957573d6000803e3d6000fd5b602081015160408201516060830151600e546000939291906001600160801b03600160801b9091048116908216101561206657600093505050506117a1565b600e5460009081906120829085906001600160801b0316612c4f565b9050806001600160801b03166000036120b55784600d54896120a49190612bd9565b6120ae9190612bb7565b91506120e9565b806001600160801b03166001036120e457633b9aca0085600d548a6120da9190612bd9565b6120a49190612bb7565b600091505b6120f7633b9aca0089612bb7565b82101561210c576000955050505050506117a1565b509695505050505050565b6006546040516321e3780160e01b81526001916001600160a01b0316906321e37801906121489085906004016129bb565b602060405180830381865afa158015612165573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121899190612c85565b600481111561219a5761219a612c6f565b146115095760405162461bcd60e51b815260206004820152604d60248201527f53746162696c697479506f6f6c3a2063616c6c6572206d75737420686176652060448201527f616e206163746976652074726f766520746f20776974686472617720636f6c6c60648201526c61746572616c4761696e20746f60981b608482015260a401610878565b600061222e82610960565b9050600081116118325760405162461bcd60e51b815260206004820152603860248201527f53746162696c697479506f6f6c3a2063616c6c6572206d7573742068617665206044820152773737b716bd32b9379031b7b63630ba32b930b61023b0b4b760411b6064820152608401610878565b600081116115095760405162461bcd60e51b815260206004820152602660248201527f53746162696c697479506f6f6c3a20416d6f756e74206d757374206265206e6f6044820152656e2d7a65726f60d01b6064820152608401610878565b6007546040516323b872dd60e01b81526001600160a01b03848116600483015230602483015260448201849052909116906323b872dd906064016020604051808303816000875af1158015612359573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061237d9190612bf0565b50600081600a5461238e91906128e5565b600a8190556040518181529091507fcacce180ae93727cdc9bb9c98e40c99de5dd6690f7b1fc58abfd51dc7d16469d9060200160405180910390a1505050565b6001600160a01b0381166124245760405162461bcd60e51b815260206004820152601e60248201527f4163636f756e742063616e6e6f74206265207a65726f206164647265737300006044820152606401610878565b803b806118325760405162461bcd60e51b815260206004820181905260248201527f4163636f756e7420636f64652073697a652063616e6e6f74206265207a65726f6044820152606401610878565b6003546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600380546001600160a01b0319169055565b600380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600081600a5461251f9190612af5565b600a8190556040518181529091507fcacce180ae93727cdc9bb9c98e40c99de5dd6690f7b1fc58abfd51dc7d16469d9060200160405180910390a15050565b6001600160a01b03831661260a576000826001600160a01b03168260405160006040518083038185875af1925050503d80600081146125b9576040519150601f19603f3d011682016040523d82523d6000602084013e6125be565b606091505b50509050806126045760405162461bcd60e51b815260206004820152601260248201527114d95b991a5b99c81155120819985a5b195960721b6044820152606401610878565b50505050565b61171f6001600160a01b038416838361171f8363a9059cbb60e01b8484604051602401612638929190612b08565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915260006126bf826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661273f9092919063ffffffff16565b90508051600014806126e05750808060200190518101906126e09190612bf0565b61171f5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610878565b606061274e8484600085612756565b949350505050565b6060824710156127b75760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610878565b600080866001600160a01b031685876040516127d39190612ca6565b60006040518083038185875af1925050503d8060008114612810576040519150601f19603f3d011682016040523d82523d6000602084013e612815565b606091505b509150915061282687838387612831565b979650505050505050565b606083156128a0578251600003612899576001600160a01b0385163b6128995760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610878565b508161274e565b61274e83838151156128b55781518083602001fd5b8060405162461bcd60e51b81526004016108789190612a2c565b634e487b7160e01b600052601160045260246000fd5b808201808211156117a1576117a16128cf565b80356001600160801b038116811461290f57600080fd5b919050565b6000806040838503121561292757600080fd5b612930836128f8565b915061293e602084016128f8565b90509250929050565b60006020828403121561295957600080fd5b5035919050565b6001600160a01b038116811461150957600080fd5b60006020828403121561298757600080fd5b813561299281612960565b9392505050565b600080604083850312156129ac57600080fd5b50508035926020909101359150565b6001600160a01b0391909116815260200190565b600080604083850312156129e257600080fd5b82356129ed81612960565b915060208301356129fd81612960565b809150509250929050565b60005b83811015612a23578181015183820152602001612a0b565b50506000910152565b6020815260008251806020840152612a4b816040850160208701612a08565b601f01601f19169190910160400192915050565b600080600080600080600060e0888a031215612a7a57600080fd5b8735612a8581612960565b96506020880135612a9581612960565b95506040880135612aa581612960565b94506060880135612ab581612960565b93506080880135612ac581612960565b925060a0880135612ad581612960565b915060c0880135612ae581612960565b8091505092959891949750929550565b818103818111156117a1576117a16128cf565b6001600160a01b03929092168252602082015260400190565b6001600160a01b03948516815260208101939093529083166040830152909116606082015260800190565b600060208284031215612b5e57600080fd5b5051919050565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b600060208284031215612bac57600080fd5b815161299281612960565b600082612bd457634e487b7160e01b600052601260045260246000fd5b500490565b80820281158282048414176117a1576117a16128cf565b600060208284031215612c0257600080fd5b8151801515811461299257600080fd5b6001600160801b03818116838216019080821115612c3257612c326128cf565b5092915050565b634e487b7160e01b600052600160045260246000fd5b6001600160801b03828116828216039080821115612c3257612c326128cf565b634e487b7160e01b600052602160045260246000fd5b600060208284031215612c9757600080fd5b81516005811061299257600080fd5b60008251612cb8818460208701612a08565b919091019291505056fe47647c495a7db9471a1b024b3c6f7555a502a0de4b130d83a4d3c8f9cff25939bce78369dccab09eec1986f4d409ab09ffbb47d65423e5148fcf98411c5111c95745610f99463e502f9c3333585fe329b498e36b00b8c1bdfd8dc87dfe35b5eaa2646970667358221220d73a0c77d42945a67ea7d2340b4bb714769d67ea63a7b44fe4c114170b8bfb5f64736f6c63430008110033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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.