Skip to content
Verified contractPartialMIT

StabilityModule

Address0x7e0215b847cac71e20fdad89c8635d7b03ea2db7
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
22,262,203
Creation transaction
0x6c6f8aa4d2…d8781640b1

StabilityModule.sol

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

interface IGovernance {
    function proposeVote(
        address _contract,
        bytes4 _function,
        bytes memory _data
    ) external;

    function executeVote(uint256 _voteCount) external;

    function vote(uint256 _voteCount, bool _supports, bool _abstains) external;

    function transfer(address to, uint256 amount) external returns (bool);

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);

    function team() external returns (address);
}

// File: contracts/contracts/contracts/libraries/Math.sol


// Copied from https://github.com/dapphub/ds-math
// Added the div function from openzepeling safeMath

pragma solidity 0.8.20;

library DSMath {
    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
        require((z = x + y) >= x, "ds-math-add-overflow");
    }

    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        require((z = x - y) <= x, "ds-math-sub-underflow");
    }

    // slither-disable-next-line incorrect-equality
    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return div(a, b, "SafeMath: division by zero");
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    uint256 public constant WAD = 10 ** 18;
    uint256 public constant RAY = 10 ** 28;

    //rounds to zero if x*y < WAD / 2
    function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, y), WAD / 2) / WAD;
    }

    //rounds to zero if x*y < WAD / 2
    function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, y), RAY / 2) / RAY;
    }

    //rounds to zero if x*y < WAD / 2
    function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, WAD), y / 2) / y;
    }

    //rounds to zero if x*y < RAY / 2
    function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = mul((x / mul(y, RAY)), WAD);
    }

    // This famous algorithm is called "exponentiation by squaring"
    // and calculates x^n with x as fixed-point and n as regular unsigned.
    //
    // It's O(log n), instead of O(n) for naive repeated multiplication.
    //
    // These facts are why it works:
    //
    //  If n is even, then x^n = (x^2)^(n/2).
    //  If n is odd,  then x^n = x * x^(n-1),
    //   and applying the equation for even x gives
    //    x^n = x * (x^2)^((n-1) / 2).
    //
    //  Also, EVM division is flooring and
    //    floor[(n-1) / 2] = floor[n / 2].
    //
    // Not sure if this is a false positive - https://github.com/dapphub/ds-math/issues/18
    // slither-disable-next-line weak-prng
    function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
        z = n % 2 != 0 ? x : RAY;

        for (n /= 2; n != 0; n /= 2) {
            x = rmul(x, x);

            if (n % 2 != 0) {
                z = rmul(z, x);
            }
        }
    }

    // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
    function sqrt(uint y) internal pure returns (uint z) {
        if (y > 3) {
            z = y;
            uint x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
    }

    function min(uint x, uint y) internal pure returns (uint z) {
        return x <= y ? x : y;
    }
}

// File: contracts/contracts/contracts/interfaces/IChrysus.sol

pragma solidity 0.8.20;

interface IChrysus {
    function ray() external view returns (uint256);
    function wad() external view returns (uint256);
    function addCollateralType(
        address _collateralType,
        uint256 _collateralRequirement,
        address _oracleAddress
    ) external;
    function allowance(
        address owner,
        address spender
    ) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function approvedCollateral(
        address
    )
        external
        view
        returns (
            bool approved,
            uint256 balance,
            uint256 fees,
            uint256 collateralRequirement,
            address oracle
        );
    function getApprovedTokens() external view returns (address[] memory);
    function balanceOf(address account) external view returns (uint256);
    function collateralRatio() external view returns (uint256);
    function collateralizationRatio() external view returns (uint256);
    function decimals() external view returns (uint8);
    function decreaseAllowance(
        address spender,
        uint256 subtractedValue
    ) external returns (bool);
    function depositCollateral(
        address _collateralType,
        uint256 _amount
    ) external;
    function ethBalance() external view returns (uint256);
    function ethFees() external view returns (uint256);
    function governance() external view returns (address);
    function increaseAllowance(
        address spender,
        uint256 addedValue
    ) external returns (bool);
    function liquidate(address _collateralType) external;
    function liquidationRatio() external view returns (uint256);
    function liquidationReward() external view returns (uint256);
    function stabilityModule() external view returns (address);
    function oracleCHC() external view returns (address);
    function swapSolution() external view returns (address);
    function totalSupply() external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
    function treasury() external view returns (address);
    function userDeposits(
        address,
        address
    ) external view returns (uint256 deposited, uint256 minted);
    function withdrawCollateral(
        address _collateralType,
        uint256 _amount
    ) external;
    function withdrawFees() external;
    function calculateCollateralAmount(
        uint256,
        address
    ) external view returns (uint256);
    function isCollateralApproved(
        address collateral
    ) external view returns (bool);
    function normalizeToWei(
        uint256 amount,
        uint8 decimal
    ) external pure returns (uint256);
    function denormalizeFromWei(
        uint256 amount,
        uint8 decimal
    ) external pure returns (uint256);
    function getCollateralDecimal(
        address collateralType
    ) external view returns (uint8);
}

// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol


// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol


// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

// File: contracts/contracts/contracts/StabilityModule.sol

pragma solidity 0.8.20;






contract StabilityModule is ReentrancyGuard {
    using DSMath for uint256;
    address public immutable governance;
    address public chrysus;

    struct Stake {
        uint256 amount;
        uint256 startTime;
        uint256 endTime;
        uint256 lastGovContractCall;
    }

    uint256 totalPoolAmount;

    mapping(address => Stake) public governanceStakes;

    event LastGovContractCallUpdated(address indexed voter, uint256 timestamp);
    event ContractInitialized(address chrysusAddress);

    modifier mustInit() {
        require(chrysus != address(0), "contract is not initialized");
        _;
    }

    modifier onlyTeam() {
        require(
            msg.sender == IGovernance(governance).team(),
            "can only be call by Governance team"
        );
        _;
    }

    constructor(address _governance) {
        require(_governance != address(0), "Zero address error");
        governance = _governance;
    }

    receive() external payable {}

    function init(address chrysusAddress) external onlyTeam {
        require(chrysusAddress != address(0), "Invalid address");

        chrysus = chrysusAddress;

        emit ContractInitialized(chrysusAddress);
    }

    function stake(uint256 amount) external {
        require(amount > 0, "invaid amount");

        Stake storage s = governanceStakes[msg.sender];
        s.startTime = block.timestamp;
        s.amount += amount;
        s.lastGovContractCall = block.timestamp;
        s.endTime = block.timestamp + 30 days;

        totalPoolAmount += amount;

        bool success = IGovernance(governance).transferFrom(
            msg.sender,
            address(this),
            amount
        );
        require(success, "Failed to transfer specified amount");
    }

    function withdrawStake() external mustInit nonReentrant {
        Stake storage s = governanceStakes[msg.sender];

        require(block.timestamp >= s.endTime, "Stake must be at least 30 days");
        require(s.amount > 0, "Insufficient stake balance");

        uint256 withdrawAmount = s.amount;
        uint256 stakingShare = DSMath.wdiv(withdrawAmount, totalPoolAmount);

        address[] memory Collaterals = IChrysus(chrysus).getApprovedTokens();

        for (uint i = 0; i < Collaterals.length; i++) {
            address collateralType = Collaterals[i];
            uint256 collateralReward = collateralType == address(0)
                ? DSMath.wmul(stakingShare, address(this).balance)
                : DSMath.wmul(
                    stakingShare,
                    IERC20(collateralType).balanceOf(address(this))
                );

            if (collateralReward > 0) {
                if (collateralType == address(0)) {
                    (bool success, ) = msg.sender.call{value: collateralReward}(
                        ""
                    );
                    require(success, "Failed to transfer reward");
                } else {
                    bool success = IERC20(collateralType).transfer(
                        msg.sender,
                        collateralReward
                    );
                    require(success, "Failed to transfer reward");
                }
            }
        }

        s.amount = 0;
        totalPoolAmount -= withdrawAmount;
    }

    function updateLastGovContractCall(address voter) external {
        require(msg.sender == governance, "can only be call by governance");

        governanceStakes[voter].lastGovContractCall = block.timestamp;

        emit LastGovContractCallUpdated(voter, block.timestamp);
    }

    function getGovernanceStake(
        address staker
    ) external view returns (Stake memory) {
        return governanceStakes[staker];
    }

    function getTotalPoolAmount() external view returns (uint256) {
        return totalPoolAmount;
    }
}
Compiler settingsShow
{
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  }
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.