Transaction Hash:
Block:
15723019 at Oct-11-2022 06:16:47 AM +UTC
Transaction Fee:
0.002455011461310114 ETH
$6.19
Gas Used:
107,177 Gas / 22.906140882 Gwei
Emitted Events:
158 |
DCHFToken.Transfer( from=[Receiver] MONStaking, to=[Sender] 0x1e81f5fc5e6856ff3d76ed349065d2055ffcf2b8, value=4822612949922886961 )
|
159 |
MONStaking.StakingGainsDCHFWithdrawn( staker=[Sender] 0x1e81f5fc5e6856ff3d76ed349065d2055ffcf2b8, DCHFGain=4822612949922886961 )
|
160 |
MONStaking.StakerSnapshotsUpdated( _staker=[Sender] 0x1e81f5fc5e6856ff3d76ed349065d2055ffcf2b8, _F_Asset=73017964, _F_DCHF=4584032686278736377 )
|
161 |
MONStaking.StakingGainsAssetWithdrawn( staker=[Sender] 0x1e81f5fc5e6856ff3d76ed349065d2055ffcf2b8, asset=0x00000000...000000000, AssetGain=25164911112 )
|
162 |
MONStaking.AssetSent( _asset=0x00000000...000000000, _account=[Sender] 0x1e81f5fc5e6856ff3d76ed349065d2055ffcf2b8, _amount=25164911112 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x045da4bF...737727A36 | |||||
0x1E81F5FC...55FFcf2B8 |
0.075584721898971321 Eth
Nonce: 252
|
0.073129735602572319 Eth
Nonce: 253
| 0.002454986296399002 | ||
0x388C818C...7ccB19297
Miner
| (Lido: Execution Layer Rewards Vault) | 168.703969574542714916 Eth | 168.704130340042714916 Eth | 0.0001607655 | |
0x8Bc3702c...34Ae0C56F | (DeFi Franc: MON Staking) | 0.000036950194823048 Eth | 0.000036925029911936 Eth | 0.000000025164911112 |
Execution Trace
MONStaking.unstake( _MONamount=0 )
DCHFToken.transfer( recipient=0x1E81F5FC5e6856ff3d76ED349065d2055FFcf2B8, amount=4822612949922886961 ) => ( True )
-
StabilityPoolManager.isStabilityPool( stabilityPool=0x1E81F5FC5e6856ff3d76ED349065d2055FFcf2B8 ) => ( False )
-
- ETH 0.000000025164911112
0x1e81f5fc5e6856ff3d76ed349065d2055ffcf2b8.CALL( )
File 1 of 3: MONStaking
File 2 of 3: DCHFToken
File 3 of 3: StabilityPoolManager
// SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../Dependencies/BaseMath.sol"; import "../Dependencies/CheckContract.sol"; import "../Dependencies/DfrancMath.sol"; import "../Dependencies/Initializable.sol"; import "../Interfaces/IMONStaking.sol"; import "../Interfaces/IDeposit.sol"; import "../Dependencies/SafetyTransfer.sol"; contract MONStaking is \tIMONStaking, \tPausable, \tOwnable, \tCheckContract, \tBaseMath, \tReentrancyGuard, \tInitializable { \tusing SafeMath for uint256; \tusing SafeERC20 for IERC20; \tbool public isInitialized; \t// --- Data --- \tstring public constant NAME = "MONStaking"; \taddress constant ETH_REF_ADDRESS = address(0); \tmapping(address => uint256) public stakes; \tuint256 public totalMONStaked; \tmapping(address => uint256) public F_ASSETS; // Running sum of ETH fees per-MON-staked \tuint256 public F_DCHF; // Running sum of MON fees per-MON-staked \t// User snapshots of F_ETH and F_DCHF, taken at the point at which their latest deposit was made \tmapping(address => Snapshot) public snapshots; \tstruct Snapshot { \t\tmapping(address => uint256) F_ASSET_Snapshot; \t\tuint256 F_DCHF_Snapshot; \t} \taddress[] ASSET_TYPE; \tmapping(address => bool) isAssetTracked; \tmapping(address => uint256) public sentToTreasuryTracker; \tIERC20 public monToken; \tIERC20 public dchfToken; \taddress public troveManagerAddress; \taddress public troveManagerHelpersAddress; \taddress public borrowerOperationsAddress; \taddress public activePoolAddress; \taddress public treasury; \t// --- Functions --- \tfunction setAddresses( \t\taddress _monTokenAddress, \t\taddress _dchfTokenAddress, \t\taddress _troveManagerAddress, \t\taddress _troveManagerHelpersAddress, \t\taddress _borrowerOperationsAddress, \t\taddress _activePoolAddress, \t\taddress _treasury \t) external override initializer { \t\trequire(!isInitialized, "Already Initialized"); \t\trequire(_treasury != address(0), "Invalid Treausry Address"); \t\tcheckContract(_monTokenAddress); \t\tcheckContract(_dchfTokenAddress); \t\tcheckContract(_troveManagerAddress); \t\tcheckContract(_troveManagerHelpersAddress); \t\tcheckContract(_borrowerOperationsAddress); \t\tcheckContract(_activePoolAddress); \t\tisInitialized = true; \t\t_pause(); \t\tmonToken = IERC20(_monTokenAddress); \t\tdchfToken = IERC20(_dchfTokenAddress); \t\ttroveManagerAddress = _troveManagerAddress; \t\ttroveManagerHelpersAddress = _troveManagerHelpersAddress; \t\tborrowerOperationsAddress = _borrowerOperationsAddress; \t\tactivePoolAddress = _activePoolAddress; \t\ttreasury = _treasury; \t\tisAssetTracked[ETH_REF_ADDRESS] = true; \t\tASSET_TYPE.push(ETH_REF_ADDRESS); \t\temit MONTokenAddressSet(_monTokenAddress); \t\temit MONTokenAddressSet(_dchfTokenAddress); \t\temit TroveManagerAddressSet(_troveManagerAddress); \t\temit BorrowerOperationsAddressSet(_borrowerOperationsAddress); \t\temit ActivePoolAddressSet(_activePoolAddress); \t} \t// If caller has a pre-existing stake, send any accumulated ETH and DCHF gains to them. \tfunction stake(uint256 _MONamount) external override nonReentrant whenNotPaused { \t\trequire(_MONamount > 0, "MON amount is zero"); \t\tuint256 currentStake = stakes[msg.sender]; \t\tuint256 assetLength = ASSET_TYPE.length; \t\tuint256 AssetGain; \t\taddress asset; \t\tfor (uint256 i = 0; i < assetLength; i++) { \t\t\tasset = ASSET_TYPE[i]; \t\t\tif (currentStake != 0) { \t\t\t\tAssetGain = _getPendingAssetGain(asset, msg.sender); \t\t\t\tif (i == 0) { \t\t\t\t\tuint256 DCHFGain = _getPendingDCHFGain(msg.sender); \t\t\t\t\tdchfToken.safeTransfer(msg.sender, DCHFGain); \t\t\t\t\temit StakingGainsDCHFWithdrawn(msg.sender, DCHFGain); \t\t\t\t} \t\t\t\t_sendAssetGainToUser(asset, AssetGain); \t\t\t\temit StakingGainsAssetWithdrawn(msg.sender, asset, AssetGain); \t\t\t} \t\t\t_updateUserSnapshots(asset, msg.sender); \t\t} \t\tuint256 newStake = currentStake.add(_MONamount); \t\t// Increase user’s stake and total MON staked \t\tstakes[msg.sender] = newStake; \t\ttotalMONStaked = totalMONStaked.add(_MONamount); \t\temit TotalMONStakedUpdated(totalMONStaked); \t\t// Transfer MON from caller to this contract \t\tmonToken.safeTransferFrom(msg.sender, address(this), _MONamount); \t\temit StakeChanged(msg.sender, newStake); \t} \t// Unstake the MON and send the it back to the caller, along with their accumulated DCHF & ETH gains. \t// If requested amount > stake, send their entire stake. \tfunction unstake(uint256 _MONamount) external override nonReentrant { \t\tuint256 currentStake = stakes[msg.sender]; \t\t_requireUserHasStake(currentStake); \t\tuint256 assetLength = ASSET_TYPE.length; \t\tuint256 AssetGain; \t\taddress asset; \t\tfor (uint256 i = 0; i < assetLength; i++) { \t\t\tasset = ASSET_TYPE[i]; \t\t\t// Grab any accumulated ETH and DCHF gains from the current stake \t\t\tAssetGain = _getPendingAssetGain(asset, msg.sender); \t\t\tif (i == 0) { \t\t\t\tuint256 DCHFGain = _getPendingDCHFGain(msg.sender); \t\t\t\tdchfToken.safeTransfer(msg.sender, DCHFGain); \t\t\t\temit StakingGainsDCHFWithdrawn(msg.sender, DCHFGain); \t\t\t} \t\t\t_updateUserSnapshots(asset, msg.sender); \t\t\temit StakingGainsAssetWithdrawn(msg.sender, asset, AssetGain); \t\t\t_sendAssetGainToUser(asset, AssetGain); \t\t} \t\tif (_MONamount > 0) { \t\t\tuint256 MONToWithdraw = DfrancMath._min(_MONamount, currentStake); \t\t\tuint256 newStake = currentStake.sub(MONToWithdraw); \t\t\t// Decrease user's stake and total MON staked \t\t\tstakes[msg.sender] = newStake; \t\t\ttotalMONStaked = totalMONStaked.sub(MONToWithdraw); \t\t\temit TotalMONStakedUpdated(totalMONStaked); \t\t\t// Transfer unstaked MON to user \t\t\tmonToken.safeTransfer(msg.sender, MONToWithdraw); \t\t\temit StakeChanged(msg.sender, newStake); \t\t} \t} \tfunction pause() public onlyOwner { \t\t_pause(); \t} \tfunction unpause() external onlyOwner { \t\t_unpause(); \t} \tfunction changeTreasuryAddress(address _treasury) public onlyOwner { \t\trequire(_treasury != address(0), "Treasury address is zero"); \t\ttreasury = _treasury; \t\temit TreasuryAddressChanged(_treasury); \t} \t// --- Reward-per-unit-staked increase functions. Called by Dfranc core contracts --- \tfunction increaseF_Asset(address _asset, uint256 _AssetFee) \t\texternal \t\toverride \t\tcallerIsTroveManager \t{ \t\tif (paused()) { \t\t\tsendToTreasury(_asset, _AssetFee); \t\t\treturn; \t\t} \t\tif (!isAssetTracked[_asset]) { \t\t\tisAssetTracked[_asset] = true; \t\t\tASSET_TYPE.push(_asset); \t\t} \t\tuint256 AssetFeePerMONStaked; \t\tif (totalMONStaked > 0) { \t\t\tAssetFeePerMONStaked = _AssetFee.mul(DECIMAL_PRECISION).div(totalMONStaked); \t\t} \t\tF_ASSETS[_asset] = F_ASSETS[_asset].add(AssetFeePerMONStaked); \t\temit F_AssetUpdated(_asset, F_ASSETS[_asset]); \t} \tfunction increaseF_DCHF(uint256 _DCHFFee) external override callerIsBorrowerOperations { \t\tif (paused()) { \t\t\tsendToTreasury(address(dchfToken), _DCHFFee); \t\t\treturn; \t\t} \t\tuint256 DCHFFeePerMONStaked; \t\tif (totalMONStaked > 0) { \t\t\tDCHFFeePerMONStaked = _DCHFFee.mul(DECIMAL_PRECISION).div(totalMONStaked); \t\t} \t\tF_DCHF = F_DCHF.add(DCHFFeePerMONStaked); \t\temit F_DCHFUpdated(F_DCHF); \t} \tfunction sendToTreasury(address _asset, uint256 _amount) internal { \t\t_sendAsset(treasury, _asset, _amount); \t\tsentToTreasuryTracker[_asset] += _amount; \t\temit SentToTreasury(_asset, _amount); \t} \t// --- Pending reward functions --- \tfunction getPendingAssetGain(address _asset, address _user) \t\texternal \t\tview \t\toverride \t\treturns (uint256) \t{ \t\treturn _getPendingAssetGain(_asset, _user); \t} \tfunction _getPendingAssetGain(address _asset, address _user) \t\tinternal \t\tview \t\treturns (uint256) \t{ \t\tuint256 F_ASSET_Snapshot = snapshots[_user].F_ASSET_Snapshot[_asset]; \t\tuint256 AssetGain = stakes[_user].mul(F_ASSETS[_asset].sub(F_ASSET_Snapshot)).div( \t\t\tDECIMAL_PRECISION \t\t); \t\treturn AssetGain; \t} \tfunction getPendingDCHFGain(address _user) external view override returns (uint256) { \t\treturn _getPendingDCHFGain(_user); \t} \tfunction _getPendingDCHFGain(address _user) internal view returns (uint256) { \t\tuint256 F_DCHF_Snapshot = snapshots[_user].F_DCHF_Snapshot; \t\tuint256 DCHFGain = stakes[_user].mul(F_DCHF.sub(F_DCHF_Snapshot)).div(DECIMAL_PRECISION); \t\treturn DCHFGain; \t} \t// --- Internal helper functions --- \tfunction _updateUserSnapshots(address _asset, address _user) internal { \t\tsnapshots[_user].F_ASSET_Snapshot[_asset] = F_ASSETS[_asset]; \t\tsnapshots[_user].F_DCHF_Snapshot = F_DCHF; \t\temit StakerSnapshotsUpdated(_user, F_ASSETS[_asset], F_DCHF); \t} \tfunction _sendAssetGainToUser(address _asset, uint256 _assetGain) internal { \t\t_assetGain = SafetyTransfer.decimalsCorrection(_asset, _assetGain); \t\t_sendAsset(msg.sender, _asset, _assetGain); \t\temit AssetSent(_asset, msg.sender, _assetGain); \t} \tfunction _sendAsset( \t\taddress _sendTo, \t\taddress _asset, \t\tuint256 _amount \t) internal { \t\tif (_asset == ETH_REF_ADDRESS) { \t\t\t(bool success, ) = _sendTo.call{ value: _amount }(""); \t\t\trequire(success, "MONStaking: Failed to send accumulated AssetGain"); \t\t} else { \t\t\tIERC20(_asset).safeTransfer(_sendTo, _amount); \t\t} \t} \t// --- 'require' functions --- \tmodifier callerIsTroveManager() { \t\trequire( \t\t\tmsg.sender == troveManagerAddress || msg.sender == troveManagerHelpersAddress, \t\t\t"MONStaking: caller is not TroveM" \t\t); \t\t_; \t} \tmodifier callerIsBorrowerOperations() { \t\trequire(msg.sender == borrowerOperationsAddress, "MONStaking: caller is not BorrowerOps"); \t\t_; \t} \tmodifier callerIsActivePool() { \t\trequire(msg.sender == activePoolAddress, "MONStaking: caller is not ActivePool"); \t\t_; \t} \tfunction _requireUserHasStake(uint256 currentStake) internal pure { \t\trequire(currentStake > 0, "MONStaking: User must have a non-zero stake"); \t} \treceive() external payable callerIsActivePool {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. 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 mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. 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 mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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; 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 make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.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; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } 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)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } 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"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @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"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; abstract contract BaseMath { \tuint256 public constant DECIMAL_PRECISION = 1 ether; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; contract CheckContract { \tfunction checkContract(address _account) internal view { \t\trequire(_account != address(0), "Account cannot be zero address"); \t\tuint256 size; \t\tassembly { \t\t\tsize := extcodesize(_account) \t\t} \t\trequire(size > 0, "Account code size cannot be zero"); \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; library DfrancMath { \tusing SafeMath for uint256; \tuint256 internal constant DECIMAL_PRECISION = 1 ether; \t/* Precision for Nominal ICR (independent of price). Rationale for the value: \t * \t * - Making it “too high” could lead to overflows. \t * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division. \t * \t * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH, \t * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator. \t * \t */ \tuint256 internal constant NICR_PRECISION = 1e20; \tfunction _min(uint256 _a, uint256 _b) internal pure returns (uint256) { \t\treturn (_a < _b) ? _a : _b; \t} \tfunction _max(uint256 _a, uint256 _b) internal pure returns (uint256) { \t\treturn (_a >= _b) ? _a : _b; \t} \t/* \t * Multiply two decimal numbers and use normal rounding rules: \t * -round product up if 19'th mantissa digit >= 5 \t * -round product down if 19'th mantissa digit < 5 \t * \t * Used only inside the exponentiation, _decPow(). \t */ \tfunction decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) { \t\tuint256 prod_xy = x.mul(y); \t\tdecProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION); \t} \t/* \t * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. \t * \t * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. \t * \t * Called by two functions that represent time in units of minutes: \t * 1) TroveManager._calcDecayedBaseRate \t * 2) CommunityIssuance._getCumulativeIssuanceFraction \t * \t * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals \t * "minutes in 1000 years": 60 * 24 * 365 * 1000 \t * \t * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be \t * negligibly different from just passing the cap, since: \t * \t * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years \t * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible \t */ \tfunction _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) { \t\tif (_minutes > 525600000) { \t\t\t_minutes = 525600000; \t\t} // cap to avoid overflow \t\tif (_minutes == 0) { \t\t\treturn DECIMAL_PRECISION; \t\t} \t\tuint256 y = DECIMAL_PRECISION; \t\tuint256 x = _base; \t\tuint256 n = _minutes; \t\t// Exponentiation-by-squaring \t\twhile (n > 1) { \t\t\tif (n % 2 == 0) { \t\t\t\tx = decMul(x, x); \t\t\t\tn = n.div(2); \t\t\t} else { \t\t\t\t// if (n % 2 != 0) \t\t\t\ty = decMul(x, y); \t\t\t\tx = decMul(x, x); \t\t\t\tn = (n.sub(1)).div(2); \t\t\t} \t\t} \t\treturn decMul(x, y); \t} \tfunction _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) { \t\treturn (_a >= _b) ? _a.sub(_b) : _b.sub(_a); \t} \tfunction _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) { \t\tif (_debt > 0) { \t\t\treturn _coll.mul(NICR_PRECISION).div(_debt); \t\t} \t\t// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. \t\telse { \t\t\t// if (_debt == 0) \t\t\treturn 2**256 - 1; \t\t} \t} \tfunction _computeCR( \t\tuint256 _coll, \t\tuint256 _debt, \t\tuint256 _price \t) internal pure returns (uint256) { \t\tif (_debt > 0) { \t\t\treturn _coll.mul(_price).div(_debt); \t\t} \t\t// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR. \t\telse { \t\t\t// if (_debt == 0) \t\t\treturn type(uint256).max; \t\t} \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/utils/Address.sol"; abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Internal function that returns the initialized version. Returns `_initialized` */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Internal function that returns the initialized version. Returns `_initializing` */ function _isInitializing() internal view returns (bool) { return _initializing; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IMONStaking { \t// --- Events -- \tevent TreasuryAddressChanged(address _treausury); \tevent SentToTreasury(address indexed _asset, uint256 _amount); \tevent MONTokenAddressSet(address _MONTokenAddress); \tevent DCHFTokenAddressSet(address _dchfTokenAddress); \tevent TroveManagerAddressSet(address _troveManager); \tevent BorrowerOperationsAddressSet(address _borrowerOperationsAddress); \tevent ActivePoolAddressSet(address _activePoolAddress); \tevent StakeChanged(address indexed staker, uint256 newStake); \tevent StakingGainsAssetWithdrawn( \t\taddress indexed staker, \t\taddress indexed asset, \t\tuint256 AssetGain \t); \tevent StakingGainsDCHFWithdrawn(address indexed staker, uint256 DCHFGain); \tevent F_AssetUpdated(address indexed _asset, uint256 _F_ASSET); \tevent F_DCHFUpdated(uint256 _F_DCHF); \tevent TotalMONStakedUpdated(uint256 _totalMONStaked); \tevent AssetSent(address indexed _asset, address indexed _account, uint256 _amount); \tevent StakerSnapshotsUpdated(address _staker, uint256 _F_Asset, uint256 _F_DCHF); \tfunction monToken() external view returns (IERC20); \t// --- Functions --- \tfunction setAddresses( \t\taddress _MONTokenAddress, \t\taddress _dchfTokenAddress, \t\taddress _troveManagerAddress, \t\taddress _troveManagerHelpersAddress, \t\taddress _borrowerOperationsAddress, \t\taddress _activePoolAddress, \t\taddress _treasury \t) external; \tfunction stake(uint256 _MONamount) external; \tfunction unstake(uint256 _MONamount) external; \tfunction increaseF_Asset(address _asset, uint256 _AssetFee) external; \tfunction increaseF_DCHF(uint256 _MONFee) external; \tfunction getPendingAssetGain(address _asset, address _user) external view returns (uint256); \tfunction getPendingDCHFGain(address _user) external view returns (uint256); } pragma solidity ^0.8.14; interface IDeposit { \tfunction receivedERC20(address _asset, uint256 _amount) external; } import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./ERC20Decimals.sol"; library SafetyTransfer { \tusing SafeMath for uint256; \t//_amount is in ether (1e18) and we want to convert it to the token decimal \tfunction decimalsCorrection(address _token, uint256 _amount) \t\tinternal \t\tview \t\treturns (uint256) \t{ \t\tif (_token == address(0)) return _amount; \t\tif (_amount == 0) return 0; \t\tuint8 decimals = ERC20Decimals(_token).decimals(); \t\tif (decimals < 18) { \t\t\treturn _amount.div(10**(18 - decimals)); \t\t} else { \t\t\treturn _amount.mul(10**(decimals - 18)); \t\t} \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount ) external returns (bool); /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(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) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason 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 { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.14; interface ERC20Decimals { \tfunction decimals() external view returns (uint8); }
File 2 of 3: DCHFToken
// SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Dependencies/CheckContract.sol"; import "./Interfaces/IDCHFToken.sol"; /* * DCHFToken contract valid for both V1 and V2: * * It allows to have 2 or more TroveManagers registered that can mint and burn. * It allows to have 2 or more BorrowerOperations registered that can mint and burn. * * Two public arrays record the TroveManager and BorrowerOps addresses registered. * * Two events are logged when modifying the array of troveManagers and borrowerOps. * * The different modifiers are updated and check if either one of the TroveManagers * or BorrowerOperations are making the call with mapping(address => bool). * * functions addTroveManager and addBorrowerOps register new contracts into the array. * * functions removeTroveManager and removeBorrowerOps enable the removal of a contract * from both the mapping and the public array. * * Additional checks in place in order to ensure that the addresses added are real * TroveManager or BorrowerOps contracts. */ interface ITroveManager { \tfunction isContractTroveManager() external pure returns (bool); } interface IBorrowerOps { \tfunction isContractBorrowerOps() external pure returns (bool); } contract DCHFToken is CheckContract, IDCHFToken, Ownable { \tusing SafeMath for uint256; \taddress[] public troveManagers; \taddress[] public borrowerOps; \tIStabilityPoolManager public immutable stabilityPoolManager; \tmapping(address => bool) public emergencyStopMintingCollateral; \tmapping(address => bool) public validTroveManagers; \tmapping(address => bool) public validBorrowerOps; \tevent EmergencyStopMintingCollateral(address _asset, bool state); \tevent UpdateTroveManagers(address[] troveManagers); \tevent UpdateBorrowerOps(address[] borrowerOps); \tconstructor(address _stabilityPoolManagerAddress) ERC20("Defi Franc", "DCHF") { \t\tcheckContract(_stabilityPoolManagerAddress); \t\tstabilityPoolManager = IStabilityPoolManager(_stabilityPoolManagerAddress); \t\temit StabilityPoolAddressChanged(_stabilityPoolManagerAddress); \t} \t// --- Functions for intra-Dfranc calls --- \tfunction emergencyStopMinting(address _asset, bool status) external override onlyOwner { \t\temergencyStopMintingCollateral[_asset] = status; \t\temit EmergencyStopMintingCollateral(_asset, status); \t} \tfunction mint( \t\taddress _asset, \t\taddress _account, \t\tuint256 _amount \t) external override { \t\t_requireCallerIsBorrowerOperations(); \t\trequire(!emergencyStopMintingCollateral[_asset], "Mint is blocked on this collateral"); \t\t_mint(_account, _amount); \t} \tfunction burn(address _account, uint256 _amount) external override { \t\t_requireCallerIsBOorTroveMorSP(); \t\t_burn(_account, _amount); \t} \tfunction sendToPool( \t\taddress _sender, \t\taddress _poolAddress, \t\tuint256 _amount \t) external override { \t\t_requireCallerIsStabilityPool(); \t\t_transfer(_sender, _poolAddress, _amount); \t} \tfunction returnFromPool( \t\taddress _poolAddress, \t\taddress _receiver, \t\tuint256 _amount \t) external override { \t\t_requireCallerIsTroveMorSP(); \t\t_transfer(_poolAddress, _receiver, _amount); \t} \t// --- External functions --- \tfunction transfer(address recipient, uint256 amount) public override returns (bool) { \t\t_requireValidRecipient(recipient); \t\treturn super.transfer(recipient, amount); \t} \tfunction transferFrom( \t\taddress sender, \t\taddress recipient, \t\tuint256 amount \t) public override returns (bool) { \t\t_requireValidRecipient(recipient); \t\treturn super.transferFrom(sender, recipient, amount); \t} \tfunction addTroveManager(address _troveManager) external override onlyOwner { \t\tCheckContract(_troveManager); \t\tassert(ITroveManager(_troveManager).isContractTroveManager()); \t\trequire(!validTroveManagers[_troveManager], "TroveManager already exists"); \t\tvalidTroveManagers[_troveManager] = true; \t\ttroveManagers.push(_troveManager); \t\temit UpdateTroveManagers(troveManagers); \t} \tfunction removeTroveManager(address _troveManager) external override onlyOwner { \t\trequire(validTroveManagers[_troveManager], "TroveManager does not exist"); \t\tdelete validTroveManagers[_troveManager]; \t\t_removeElement(troveManagers, _troveManager); \t\temit UpdateTroveManagers(troveManagers); \t} \tfunction addBorrowerOps(address _borrowerOps) external override onlyOwner { \t\tCheckContract(_borrowerOps); \t\tassert(IBorrowerOps(_borrowerOps).isContractBorrowerOps()); \t\trequire(!validBorrowerOps[_borrowerOps], "BorrowerOps already exists"); \t\tvalidBorrowerOps[_borrowerOps] = true; \t\tborrowerOps.push(_borrowerOps); \t\temit UpdateBorrowerOps(borrowerOps); \t} \tfunction removeBorrowerOps(address _borrowerOps) external override onlyOwner { \t\trequire(validBorrowerOps[_borrowerOps], "BorrowerOps does not exist"); \t\tdelete validBorrowerOps[_borrowerOps]; \t\t_removeElement(borrowerOps, _borrowerOps); \t\temit UpdateBorrowerOps(borrowerOps); \t} \t// --- Internal functions --- \tfunction _removeElement(address[] storage _array, address _contract) internal { \t\tfor (uint256 i; i < _array.length; i++) { \t\t\tif (_array[i] == _contract) { \t\t\t\t_array[i] = _array[_array.length - 1]; \t\t\t\t_array.pop(); \t\t\t\tbreak; \t\t\t} \t\t} \t} \t// --- 'require' functions --- \tfunction _requireValidRecipient(address _recipient) internal view { \t\trequire( \t\t\t_recipient != address(0) && _recipient != address(this), \t\t\t"DCHF: Cannot transfer tokens directly to the DCHF token contract or the zero address" \t\t); \t\trequire( \t\t\t!stabilityPoolManager.isStabilityPool(_recipient) && \t\t\t\t!validTroveManagers[_recipient] && \t\t\t\t!validBorrowerOps[_recipient], \t\t\t"DCHF: Cannot transfer tokens directly to the StabilityPool, TroveManager or BorrowerOps" \t\t); \t} \tfunction _requireCallerIsBorrowerOperations() internal view { \t\trequire(validBorrowerOps[msg.sender], "DCHFToken: Caller is not BorrowerOperations"); \t} \tfunction _requireCallerIsBOorTroveMorSP() internal view { \t\trequire( \t\t\tvalidBorrowerOps[msg.sender] || \t\t\t\tvalidTroveManagers[msg.sender] || \t\t\t\tstabilityPoolManager.isStabilityPool(msg.sender), \t\t\t"DCHF: Caller is neither BorrowerOperations nor TroveManager nor StabilityPool" \t\t); \t} \tfunction _requireCallerIsStabilityPool() internal view { \t\trequire( \t\t\tstabilityPoolManager.isStabilityPool(msg.sender), \t\t\t"DCHF: Caller is not the StabilityPool" \t\t); \t} \tfunction _requireCallerIsTroveMorSP() internal view { \t\trequire( \t\t\tvalidTroveManagers[msg.sender] || stabilityPoolManager.isStabilityPool(msg.sender), \t\t\t"DCHF: Caller is neither TroveManager nor StabilityPool" \t\t); \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. 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 mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. 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 mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; contract CheckContract { \tfunction checkContract(address _account) internal view { \t\trequire(_account != address(0), "Account cannot be zero address"); \t\tuint256 size; \t\tassembly { \t\t\tsize := extcodesize(_account) \t\t} \t\trequire(size > 0, "Account code size cannot be zero"); \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "../Dependencies/ERC20Permit.sol"; import "../Interfaces/IStabilityPoolManager.sol"; abstract contract IDCHFToken is ERC20Permit { \t// --- Events --- \tevent StabilityPoolAddressChanged(address _newStabilityPoolAddress); \tevent DCHFTokenBalanceUpdated(address _user, uint256 _amount); \tfunction emergencyStopMinting(address _asset, bool status) external virtual; \tfunction addTroveManager(address _troveManager) external virtual; \tfunction removeTroveManager(address _troveManager) external virtual; \tfunction addBorrowerOps(address _borrowerOps) external virtual; \tfunction removeBorrowerOps(address _borrowerOps) external virtual; \tfunction mint( \t\taddress _asset, \t\taddress _account, \t\tuint256 _amount \t) external virtual; \tfunction burn(address _account, uint256 _amount) external virtual; \tfunction sendToPool( \t\taddress _sender, \t\taddress poolAddress, \t\tuint256 _amount \t) external virtual; \tfunction returnFromPool( \t\taddress poolAddress, \t\taddress user, \t\tuint256 _amount \t) external virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.14; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; interface IERC2612Permit { \t/** \t * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, \t * given `owner`'s signed approval. \t * \t * IMPORTANT: The same issues {IERC20-approve} has related to transaction \t * ordering also apply here. \t * \t * Emits an {Approval} event. \t * \t * Requirements: \t * \t * - `owner` cannot be the zero address. \t * - `spender` cannot be the zero address. \t * - `deadline` must be a timestamp in the future. \t * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` \t * over the EIP712-formatted function arguments. \t * - the signature must use ``owner``'s current nonce (see {nonces}). \t * \t * For more information on the signature format, see the \t * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP \t * section]. \t */ \tfunction permit( \t\taddress owner, \t\taddress spender, \t\tuint256 amount, \t\tuint256 deadline, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) external; \t/** \t * @dev Returns the current ERC2612 nonce for `owner`. This value must be \t * included whenever a signature is generated for {permit}. \t * \t * Every successful call to {permit} increases ``owner``'s nonce by one. This \t * prevents a signature from being used multiple times. \t */ \tfunction nonces(address owner) external view returns (uint256); } abstract contract ERC20Permit is ERC20, IERC2612Permit { \tusing Counters for Counters.Counter; \tmapping(address => Counters.Counter) private _nonces; \t// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); \tbytes32 public constant PERMIT_TYPEHASH = \t\t0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; \tbytes32 public DOMAIN_SEPARATOR; \tconstructor() { \t\tuint256 chainID; \t\tassembly { \t\t\tchainID := chainid() \t\t} \t\tDOMAIN_SEPARATOR = keccak256( \t\t\tabi.encode( \t\t\t\tkeccak256( \t\t\t\t\t"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" \t\t\t\t), \t\t\t\tkeccak256(bytes(name())), \t\t\t\tkeccak256(bytes("1")), // Version \t\t\t\tchainID, \t\t\t\taddress(this) \t\t\t) \t\t); \t} \t/** \t * @dev See {IERC2612Permit-permit}. \t * \t */ \tfunction permit( \t\taddress owner, \t\taddress spender, \t\tuint256 amount, \t\tuint256 deadline, \t\tuint8 v, \t\tbytes32 r, \t\tbytes32 s \t) external virtual override { \t\trequire(block.timestamp <= deadline, "Permit: expired deadline"); \t\tbytes32 hashStruct = keccak256( \t\t\tabi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline) \t\t); \t\tbytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); \t\taddress signer = ecrecover(_hash, v, r, s); \t\trequire(signer != address(0) && signer == owner, "ERC20Permit: Invalid signature"); \t\t_nonces[owner].increment(); \t\t_approve(owner, spender, amount); \t} \t/** \t * @dev See {IERC2612Permit-nonces}. \t */ \tfunction nonces(address owner) public view override returns (uint256) { \t\treturn _nonces[owner].current(); \t} \tfunction chainId() public view returns (uint256 chainID) { \t\tassembly { \t\t\tchainID := chainid() \t\t} \t} } pragma solidity ^0.8.14; import "./IStabilityPool.sol"; interface IStabilityPoolManager { \tevent StabilityPoolAdded(address asset, address stabilityPool); \tevent StabilityPoolRemoved(address asset, address stabilityPool); \tfunction isStabilityPool(address stabilityPool) external view returns (bool); \tfunction addStabilityPool(address asset, address stabilityPool) external; \tfunction getAssetStabilityPool(address asset) external view returns (IStabilityPool); \tfunction unsafeGetAssetStabilityPool(address asset) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount ) external returns (bool); /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "./IDeposit.sol"; interface IStabilityPool is IDeposit { \t// --- Events --- \tevent StabilityPoolAssetBalanceUpdated(uint256 _newBalance); \tevent StabilityPoolDCHFBalanceUpdated(uint256 _newBalance); \tevent BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); \tevent TroveManagerAddressChanged(address _newTroveManagerAddress); \tevent DefaultPoolAddressChanged(address _newDefaultPoolAddress); \tevent DCHFTokenAddressChanged(address _newDCHFTokenAddress); \tevent SortedTrovesAddressChanged(address _newSortedTrovesAddress); \tevent CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); \tevent P_Updated(uint256 _P); \tevent S_Updated(uint256 _S, uint128 _epoch, uint128 _scale); \tevent G_Updated(uint256 _G, uint128 _epoch, uint128 _scale); \tevent EpochUpdated(uint128 _currentEpoch); \tevent ScaleUpdated(uint128 _currentScale); \tevent DepositSnapshotUpdated(address indexed _depositor, uint256 _P, uint256 _S, uint256 _G); \tevent SystemSnapshotUpdated(uint256 _P, uint256 _G); \tevent UserDepositChanged(address indexed _depositor, uint256 _newDeposit); \tevent StakeChanged(uint256 _newSystemStake, address _depositor); \tevent AssetGainWithdrawn(address indexed _depositor, uint256 _Asset, uint256 _DCHFLoss); \tevent MONPaidToDepositor(address indexed _depositor, uint256 _MON); \tevent AssetSent(address _to, uint256 _amount); \t// --- Functions --- \tfunction NAME() external view returns (string memory name); \t/* \t * Called only once on init, to set addresses of other Dfranc contracts \t * Callable only by owner, renounces ownership at the end \t */ \tfunction setAddresses( \t\taddress _assetAddress, \t\taddress _borrowerOperationsAddress, \t\taddress _troveManagerAddress, \t\taddress _troveManagerHelperAddress, \t\taddress _dchfTokenAddress, \t\taddress _sortedTrovesAddress, \t\taddress _communityIssuanceAddress, \t\taddress _dfrancParamsAddress \t) external; \t/* \t * Initial checks: \t * - Frontend is registered or zero address \t * - Sender is not a registered frontend \t * - _amount is not zero \t * --- \t * - Triggers a MON issuance, based on time passed since the last issuance. The MON issuance is shared between *all* depositors and front ends \t * - Tags the deposit with the provided front end tag param, if it's a new deposit \t * - Sends depositor's accumulated gains (MON, ETH) to depositor \t * - Sends the tagged front end's accumulated MON gains to the tagged front end \t * - Increases deposit and tagged front end's stake, and takes new snapshots for each. \t */ \tfunction provideToSP(uint256 _amount) external; \t/* \t * Initial checks: \t * - _amount is zero or there are no under collateralized troves left in the system \t * - User has a non zero deposit \t * --- \t * - Triggers a MON issuance, based on time passed since the last issuance. The MON issuance is shared between *all* depositors and front ends \t * - Removes the deposit's front end tag if it is a full withdrawal \t * - Sends all depositor's accumulated gains (MON, ETH) to depositor \t * - Sends the tagged front end's accumulated MON gains to the tagged front end \t * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. \t * \t * If _amount > userDeposit, the user withdraws all of their compounded deposit. \t */ \tfunction withdrawFromSP(uint256 _amount) external; \t/* \t * Initial checks: \t * - User has a non zero deposit \t * - User has an open trove \t * - User has some ETH gain \t * --- \t * - Triggers a MON issuance, based on time passed since the last issuance. The MON issuance is shared between *all* depositors and front ends \t * - Sends all depositor's MON gain to depositor \t * - Sends all tagged front end's MON gain to the tagged front end \t * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove \t * - Leaves their compounded deposit in the Stability Pool \t * - Updates snapshots for deposit and tagged front end stake \t */ \tfunction withdrawAssetGainToTrove(address _upperHint, address _lowerHint) external; \t/* \t * Initial checks: \t * - Caller is TroveManager \t * --- \t * Cancels out the specified debt against the DCHF contained in the Stability Pool (as far as possible) \t * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. \t * Only called by liquidation functions in the TroveManager. \t */ \tfunction offset(uint256 _debt, uint256 _coll) external; \t/* \t * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, \t * to exclude edge cases like ETH received from a self-destruct. \t */ \tfunction getAssetBalance() external view returns (uint256); \t/* \t * Returns DCHF held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. \t */ \tfunction getTotalDCHFDeposits() external view returns (uint256); \t/* \t * Calculates the ETH gain earned by the deposit since its last snapshots were taken. \t */ \tfunction getDepositorAssetGain(address _depositor) external view returns (uint256); \t/* \t * Calculate the MON gain earned by a deposit since its last snapshots were taken. \t * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. \t * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through \t * which they made their deposit. \t */ \tfunction getDepositorMONGain(address _depositor) external view returns (uint256); \t/* \t * Return the user's compounded deposit. \t */ \tfunction getCompoundedDCHFDeposit(address _depositor) external view returns (uint256); \t/* \t * Return the front end's compounded stake. \t * \t * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. \t */ \tfunction getCompoundedTotalStake() external view returns (uint256); \tfunction getNameBytes() external view returns (bytes32); \tfunction getAssetType() external view returns (address); \t/* \t * Fallback function \t * Only callable by Active Pool, it just accounts for ETH received \t * receive() external payable; \t */ } pragma solidity ^0.8.14; interface IDeposit { \tfunction receivedERC20(address _asset, uint256 _amount) external; }
File 3 of 3: StabilityPoolManager
pragma solidity ^0.8.14; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Dependencies/CheckContract.sol"; import "./Dependencies/Initializable.sol"; import "./Interfaces/IStabilityPoolManager.sol"; contract StabilityPoolManager is Ownable, CheckContract, Initializable, IStabilityPoolManager { \tmapping(address => address) stabilityPools; \tmapping(address => bool) validStabilityPools; \tstring public constant NAME = "StabilityPoolManager"; \tbool public isInitialized; \taddress public adminContract; \tmodifier isController() { \t\trequire(msg.sender == owner() || msg.sender == adminContract, "Invalid permissions"); \t\t_; \t} \tfunction setAddresses(address _adminContract) external initializer onlyOwner { \t\trequire(!isInitialized, "Already initialized"); \t\tcheckContract(_adminContract); \t\tisInitialized = true; \t\tadminContract = _adminContract; \t} \tfunction setAdminContract(address _admin) external onlyOwner { \t\trequire(_admin != address(0), "Admin cannot be empty address"); \t\tcheckContract(_admin); \t\tadminContract = _admin; \t} \tfunction isStabilityPool(address stabilityPool) external view override returns (bool) { \t\treturn validStabilityPools[stabilityPool]; \t} \tfunction addStabilityPool(address asset, address stabilityPool) \t\texternal \t\toverride \t\tisController \t{ \t\tCheckContract(asset); \t\tCheckContract(stabilityPool); \t\trequire(!validStabilityPools[stabilityPool], "StabilityPool already created."); \t\trequire( \t\t\tIStabilityPool(stabilityPool).getAssetType() == asset, \t\t\t"Stability Pool doesn't have the same asset type. Is it initialized?" \t\t); \t\tstabilityPools[asset] = stabilityPool; \t\tvalidStabilityPools[stabilityPool] = true; \t\temit StabilityPoolAdded(asset, stabilityPool); \t} \tfunction removeStabilityPool(address asset) external isController { \t\taddress stabilityPool = stabilityPools[asset]; \t\tdelete validStabilityPools[stabilityPool]; \t\tdelete stabilityPools[asset]; \t\temit StabilityPoolRemoved(asset, stabilityPool); \t} \tfunction getAssetStabilityPool(address asset) \t\texternal \t\tview \t\toverride \t\treturns (IStabilityPool) \t{ \t\trequire(stabilityPools[asset] != address(0), "Invalid asset StabilityPool"); \t\treturn IStabilityPool(stabilityPools[asset]); \t} \tfunction unsafeGetAssetStabilityPool(address _asset) \t\texternal \t\tview \t\toverride \t\treturns (address) \t{ \t\treturn stabilityPools[_asset]; \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; contract CheckContract { \tfunction checkContract(address _account) internal view { \t\trequire(_account != address(0), "Account cannot be zero address"); \t\tuint256 size; \t\tassembly { \t\t\tsize := extcodesize(_account) \t\t} \t\trequire(size > 0, "Account code size cannot be zero"); \t} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/utils/Address.sol"; abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Internal function that returns the initialized version. Returns `_initialized` */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Internal function that returns the initialized version. Returns `_initializing` */ function _isInitializing() internal view returns (bool) { return _initializing; } } pragma solidity ^0.8.14; import "./IStabilityPool.sol"; interface IStabilityPoolManager { \tevent StabilityPoolAdded(address asset, address stabilityPool); \tevent StabilityPoolRemoved(address asset, address stabilityPool); \tfunction isStabilityPool(address stabilityPool) external view returns (bool); \tfunction addStabilityPool(address asset, address stabilityPool) external; \tfunction getAssetStabilityPool(address asset) external view returns (IStabilityPool); \tfunction unsafeGetAssetStabilityPool(address asset) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 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://diligence.consensys.net/posts/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.5.11/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 functionCall(target, data, "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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(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) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason 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 { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.14; import "./IDeposit.sol"; interface IStabilityPool is IDeposit { \t// --- Events --- \tevent StabilityPoolAssetBalanceUpdated(uint256 _newBalance); \tevent StabilityPoolDCHFBalanceUpdated(uint256 _newBalance); \tevent BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); \tevent TroveManagerAddressChanged(address _newTroveManagerAddress); \tevent DefaultPoolAddressChanged(address _newDefaultPoolAddress); \tevent DCHFTokenAddressChanged(address _newDCHFTokenAddress); \tevent SortedTrovesAddressChanged(address _newSortedTrovesAddress); \tevent CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress); \tevent P_Updated(uint256 _P); \tevent S_Updated(uint256 _S, uint128 _epoch, uint128 _scale); \tevent G_Updated(uint256 _G, uint128 _epoch, uint128 _scale); \tevent EpochUpdated(uint128 _currentEpoch); \tevent ScaleUpdated(uint128 _currentScale); \tevent DepositSnapshotUpdated(address indexed _depositor, uint256 _P, uint256 _S, uint256 _G); \tevent SystemSnapshotUpdated(uint256 _P, uint256 _G); \tevent UserDepositChanged(address indexed _depositor, uint256 _newDeposit); \tevent StakeChanged(uint256 _newSystemStake, address _depositor); \tevent AssetGainWithdrawn(address indexed _depositor, uint256 _Asset, uint256 _DCHFLoss); \tevent MONPaidToDepositor(address indexed _depositor, uint256 _MON); \tevent AssetSent(address _to, uint256 _amount); \t// --- Functions --- \tfunction NAME() external view returns (string memory name); \t/* \t * Called only once on init, to set addresses of other Dfranc contracts \t * Callable only by owner, renounces ownership at the end \t */ \tfunction setAddresses( \t\taddress _assetAddress, \t\taddress _borrowerOperationsAddress, \t\taddress _troveManagerAddress, \t\taddress _troveManagerHelperAddress, \t\taddress _dchfTokenAddress, \t\taddress _sortedTrovesAddress, \t\taddress _communityIssuanceAddress, \t\taddress _dfrancParamsAddress \t) external; \t/* \t * Initial checks: \t * - Frontend is registered or zero address \t * - Sender is not a registered frontend \t * - _amount is not zero \t * --- \t * - Triggers a MON issuance, based on time passed since the last issuance. The MON issuance is shared between *all* depositors and front ends \t * - Tags the deposit with the provided front end tag param, if it's a new deposit \t * - Sends depositor's accumulated gains (MON, ETH) to depositor \t * - Sends the tagged front end's accumulated MON gains to the tagged front end \t * - Increases deposit and tagged front end's stake, and takes new snapshots for each. \t */ \tfunction provideToSP(uint256 _amount) external; \t/* \t * Initial checks: \t * - _amount is zero or there are no under collateralized troves left in the system \t * - User has a non zero deposit \t * --- \t * - Triggers a MON issuance, based on time passed since the last issuance. The MON issuance is shared between *all* depositors and front ends \t * - Removes the deposit's front end tag if it is a full withdrawal \t * - Sends all depositor's accumulated gains (MON, ETH) to depositor \t * - Sends the tagged front end's accumulated MON gains to the tagged front end \t * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. \t * \t * If _amount > userDeposit, the user withdraws all of their compounded deposit. \t */ \tfunction withdrawFromSP(uint256 _amount) external; \t/* \t * Initial checks: \t * - User has a non zero deposit \t * - User has an open trove \t * - User has some ETH gain \t * --- \t * - Triggers a MON issuance, based on time passed since the last issuance. The MON issuance is shared between *all* depositors and front ends \t * - Sends all depositor's MON gain to depositor \t * - Sends all tagged front end's MON gain to the tagged front end \t * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove \t * - Leaves their compounded deposit in the Stability Pool \t * - Updates snapshots for deposit and tagged front end stake \t */ \tfunction withdrawAssetGainToTrove(address _upperHint, address _lowerHint) external; \t/* \t * Initial checks: \t * - Caller is TroveManager \t * --- \t * Cancels out the specified debt against the DCHF contained in the Stability Pool (as far as possible) \t * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. \t * Only called by liquidation functions in the TroveManager. \t */ \tfunction offset(uint256 _debt, uint256 _coll) external; \t/* \t * Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`, \t * to exclude edge cases like ETH received from a self-destruct. \t */ \tfunction getAssetBalance() external view returns (uint256); \t/* \t * Returns DCHF held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset. \t */ \tfunction getTotalDCHFDeposits() external view returns (uint256); \t/* \t * Calculates the ETH gain earned by the deposit since its last snapshots were taken. \t */ \tfunction getDepositorAssetGain(address _depositor) external view returns (uint256); \t/* \t * Calculate the MON gain earned by a deposit since its last snapshots were taken. \t * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. \t * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through \t * which they made their deposit. \t */ \tfunction getDepositorMONGain(address _depositor) external view returns (uint256); \t/* \t * Return the user's compounded deposit. \t */ \tfunction getCompoundedDCHFDeposit(address _depositor) external view returns (uint256); \t/* \t * Return the front end's compounded stake. \t * \t * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. \t */ \tfunction getCompoundedTotalStake() external view returns (uint256); \tfunction getNameBytes() external view returns (bytes32); \tfunction getAssetType() external view returns (address); \t/* \t * Fallback function \t * Only callable by Active Pool, it just accounts for ETH received \t * receive() external payable; \t */ } pragma solidity ^0.8.14; interface IDeposit { \tfunction receivedERC20(address _asset, uint256 _amount) external; }