Unnamed: 0
int64 0
7.36k
| comments
stringlengths 3
35.2k
| code_string
stringlengths 1
527k
| code
stringlengths 1
527k
| __index_level_0__
int64 0
88.6k
|
---|---|---|---|---|
161 | // Update storedTotalAssets on withdraw/redeem | function beforeWithdraw(uint256 amount, uint256 shares) internal virtual override {
super.beforeWithdraw(amount, shares);
storedTotalAssets -= amount;
}
| function beforeWithdraw(uint256 amount, uint256 shares) internal virtual override {
super.beforeWithdraw(amount, shares);
storedTotalAssets -= amount;
}
| 41,810 |
12 | // Returns the global time cursor representing the most earliest uncheckpointed week. / | function getTimeCursor() external view override returns (uint256) {
return _timeCursor;
}
| function getTimeCursor() external view override returns (uint256) {
return _timeCursor;
}
| 29,042 |
24 | // Set to Refunded for confirmation | function createAccountRefund(
string calldata operationId
| function createAccountRefund(
string calldata operationId
| 13,231 |
194 | // Send bounty. Wrapper over the real function that performs an extracheck to see if it&39;s after execution window (and thus the first transaction failed) / | function sendBounty(Request storage self)
public returns (bool)
| function sendBounty(Request storage self)
public returns (bool)
| 53,344 |
81 | // We need to parse Flash loan actions in a different way | enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
| enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
| 2,655 |
118 | // Simple SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. | function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
pair.swap(amountOut, 0, to, "");
}
}
| function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).safeBalanceOfSelf();
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
pair.swap(amountOut, 0, to, "");
}
}
| 51,700 |
102 | // Added safety function to extend LGE in case multisig 2 isn't avaiable from emergency life events TODO x3 add your key here | function extendLGE(uint numHours) public {
require(msg.sender == 0xd5b47B80668840e7164C1D1d81aF8a9d9727B421 || msg.sender == 0xC91FE1ee441402D854B8F22F94Ddf66618169636, "LGE: Requires admin");
require(numHours <= 24);
LGEDurationDays = LGEDurationDays.add(numHours.mul(1 hours));
}
| function extendLGE(uint numHours) public {
require(msg.sender == 0xd5b47B80668840e7164C1D1d81aF8a9d9727B421 || msg.sender == 0xC91FE1ee441402D854B8F22F94Ddf66618169636, "LGE: Requires admin");
require(numHours <= 24);
LGEDurationDays = LGEDurationDays.add(numHours.mul(1 hours));
}
| 11,255 |
209 | // Get the amount of stake available for a given staker to withdraw. stakerThe address whose balance to check. return The staker's stake amount that is inactive and available to withdraw. / | function getStakeAvailableToWithdraw(
address staker
)
public
view
returns (uint256)
| function getStakeAvailableToWithdraw(
address staker
)
public
view
returns (uint256)
| 43,865 |
8 | // Withdraw liquidity from Uniswap pool | (uint256 base0, uint256 base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
to,
false
);
(uint256 limit0, uint256 limit1) = _burnLiquidity(
limitLower,
limitUpper,
| (uint256 base0, uint256 base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
to,
false
);
(uint256 limit0, uint256 limit1) = _burnLiquidity(
limitLower,
limitUpper,
| 36,205 |
60 | // Symbol of token. / | string public constant symbol = "DUNG";
| string public constant symbol = "DUNG";
| 56,639 |
32 | // Grand and Revoke Admin Roles | function addAdmin(bytes32 _role, address _address) onlyRole(_role) external {
grantRole(_role, _address);
}
| function addAdmin(bytes32 _role, address _address) onlyRole(_role) external {
grantRole(_role, _address);
}
| 20,212 |
61 | // dynamic reward: | (, uint dynamicReward,, uint dynamicWd,) = hdudPool.userInfoes(player);
recieve = recieve.add(dynamicReward.sub(dynamicWd));
hdudPool.setUser(player, address(0), 0, rewardHDUD.mul(85).div(100), dynamicReward.sub(dynamicWd));
hdudPool.mintHDUD(player, recieve);
| (, uint dynamicReward,, uint dynamicWd,) = hdudPool.userInfoes(player);
recieve = recieve.add(dynamicReward.sub(dynamicWd));
hdudPool.setUser(player, address(0), 0, rewardHDUD.mul(85).div(100), dynamicReward.sub(dynamicWd));
hdudPool.mintHDUD(player, recieve);
| 19,898 |
15 | // wrapper to call the encoded transactions on downstream consumers. destination Address of destination contract. data The encoded data payload.return True on success / | function externalCall(address destination, bytes memory data)
internal
returns (bool)
| function externalCall(address destination, bytes memory data)
internal
returns (bool)
| 9,717 |
4 | // Used when attempting to unlock stCELO when there is no stCELO to unlock. account The account's address. / | error NothingToUnlock(address account);
| error NothingToUnlock(address account);
| 26,156 |
0 | // Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Constant token specific fields | uint256 public _maxSupply = 0;
| uint256 public _maxSupply = 0;
| 16,854 |
7 | // After the end date, the newly deployed parity multisig will bechosen if no transaction is made. | require(now <= endDate);
require(returnAddresses[msg.sender] == 0x0);
returnAddresses[msg.sender] = _returnAddr;
ReturnRequested(msg.sender, _returnAddr);
| require(now <= endDate);
require(returnAddresses[msg.sender] == 0x0);
returnAddresses[msg.sender] = _returnAddr;
ReturnRequested(msg.sender, _returnAddr);
| 16,283 |
51 | // burn the amount sent | return burn(amount);
| return burn(amount);
| 4,146 |
121 | // Update the pre-ICO investments statistic._weiAmount The investment received from a pre-ICO investor._tokensAmount The tokens that will be sent to pre-ICO investor./ | function addPreIcoPurchaseInfo(uint256 _weiAmount, uint256 _tokensAmount) internal {
totalInvestedAmount[msg.sender] = totalInvestedAmount[msg.sender].add(_weiAmount);
tokensSoldPreIco = tokensSoldPreIco.add(_tokensAmount);
tokensSoldTotal = tokensSoldTotal.add(_tokensAmount);
tokensRemainingPreIco = tokensRemainingPreIco.sub(_tokensAmount);
weiRaisedPreIco = weiRaisedPreIco.add(_weiAmount);
weiRaisedTotal = weiRaisedTotal.add(_weiAmount);
}
| function addPreIcoPurchaseInfo(uint256 _weiAmount, uint256 _tokensAmount) internal {
totalInvestedAmount[msg.sender] = totalInvestedAmount[msg.sender].add(_weiAmount);
tokensSoldPreIco = tokensSoldPreIco.add(_tokensAmount);
tokensSoldTotal = tokensSoldTotal.add(_tokensAmount);
tokensRemainingPreIco = tokensRemainingPreIco.sub(_tokensAmount);
weiRaisedPreIco = weiRaisedPreIco.add(_weiAmount);
weiRaisedTotal = weiRaisedTotal.add(_weiAmount);
}
| 4,747 |
22 | // Only worry about allowances for other addresses | _transfer(sender, recipient, amount);
return true;
| _transfer(sender, recipient, amount);
return true;
| 22,973 |
24 | // ChangedDns: dnsDomains have been updated | event ChangedDns(string primary, string secondary, string tertiary);
| event ChangedDns(string primary, string secondary, string tertiary);
| 36,875 |
0 | // event FeeChanged(uint256 fee); | event ParametersChanged(address wallet, string name);
| event ParametersChanged(address wallet, string name);
| 30 |
12 | // Минимальная сумма для участия в режиме Тигров | uint256 minValueInvest = 0.05 ether;
| uint256 minValueInvest = 0.05 ether;
| 41,828 |
41 | // Usage of this method is discouraged, use {safeTransferFrom} whenever possible. Requires the msg.sender to be the owner, approved, or operator.from current owner of the tokento address to receive the ownership of the given token IDtokenId uint256 ID of the token to be transferred/ | function transferFrom(address from, address to, uint256 tokenId) public {
| function transferFrom(address from, address to, uint256 tokenId) public {
| 50,092 |
200 | // Interface of the ERC3156 FlashLender, as defined in _Available since v4.1._ / | interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
| interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(address token) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(address token, uint256 amount) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
| 6,044 |
7 | // Publish a new extension in structure | function publishExtension(string _hash, string _name, string _version, ExtensionType _type, string _moduleKey)
| function publishExtension(string _hash, string _name, string _version, ExtensionType _type, string _moduleKey)
| 46,534 |
447 | // Policy Hooks // Checks if the account should be allowed to mint tokens in the given market bToken The market to verify the mint against minter The account which would get the minted tokens mintAmount The amount of underlying being supplied to the market in exchange for tokensreturn 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) / | function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[bToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[bToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateBirdPlusSupplyIndex(bToken);
distributeSupplierBirdPlus(bToken, minter, false);
return uint(Error.NO_ERROR);
}
| function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[bToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[bToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateBirdPlusSupplyIndex(bToken);
distributeSupplierBirdPlus(bToken, minter, false);
return uint(Error.NO_ERROR);
}
| 11,863 |
53 | // Use of staticcall - this will revert if the underlying function mutates state | let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
| let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
| 4,657 |
21 | // Amount that is ending up after liq rewards and liq budget | uint256 totalsub = LiqPoolAddition.add(liquidityLockAmount);
super._transfer(from, to, amount.sub(totalsub));
| uint256 totalsub = LiqPoolAddition.add(liquidityLockAmount);
super._transfer(from, to, amount.sub(totalsub));
| 31,076 |
10 | // Mints token. / | function mint(uint256 _quanity) external {
_mint(msg.sender, _quanity);
}
| function mint(uint256 _quanity) external {
_mint(msg.sender, _quanity);
}
| 28,963 |
34 | // Minimum amount of funds to be raised for the sale to succeed. | uint256 public constant GOAL = 5000 ether;
| uint256 public constant GOAL = 5000 ether;
| 77,639 |
168 | // IIFOV2. It is an interface for IFOV2.sol / | interface IIFOV2 {
/**
* @notice It allows users to deposit LP tokens to pool
* @param _amount: the number of LP token used (18 decimals)
* @param _pid: poolId
*/
function depositPool(uint256 _amount, uint8 _pid) external;
/**
* @notice It allows users to harvest from pool
* @param _pid: poolId
*/
function harvestPool(uint8 _pid) external;
/**
* @notice It allows the admin to withdraw funds
* @param _lpAmount: the number of LP token to withdraw (18 decimals)
* @param _offerAmount: the number of offering amount to withdraw
* @dev This function is only callable by admin.
*/
function finalWithdraw(uint256 _lpAmount, uint256 _offerAmount) external;
/**
* @notice It sets parameters for pool
* @param _offeringAmountPool: offering amount (in tokens)
* @param _raisingAmountPool: raising amount (in LP tokens)
* @param _limitPerUserInLP: limit per user (in LP tokens)
* @param _hasTax: if the pool has a tax
* @param _pid: poolId
* @dev This function is only callable by admin.
*/
function setPool(
uint256 _offeringAmountPool,
uint256 _raisingAmountPool,
uint256 _limitPerUserInLP,
bool _hasTax,
uint8 _pid
) external;
/**
* @notice It updates point parameters for the IFO.
* @param _numberPoints: the number of points for the IFO
* @param _campaignId: the campaignId for the IFO
* @param _thresholdPoints: the amount of LP required to receive points
* @dev This function is only callable by admin.
*/
function updatePointParameters(
uint256 _campaignId,
uint256 _numberPoints,
uint256 _thresholdPoints
) external;
/**
* @notice It returns the pool information
* @param _pid: poolId
*/
function viewPoolInformation(uint256 _pid)
external
view
returns (
uint256,
uint256,
uint256,
bool,
uint256,
uint256
);
/**
* @notice It returns the tax overflow rate calculated for a pool
* @dev 100,000 means 0.1(10%)/ 1 means 0.000001(0.0001%)/ 1,000,000 means 1(100%)
* @param _pid: poolId
* @return It returns the tax percentage
*/
function viewPoolTaxRateOverflow(uint256 _pid) external view returns (uint256);
/**
* @notice External view function to see user information
* @param _user: user address
* @param _pids[]: array of pids
*/
function viewUserInfo(address _user, uint8[] calldata _pids)
external
view
returns (uint256[] memory, bool[] memory);
/**
* @notice External view function to see user allocations for both pools
* @param _user: user address
* @param _pids[]: array of pids
*/
function viewUserAllocationPools(address _user, uint8[] calldata _pids) external view returns (uint256[] memory);
/**
* @notice External view function to see user offering and refunding amounts for both pools
* @param _user: user address
* @param _pids: array of pids
*/
function viewUserOfferingAndRefundingAmountsForPools(address _user, uint8[] calldata _pids)
external
view
returns (uint256[3][] memory);
}
| interface IIFOV2 {
/**
* @notice It allows users to deposit LP tokens to pool
* @param _amount: the number of LP token used (18 decimals)
* @param _pid: poolId
*/
function depositPool(uint256 _amount, uint8 _pid) external;
/**
* @notice It allows users to harvest from pool
* @param _pid: poolId
*/
function harvestPool(uint8 _pid) external;
/**
* @notice It allows the admin to withdraw funds
* @param _lpAmount: the number of LP token to withdraw (18 decimals)
* @param _offerAmount: the number of offering amount to withdraw
* @dev This function is only callable by admin.
*/
function finalWithdraw(uint256 _lpAmount, uint256 _offerAmount) external;
/**
* @notice It sets parameters for pool
* @param _offeringAmountPool: offering amount (in tokens)
* @param _raisingAmountPool: raising amount (in LP tokens)
* @param _limitPerUserInLP: limit per user (in LP tokens)
* @param _hasTax: if the pool has a tax
* @param _pid: poolId
* @dev This function is only callable by admin.
*/
function setPool(
uint256 _offeringAmountPool,
uint256 _raisingAmountPool,
uint256 _limitPerUserInLP,
bool _hasTax,
uint8 _pid
) external;
/**
* @notice It updates point parameters for the IFO.
* @param _numberPoints: the number of points for the IFO
* @param _campaignId: the campaignId for the IFO
* @param _thresholdPoints: the amount of LP required to receive points
* @dev This function is only callable by admin.
*/
function updatePointParameters(
uint256 _campaignId,
uint256 _numberPoints,
uint256 _thresholdPoints
) external;
/**
* @notice It returns the pool information
* @param _pid: poolId
*/
function viewPoolInformation(uint256 _pid)
external
view
returns (
uint256,
uint256,
uint256,
bool,
uint256,
uint256
);
/**
* @notice It returns the tax overflow rate calculated for a pool
* @dev 100,000 means 0.1(10%)/ 1 means 0.000001(0.0001%)/ 1,000,000 means 1(100%)
* @param _pid: poolId
* @return It returns the tax percentage
*/
function viewPoolTaxRateOverflow(uint256 _pid) external view returns (uint256);
/**
* @notice External view function to see user information
* @param _user: user address
* @param _pids[]: array of pids
*/
function viewUserInfo(address _user, uint8[] calldata _pids)
external
view
returns (uint256[] memory, bool[] memory);
/**
* @notice External view function to see user allocations for both pools
* @param _user: user address
* @param _pids[]: array of pids
*/
function viewUserAllocationPools(address _user, uint8[] calldata _pids) external view returns (uint256[] memory);
/**
* @notice External view function to see user offering and refunding amounts for both pools
* @param _user: user address
* @param _pids: array of pids
*/
function viewUserOfferingAndRefundingAmountsForPools(address _user, uint8[] calldata _pids)
external
view
returns (uint256[3][] memory);
}
| 5,177 |
391 | // Update the allowed fee recipient for this nft contracton SeaDrop.Only the administrator can set the allowed fee recipient.seaDropImplThe allowed SeaDrop contract. feeRecipient The new fee recipient. / | function updateAllowedFeeRecipient(
| function updateAllowedFeeRecipient(
| 26,017 |
47 | // confirm transaction on behalf of signer, not msg.sender | function confirmTransactionBySigner(
address signer,
uint256 transactionId
)
internal
transactionExists(transactionId)
notConfirmed(transactionId, signer)
| function confirmTransactionBySigner(
address signer,
uint256 transactionId
)
internal
transactionExists(transactionId)
notConfirmed(transactionId, signer)
| 38,584 |
96 | // if (msg.sender == ci.users[_teamIdx]) { Team storage teamInfo = userToTeam[msg.sender]; require(teamInfo.index == _competitionId && teamInfo.status == TeamStatus.Competition); delete userToTeam[msg.sender]; } | delete si.sponsors[msg.sender];
require(joyTokenContract.transfer(msg.sender, baseValue));
| delete si.sponsors[msg.sender];
require(joyTokenContract.transfer(msg.sender, baseValue));
| 35,444 |
678 | // Record voteMagnitude for voter | proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake;
| proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake;
| 45,513 |
26 | // @custom:member recipientContract - The target contract address@custom:member sourceChain - The chain which this delivery was requested from (in wormholeChainID format)@custom:member sequence - The wormhole sequence number of the delivery VAA on the source chaincorresponding to this delivery request@custom:member deliveryVaaHash - The hash of the delivery VAA corresponding to this deliveryrequest@custom:member gasUsed - The amount of gas that was used to call your target contract@custom:member status:- RECEIVER_FAILURE, if the target contract reverts- SUCCESS, if the target contract doesn't revert and no forwards were requested- FORWARD_REQUEST_FAILURE, if the target contract doesn't revert, forwards were requested,but provided/leftover funds were not sufficient to cover | event Delivery(
address indexed recipientContract,
uint16 indexed sourceChain,
uint64 indexed sequence,
bytes32 deliveryVaaHash,
DeliveryStatus status,
uint256 gasUsed,
RefundStatus refundStatus,
bytes additionalStatusInfo,
bytes overridesInfo
| event Delivery(
address indexed recipientContract,
uint16 indexed sourceChain,
uint64 indexed sequence,
bytes32 deliveryVaaHash,
DeliveryStatus status,
uint256 gasUsed,
RefundStatus refundStatus,
bytes additionalStatusInfo,
bytes overridesInfo
| 8,622 |
230 | // Set 'stop = min(stop, stopLimit)'. | if (stop > stopLimit) {
stop = stopLimit;
}
| if (stop > stopLimit) {
stop = stopLimit;
}
| 44,336 |
68 | // Logged when the owner of a node assigns a new owner to a subnode. | event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
| event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
| 4,730 |
0 | // Functions/The next two functions are onlyOwner functions.For Zap to be truly decentralized, we will need to transfer the Deity to the 0 address.Only needs to be in library/This function allows us to set a new Deity (or remove it) _newDeity address of the new Deity of the zap system / | function changeDeity(ZapStorage.ZapStorageStruct storage self, address _newDeity) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("_deity")] =_newDeity;
}
| function changeDeity(ZapStorage.ZapStorageStruct storage self, address _newDeity) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("_deity")] =_newDeity;
}
| 7,529 |
8 | // Mapping to check if extension is added | mapping(address => bool) public isExtension;
| mapping(address => bool) public isExtension;
| 45,541 |
43 | // -----------------------------------------payableFunctions----------------------------------------- | 53,894 |
||
15 | // What action to execute when a hash is validated . | mapping (bytes32 => ValidatorAction) internal _hashActions;
| mapping (bytes32 => ValidatorAction) internal _hashActions;
| 30,484 |
87 | // BlacklistableToken Allows accounts to be blacklisted by a "blacklister" role / | contract BlacklistableToken is PausableToken {
BlacklistStore public blacklistStore;
address private _blacklister;
event BlacklisterChanged(address indexed previousBlacklister, address indexed newBlacklister);
event BlacklistStoreSet(address indexed previousBlacklistStore, address indexed newblacklistStore);
event Blacklist(address indexed account, uint256 _status);
/**
* @dev Throws if argument account is blacklisted
* @param _account The address to check
*/
modifier notBlacklisted(address _account) {
require(blacklistStore.blacklisted(_account) == 0, "Account in the blacklist");
_;
}
/**
* @dev Throws if called by any account other than the blacklister
*/
modifier onlyBlacklister() {
require(msg.sender == _blacklister, "msg.sener should be blacklister");
_;
}
/**
* @dev Tells the address of the blacklister
* @return The address of the blacklister
*/
function blacklister() public view returns (address) {
return _blacklister;
}
/**
* @dev Set the blacklistStore
* @param _newblacklistStore The blacklistStore address to set
*/
function setBlacklistStore(address _newblacklistStore) public onlyOwner returns (bool) {
emit BlacklistStoreSet(address(blacklistStore), _newblacklistStore);
blacklistStore = BlacklistStore(_newblacklistStore);
return true;
}
/**
* @dev Update the blacklister
* @param _newBlacklister The newBlacklister to update
*/
function updateBlacklister(address _newBlacklister) public onlyOwner {
require(_newBlacklister != address(0), "Cannot update the blacklister to the zero address");
emit BlacklisterChanged(_blacklister, _newBlacklister);
_blacklister = _newBlacklister;
}
/**
* @dev Checks if account is blacklisted
* @param _account The address status to query
* @return the address status
*/
function queryBlacklist(address _account) public view returns (uint256) {
return blacklistStore.blacklisted(_account);
}
/**
* @dev Adds account to blacklist
* @param _account The address to blacklist
* @param _status The address status to change
*/
function changeBlacklist(address _account, uint256 _status) public onlyBlacklister {
blacklistStore.setBlacklist(_account, _status);
emit Blacklist(_account, _status);
}
function approve(
address _spender,
uint256 _value
) public notBlacklisted(msg.sender) notBlacklisted(_spender) returns (bool success) {
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint256 _addedValue
) public notBlacklisted(msg.sender) notBlacklisted(_spender) returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
) public notBlacklisted(msg.sender) notBlacklisted(_spender) returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public notBlacklisted(_from) notBlacklisted(_to) notBlacklisted(msg.sender) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function transfer(
address _to,
uint256 _value
) public notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool success) {
return super.transfer(_to, _value);
}
}
| contract BlacklistableToken is PausableToken {
BlacklistStore public blacklistStore;
address private _blacklister;
event BlacklisterChanged(address indexed previousBlacklister, address indexed newBlacklister);
event BlacklistStoreSet(address indexed previousBlacklistStore, address indexed newblacklistStore);
event Blacklist(address indexed account, uint256 _status);
/**
* @dev Throws if argument account is blacklisted
* @param _account The address to check
*/
modifier notBlacklisted(address _account) {
require(blacklistStore.blacklisted(_account) == 0, "Account in the blacklist");
_;
}
/**
* @dev Throws if called by any account other than the blacklister
*/
modifier onlyBlacklister() {
require(msg.sender == _blacklister, "msg.sener should be blacklister");
_;
}
/**
* @dev Tells the address of the blacklister
* @return The address of the blacklister
*/
function blacklister() public view returns (address) {
return _blacklister;
}
/**
* @dev Set the blacklistStore
* @param _newblacklistStore The blacklistStore address to set
*/
function setBlacklistStore(address _newblacklistStore) public onlyOwner returns (bool) {
emit BlacklistStoreSet(address(blacklistStore), _newblacklistStore);
blacklistStore = BlacklistStore(_newblacklistStore);
return true;
}
/**
* @dev Update the blacklister
* @param _newBlacklister The newBlacklister to update
*/
function updateBlacklister(address _newBlacklister) public onlyOwner {
require(_newBlacklister != address(0), "Cannot update the blacklister to the zero address");
emit BlacklisterChanged(_blacklister, _newBlacklister);
_blacklister = _newBlacklister;
}
/**
* @dev Checks if account is blacklisted
* @param _account The address status to query
* @return the address status
*/
function queryBlacklist(address _account) public view returns (uint256) {
return blacklistStore.blacklisted(_account);
}
/**
* @dev Adds account to blacklist
* @param _account The address to blacklist
* @param _status The address status to change
*/
function changeBlacklist(address _account, uint256 _status) public onlyBlacklister {
blacklistStore.setBlacklist(_account, _status);
emit Blacklist(_account, _status);
}
function approve(
address _spender,
uint256 _value
) public notBlacklisted(msg.sender) notBlacklisted(_spender) returns (bool success) {
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint256 _addedValue
) public notBlacklisted(msg.sender) notBlacklisted(_spender) returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
) public notBlacklisted(msg.sender) notBlacklisted(_spender) returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public notBlacklisted(_from) notBlacklisted(_to) notBlacklisted(msg.sender) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function transfer(
address _to,
uint256 _value
) public notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool success) {
return super.transfer(_to, _value);
}
}
| 49,808 |
23 | // no user money is kept in this contract, only trasaction fee | if (_amount > address(this).balance) {
revert();
}
| if (_amount > address(this).balance) {
revert();
}
| 9,265 |
160 | // Emit Event | LimitSellOrderCreated(tokenNameIndex, msg.sender, amountOfTokensNecessary, priceInWei, tokens[tokenNameIndex].sellBook[priceInWei].offers_length);
| LimitSellOrderCreated(tokenNameIndex, msg.sender, amountOfTokensNecessary, priceInWei, tokens[tokenNameIndex].sellBook[priceInWei].offers_length);
| 46,094 |
21 | // Redeem collateral. 100+% collateral-backed | function redeem1t1FRAX(uint256 FRAX_amount) external notRedeemPaused {
(uint256 frax_price, , , uint256 global_collateral_ratio, , , uint256 redemption_fee) = FRAX.frax_info();
require(global_collateral_ratio >= 1000000, "Collateral ratio must be >= 1");
(uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(
frax_price,
oracle.consult(frax_contract_address, 1e6).mul(1e6).div(frax_price),
FRAX_amount,
redemption_fee
);
collateral_token.approve(msg.sender, collateral_needed);
redeemCollateralBalances[msg.sender] += collateral_needed;
unclaimedPoolCollateral += collateral_needed;
lastRedeemed[msg.sender] = block.number;
FRAX.pool_burn_from(msg.sender, FRAX_amount);
}
| function redeem1t1FRAX(uint256 FRAX_amount) external notRedeemPaused {
(uint256 frax_price, , , uint256 global_collateral_ratio, , , uint256 redemption_fee) = FRAX.frax_info();
require(global_collateral_ratio >= 1000000, "Collateral ratio must be >= 1");
(uint256 collateral_needed) = FraxPoolLibrary.calcRedeem1t1FRAX(
frax_price,
oracle.consult(frax_contract_address, 1e6).mul(1e6).div(frax_price),
FRAX_amount,
redemption_fee
);
collateral_token.approve(msg.sender, collateral_needed);
redeemCollateralBalances[msg.sender] += collateral_needed;
unclaimedPoolCollateral += collateral_needed;
lastRedeemed[msg.sender] = block.number;
FRAX.pool_burn_from(msg.sender, FRAX_amount);
}
| 19,552 |
115 | // Updating the core currency is not yet supported | require(_userRegistry.currency() == currency, "TC01");
| require(_userRegistry.currency() == currency, "TC01");
| 16,023 |
7 | // Check if the NFT was already minted, in which case we will give ownership to whoever preminted it first. | bool was_nft_already_minted = ( nft.minted_at > 0 );
if( was_nft_already_minted )
{
require( preminted_at < nft.preminted_at, ACCESS_DENIED );
nft.owners[ nft.minter ] = 0; // Reset previous minter balance to zero.
| bool was_nft_already_minted = ( nft.minted_at > 0 );
if( was_nft_already_minted )
{
require( preminted_at < nft.preminted_at, ACCESS_DENIED );
nft.owners[ nft.minter ] = 0; // Reset previous minter balance to zero.
| 36,258 |
21 | // Make payments to the business and service node | if (attemptPaymentElseCancel(
_subscriptionContract,
_subscriptionIdentifier,
tokenAddress,
msg.sender,
amount,
fee,
stakeMultiplier
) == false) {
| if (attemptPaymentElseCancel(
_subscriptionContract,
_subscriptionIdentifier,
tokenAddress,
msg.sender,
amount,
fee,
stakeMultiplier
) == false) {
| 10,049 |
10 | // Check if address is stakeholder / | function isStakeholder(address _address) public view returns(bool, uint256) {
for (uint256 s = 0; s < stakeholders.length; s += 1){
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
| function isStakeholder(address _address) public view returns(bool, uint256) {
for (uint256 s = 0; s < stakeholders.length; s += 1){
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
| 44,464 |
8 | // to deposit collateral into ArbitragePool and get APtoken/ _collateralToken amount to deposit/ _amount amount to deposit | function deposit(address _collateralToken, uint256 _amount) public nonReentrant {
IMintableToken apToken = collateralToAPToken[_collateralToken];
require(address(apToken) != address(0), "d7db9 token must have APtoken");
require(_amount > 0, "d7db9 deposit amount must be bigger than zero");
uint256 startPrice = _apTokenPrice(_collateralToken, apToken);
require(IERC20(_collateralToken).transferFrom(msg.sender, address(this), _amount), "150aa0 transfer from failed");
uint256 amountToMint = (_amount * DECIMAL_PRECISION) / startPrice;
apToken.mint(msg.sender, amountToMint);
depositsAndRewards[_collateralToken] += _amount;
emit Deposit(_collateralToken, msg.sender, _amount, amountToMint);
}
| function deposit(address _collateralToken, uint256 _amount) public nonReentrant {
IMintableToken apToken = collateralToAPToken[_collateralToken];
require(address(apToken) != address(0), "d7db9 token must have APtoken");
require(_amount > 0, "d7db9 deposit amount must be bigger than zero");
uint256 startPrice = _apTokenPrice(_collateralToken, apToken);
require(IERC20(_collateralToken).transferFrom(msg.sender, address(this), _amount), "150aa0 transfer from failed");
uint256 amountToMint = (_amount * DECIMAL_PRECISION) / startPrice;
apToken.mint(msg.sender, amountToMint);
depositsAndRewards[_collateralToken] += _amount;
emit Deposit(_collateralToken, msg.sender, _amount, amountToMint);
}
| 21,542 |
35 | // 2. Burn bridgeable nft | bridgeableNfts[nftType-1].burn(tokenId);
| bridgeableNfts[nftType-1].burn(tokenId);
| 43,967 |
162 | // convert to eth first, same as convertToEther() Store the token in memory to save map entry lookup gas. | (, uint256 magnitude, uint256 rate, bool available, , , ) = _getTokenInfo(_token);
| (, uint256 magnitude, uint256 rate, bool available, , , ) = _getTokenInfo(_token);
| 35,394 |
38 | // Strategy shares have been redeemed strategy Strategy address owner Address that owns the shares recipient Address that received the withdrawn funds shares Amount of shares that were redeemed assetsWithdrawn Amounts of withdrawn assets / | event StrategySharesRedeemed(
| event StrategySharesRedeemed(
| 30,968 |
2 | // `Jade` metadata | mapping(uint256=>uint40) private _jadeMetadata;
| mapping(uint256=>uint40) private _jadeMetadata;
| 4,664 |
43 | // PONZU3 | constructor(string memory _name, string memory _symbol, address _ethContract) ERC20(_name, _symbol) {
LiveTimer = (block.timestamp + day_1_time) * 1 ether;
contractAddress = _ethContract;
}
| constructor(string memory _name, string memory _symbol, address _ethContract) ERC20(_name, _symbol) {
LiveTimer = (block.timestamp + day_1_time) * 1 ether;
contractAddress = _ethContract;
}
| 1,213 |
27 | // stake amount | _stake(msg.sender, msg.value);
emit StakedWithPartner(partner, msg.value);
| _stake(msg.sender, msg.value);
emit StakedWithPartner(partner, msg.value);
| 52,016 |
3 | // Selector: contractOwner(address) 5152b14c | function contractOwner(address contractAddress)
external
view
returns (address);
| function contractOwner(address contractAddress)
external
view
returns (address);
| 35,742 |
18 | // DATATYPES / | struct Char {
//name of the char
//string name;
//wiki pageid of char
string wikiID_Name; //save gas
}
| struct Char {
//name of the char
//string name;
//wiki pageid of char
string wikiID_Name; //save gas
}
| 27,664 |
4 | // The SNP TOKEN! | SnpToken public snptoken;
| SnpToken public snptoken;
| 4,149 |
16 | // Vault must have a positive balance for at least one managed asset | if (amountOut >= type(uint256).max) revert DefunctVault();
| if (amountOut >= type(uint256).max) revert DefunctVault();
| 9,696 |
9 | // greater than 100gwei for safetymeasure | require(address(this).balance > 100000000000, "Make sure this contract has atleast 100 gwei");
require(isAuto = true, "Auto Mode is not on");
| require(address(this).balance > 100000000000, "Make sure this contract has atleast 100 gwei");
require(isAuto = true, "Auto Mode is not on");
| 1,042 |
22 | // Mapping for allowance | mapping (address => mapping (address => uint)) internal allowed;
| mapping (address => mapping (address => uint)) internal allowed;
| 20,967 |
13 | // | error TOO_MANY_PROPERTIES();
| error TOO_MANY_PROPERTIES();
| 17,034 |
13 | // Calculate estimated epoch for _startBlock | StreamInfo memory streamInfo =
StreamInfo(0, false, 0, 0, 0, new uint256[](0), new uint256[](0));
(streamInfo.notOverflow, streamInfo.startDiff) = _startBlock.trySub(
block.number
);
if (streamInfo.notOverflow) {
| StreamInfo memory streamInfo =
StreamInfo(0, false, 0, 0, 0, new uint256[](0), new uint256[](0));
(streamInfo.notOverflow, streamInfo.startDiff) = _startBlock.trySub(
block.number
);
if (streamInfo.notOverflow) {
| 40,447 |
81 | // Logic for pricing based on the Tiers of the crowdsale These bonus amounts and the number of tiers itself can be changed/This means that:/ | if (now>=tier1Start && now < tier1End) {
rate = 120;
}else if (now>=tier2Start && now < tier2End) {
| if (now>=tier1Start && now < tier1End) {
rate = 120;
}else if (now>=tier2Start && now < tier2End) {
| 10,321 |
4 | // Sets contract blocker _val Should we block contracts? / | function setBlockContracts(bool _val) external onlyOwner {
_blockContracts = _val;
}
| function setBlockContracts(bool _val) external onlyOwner {
_blockContracts = _val;
}
| 8,097 |
9 | // Specifies clothes owner would like to wear. Overwrites existing selections, so always include every items you'd like to wear. | function wearClothes(uint256 tokenId, uint256[] calldata clothes) public returns (string memory) {
require (msg.sender == ownerOf(tokenId), "not your Noun");
clothingState[tokenId] = clothes;
return 'Updated your clothing';
}
| function wearClothes(uint256 tokenId, uint256[] calldata clothes) public returns (string memory) {
require (msg.sender == ownerOf(tokenId), "not your Noun");
clothingState[tokenId] = clothes;
return 'Updated your clothing';
}
| 71,934 |
120 | // Sets the owner for a given list/_id The id of the list/_nextOwner The owner to set | function setListOwner(uint256 _id, address _nextOwner) external onlyListOwner(_id) {
lists[_id].owner = _nextOwner;
emit ListOwnerSet(_id, _nextOwner);
}
| function setListOwner(uint256 _id, address _nextOwner) external onlyListOwner(_id) {
lists[_id].owner = _nextOwner;
emit ListOwnerSet(_id, _nextOwner);
}
| 72,858 |
22 | // Increases the given smart contract `vault`'s balance and/ notifies the `vault` contract. Called by the Bridge after/ the deposits routed by depositors to that `vault` have been/ swept by the Bridge. This way, the depositor does not have to/ issue a separatetransaction to the `vault` contract./ Can be called only by the Bridge./Requirements:/ - `vault` must implement `IVault` interface,/ - length of `depositors` and `depositedAmounts` must be the same./vault Address of `IVault` recipient contract/depositors Addresses of depositors whose deposits have been swept/depositedAmounts Amounts deposited by individual depositors and/swept. The `vault`'s balance in the Bank will be increased by the/sum of | function increaseBalanceAndCall(
address vault,
address[] calldata depositors,
uint256[] calldata depositedAmounts
| function increaseBalanceAndCall(
address vault,
address[] calldata depositors,
uint256[] calldata depositedAmounts
| 9,118 |
241 | // for other pools - stake as pool | address highPool = factory.getPoolAddress(HIGH);
require(highPool != address(0),"invalid high pool address");
ICorePool(highPool).stakeAsPool(_staker, pendingYield);
| address highPool = factory.getPoolAddress(HIGH);
require(highPool != address(0),"invalid high pool address");
ICorePool(highPool).stakeAsPool(_staker, pendingYield);
| 12,325 |
54 | // Get the balance of multiple account/token pairs _owners The addresses of the token holders _idsID of the TokensreturnThe _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) / | function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public
view
returns (uint256[] memory)
| function balanceOfBatch(address[] memory _owners, uint256[] memory _ids)
public
view
returns (uint256[] memory)
| 1,847 |
149 | // Return the desired amount of liquidity token that the migrator wants. | function desiredLiquidity() external view returns (uint256);
| function desiredLiquidity() external view returns (uint256);
| 1,654 |
94 | // Get rewards for one day stakedAmount Stake amount of the user stakedToken Staked token address of the user rewardToken Reward token addressreturn reward One dayh reward for the user / | function getOneDayReward(
uint256 stakedAmount,
address stakedToken,
address rewardToken
| function getOneDayReward(
uint256 stakedAmount,
address stakedToken,
address rewardToken
| 3,199 |
16 | // Create ERC20 oreder. price uint The ETH price amount uint The token amount tokenId uint The token id expireDate uint The expire date in timestamp / | function createERC20order(uint price, uint amount, uint tokenId, uint expireDate) external isActive checkOrderERC20(amount, tokenId, expireDate) returns(uint id) {
ERC20tokens[tokenId].transferFrom(msg.sender, address(this), amount);
OrderERC20 memory order;
id = ordersCountERC20;
order.orderId = id;
order.owner = msg.sender;
order.price = price;
order.amount = amount;
order.tokenId = tokenId;
order.expireDate = expireDate;
order.status = true;
ordersERC20[id] = order;
ordersCountERC20++;
emit CreateERC20order(price, amount, tokenId, expireDate);
}
| function createERC20order(uint price, uint amount, uint tokenId, uint expireDate) external isActive checkOrderERC20(amount, tokenId, expireDate) returns(uint id) {
ERC20tokens[tokenId].transferFrom(msg.sender, address(this), amount);
OrderERC20 memory order;
id = ordersCountERC20;
order.orderId = id;
order.owner = msg.sender;
order.price = price;
order.amount = amount;
order.tokenId = tokenId;
order.expireDate = expireDate;
order.status = true;
ordersERC20[id] = order;
ordersCountERC20++;
emit CreateERC20order(price, amount, tokenId, expireDate);
}
| 47,155 |
167 | // Internal only rebalance for better gas in redeem | function _rebalance(Lender newProvider) internal {
if (_balance() > 0) {
if (newProvider == Lender.DYDX) {
supplyDydx(_balance());
} else if (newProvider == Lender.FULCRUM) {
supplyFulcrum(_balance());
} else if (newProvider == Lender.COMPOUND) {
supplyCompound(_balance());
} else if (newProvider == Lender.AAVE) {
supplyAave(_balance());
}
}
provider = newProvider;
}
| function _rebalance(Lender newProvider) internal {
if (_balance() > 0) {
if (newProvider == Lender.DYDX) {
supplyDydx(_balance());
} else if (newProvider == Lender.FULCRUM) {
supplyFulcrum(_balance());
} else if (newProvider == Lender.COMPOUND) {
supplyCompound(_balance());
} else if (newProvider == Lender.AAVE) {
supplyAave(_balance());
}
}
provider = newProvider;
}
| 83,217 |
35 | // May need to be split if not enough gas | require(!open,"Airdrop is already close");
for (uint i=0; i<_addresses.length; i++) {
if(_isParticipant[_addresses[i]]){
continue;
}
| require(!open,"Airdrop is already close");
for (uint i=0; i<_addresses.length; i++) {
if(_isParticipant[_addresses[i]]){
continue;
}
| 26,861 |
14 | // Withdraws stETH + WETH (if necessary) from vault using vault shares collateralToken is the address of the collateral token weth is the WETH address recipient is the recipient amount is the withdraw amount in `asset`return withdrawAmount is the withdraw amount in `collateralToken` / | function withdrawYieldAndBaseToken(
address collateralToken,
address weth,
address recipient,
uint256 amount
| function withdrawYieldAndBaseToken(
address collateralToken,
address weth,
address recipient,
uint256 amount
| 48,071 |
198 | // Verifies that the rebasing is not paused. / | modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
| modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
| 11,602 |
2 | // How many allocation points assigned to this pool. UBQ to distribute per block. | uint256 allocPoint;
uint256 lastRewardBlock; // Last block number that UBQs distribution occurs.
uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below.
| uint256 allocPoint;
uint256 lastRewardBlock; // Last block number that UBQs distribution occurs.
uint256 accUbqPerShare; // Accumulated UBQs per share, times 1e12. See below.
| 7,523 |
69 | // Called by the DSProxy contract which owns the Compound position/Adds the users Compound poistion in the list of subscriptions so it can be monitored/_minRatio Minimum ratio below which repay is triggered/_maxRatio Maximum ratio after which boost is triggered/_optimalBoost Ratio amount which boost should target/_optimalRepay Ratio amount which repay should target/_boostEnabled Boolean determing if boost is enabled | function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
| function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
| 7,775 |
7 | // The lower limit of the maximum number of tokens that can be minted. | uint32 editionMaxMintableUpper;
| uint32 editionMaxMintableUpper;
| 42,579 |
64 | // calculate tax amount and send WETH _developmentFee + _autoLPFee _totalTax | uint256 wethDevelopment = (wethReceived * _developmentFee) / (_developmentFee + _autoLPFee);
IERC20(token).transfer(feeaddress, wethDevelopment);
| uint256 wethDevelopment = (wethReceived * _developmentFee) / (_developmentFee + _autoLPFee);
IERC20(token).transfer(feeaddress, wethDevelopment);
| 22,138 |
959 | // Returns the time average weighted price corresponding to `query`. / | function getTimeWeightedAverage(
mapping(uint256 => bytes32) storage samples,
IPriceOracle.OracleAverageQuery memory query,
uint256 latestIndex
| function getTimeWeightedAverage(
mapping(uint256 => bytes32) storage samples,
IPriceOracle.OracleAverageQuery memory query,
uint256 latestIndex
| 13,739 |
364 | // If the previous cumulativeRewardFactor is 0 and we are before the LIP-71 round, set the default value to MathUtils.percPoints(1, 1) because we only set the default value to PreciseMathUtils.percPoints(1, 1) when storing for the LIP-71 round and onwards (see updateCumulativeRewardFactor() in EarningsPoolLIP36.sol) | if (prevEarningsPool.cumulativeRewardFactor == 0 && _round < roundsManager().lipUpgradeRound(71)) {
prevEarningsPool.cumulativeRewardFactor = MathUtils.percPoints(1, 1);
}
| if (prevEarningsPool.cumulativeRewardFactor == 0 && _round < roundsManager().lipUpgradeRound(71)) {
prevEarningsPool.cumulativeRewardFactor = MathUtils.percPoints(1, 1);
}
| 35,703 |
15 | // Determine whether or not a contract address relates to one of the identifiers. _contractAddress The contract address to look for. _identifiers The identifiers.return A boolean indicating if the contract address relates to one of the identifiers. / | function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
| function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
| 53,136 |
522 | // PIGGY-MODIFY: Modified some methods and fields according to WePiggy's business logic | contract Comptroller is ComptrollerStorage, IComptroller, ComptrollerErrorReporter, Exponential, OwnableUpgradeSafe {
// @notice Emitted when an admin supports a market
event MarketListed(PToken pToken);
// @notice Emitted when an account enters a market
event MarketEntered(PToken pToken, address account);
// @notice Emitted when an account exits a market
event MarketExited(PToken pToken, address account);
// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(PToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
// @notice Emitted when price oracle is changed
event NewPriceOracle(IPriceOracle oldPriceOracle, IPriceOracle newPriceOracle);
// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
// @notice Emitted when an action is paused on a market
event ActionPaused(PToken pToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a pToken is changed
event NewBorrowCap(PToken indexed pToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
event NewPiggyDistribution(IPiggyDistribution oldPiggyDistribution, IPiggyDistribution newPiggyDistribution);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18;
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18;
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18;
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18;
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18;
// for distribute wpc
IPiggyDistribution piggyDistribution;
function initialize() public initializer {
//setting the msg.sender as the initial owner.
super.__Ownable_init();
}
/*** Assets You Are In ***/
function enterMarkets(address[] memory pTokens) public override(IComptroller) returns (uint[] memory) {
uint len = pTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
PToken pToken = PToken(pTokens[i]);
results[i] = uint(addToMarketInternal(pToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param pToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(PToken pToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(pToken)];
// market is not listed, cannot join
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
// already joined
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) {
return Error.TOO_MANY_ASSETS;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(pToken);
emit MarketEntered(pToken, borrower);
return Error.NO_ERROR;
}
function exitMarket(address pTokenAddress) external override(IComptroller) returns (uint) {
PToken pToken = PToken(pTokenAddress);
// Get sender tokensHeld and amountOwed underlying from the pToken
(uint oErr, uint tokensHeld, uint amountOwed,) = pToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed");
// Fail if the sender has a borrow balance
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
// Fail if the sender is not permitted to redeem all of their tokens
uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(pToken)];
// Return true if the sender is not already ‘in’ the market
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
// Set pToken account membership to false
delete marketToExit.accountMembership[msg.sender];
// Delete pToken from the account’s list of assets
// load into memory for faster iteration
PToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == pToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
PToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(pToken, msg.sender);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (PToken[] memory) {
PToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param pToken The pToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, PToken pToken) external view returns (bool) {
return markets[address(pToken)].accountMembership[account];
}
/*** Policy Hooks ***/
function mintAllowed(address pToken, address minter, uint mintAmount) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenMintGuardianPaused[pToken], "mint is paused");
//Shh - currently unused. It's written here to eliminate compile-time alarms.
minter;
mintAmount;
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
//will not distribute wpc here!
return uint(Error.NO_ERROR);
}
function mintVerify(address pToken, address minter, uint mintAmount, uint mintTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
minter;
mintAmount;
mintTokens;
}
function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override(IComptroller) returns (uint){
uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
//will not distribute wpc here!
return uint(Error.NO_ERROR);
}
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param pToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of pTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[pToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, PToken(pToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
redeemer;
redeemAmount;
redeemTokens;
}
function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override(IComptroller) returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenBorrowGuardianPaused[pToken], "borrow is paused");
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[pToken].accountMembership[borrower]) {
// only pTokens may call borrowAllowed if borrower not in market
require(msg.sender == pToken, "sender must be pToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(PToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[pToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(PToken(pToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[pToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = PToken(pToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, PToken(pToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function borrowVerify(address pToken, address borrower, uint borrowAmount) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
borrower;
borrowAmount;
}
function repayBorrowAllowed(address pToken, address payer, address borrower, uint repayAmount) external override(IComptroller) returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Shh - currently unused. It's written here to eliminate compile-time alarms.
payer;
borrower;
repayAmount;
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeRepayBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function repayBorrowVerify(address pToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
payer;
borrower;
repayAmount;
borrowerIndex;
}
function liquidateBorrowAllowed(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount
) external override(IComptroller) returns (uint){
// Shh - currently unused. It's written here to eliminate compile-time alarms.
liquidator;
if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = PToken(pTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
function liquidateBorrowVerify(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenBorrowed;
pTokenCollateral;
liquidator;
borrower;
repayAmount;
seizeTokens;
}
function seizeAllowed(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused. It's written here to eliminate compile-time alarms.
seizeTokens;
if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (PToken(pTokenCollateral).comptroller() != PToken(pTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeSeizeWpc(pTokenCollateral, borrower, liquidator, false);
}
return uint(Error.NO_ERROR);
}
function seizeVerify(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenCollateral;
pTokenBorrowed;
liquidator;
borrower;
seizeTokens;
}
function transferAllowed(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(pToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeTransferWpc(pToken, src, dst, false);
}
return uint(Error.NO_ERROR);
}
function transferVerify(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
src;
dst;
transferTokens;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `pTokenBalance` is the number of pTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint pTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, PToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, PToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address pTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, PToken(pTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param account The account to determine liquidity for
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
PToken pTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars;
uint oErr;
MathError mErr;
// For each asset the account is in
PToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
PToken asset = assets[i];
// Read the balances and exchange rate from the pToken
(oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> usd (normalized price value)
// pTokenPrice = oraclePrice * exchangeRate
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * pTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with pTokenModify
if (asset == pTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
function liquidateCalculateSeizeTokens(
address pTokenBorrowed,
address pTokenCollateral,
uint actualRepayAmount
) external override(IComptroller) view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(PToken(pTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(PToken(pTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*
* Note: reverts on error
*/
uint exchangeRateMantissa = PToken(pTokenCollateral).exchangeRateStored();
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(IPriceOracle newOracle) public onlyOwner returns (uint) {
// Track the old oracle for the comptroller
IPriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyOwner returns (uint) {
Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param pToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(PToken pToken, uint newCollateralFactorMantissa) external onlyOwner returns (uint) {
// Verify market is listed
Market storage market = markets[address(pToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external onlyOwner returns (uint) {
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyOwner returns (uint) {
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param pToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(PToken pToken) external onlyOwner returns (uint) {
if (markets[address(pToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
markets[address(pToken)] = Market({isListed : true, isMinted : false, collateralFactorMantissa : 0});
_addMarketInternal(address(pToken));
emit MarketListed(pToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address pToken) internal onlyOwner {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != PToken(pToken), "market already added");
}
allMarkets.push(PToken(pToken));
}
/**
* @notice Set the given borrow caps for the given pToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param pTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(PToken[] calldata pTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == owner() || msg.sender == borrowCapGuardian, "only owner or borrow cap guardian can set borrow caps");
uint numMarkets = pTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(pTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(pTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external onlyOwner {
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public onlyOwner returns (uint) {
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(PToken pToken, bool state) public returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
pTokenMintGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Mint", state);
return state;
}
function _setBorrowPaused(PToken pToken, bool state) public returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
pTokenBorrowGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _setDistributeWpcPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
distributeWpcPaused = state;
emit ActionPaused("DistributeWpc", state);
return state;
}
/**
* @notice Sets a new price piggyDistribution for the comptroller
* @dev Admin function to set a new piggy distribution
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
function getAllMarkets() public view returns (PToken[] memory){
return allMarkets;
}
function isMarketMinted(address pToken) public view returns (bool){
return markets[pToken].isMinted;
}
function isMarketListed(address pToken) public view returns (bool){
return markets[pToken].isListed;
}
function _setMarketMinted(address pToken, bool status) public {
require(msg.sender == address(piggyDistribution) || msg.sender == owner(), "only PiggyDistribution or owner can update");
markets[pToken].isMinted = status;
}
} | contract Comptroller is ComptrollerStorage, IComptroller, ComptrollerErrorReporter, Exponential, OwnableUpgradeSafe {
// @notice Emitted when an admin supports a market
event MarketListed(PToken pToken);
// @notice Emitted when an account enters a market
event MarketEntered(PToken pToken, address account);
// @notice Emitted when an account exits a market
event MarketExited(PToken pToken, address account);
// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(PToken pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
// @notice Emitted when price oracle is changed
event NewPriceOracle(IPriceOracle oldPriceOracle, IPriceOracle newPriceOracle);
// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
// @notice Emitted when an action is paused on a market
event ActionPaused(PToken pToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a pToken is changed
event NewBorrowCap(PToken indexed pToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
event NewPiggyDistribution(IPiggyDistribution oldPiggyDistribution, IPiggyDistribution newPiggyDistribution);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18;
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18;
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18;
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18;
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18;
// for distribute wpc
IPiggyDistribution piggyDistribution;
function initialize() public initializer {
//setting the msg.sender as the initial owner.
super.__Ownable_init();
}
/*** Assets You Are In ***/
function enterMarkets(address[] memory pTokens) public override(IComptroller) returns (uint[] memory) {
uint len = pTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
PToken pToken = PToken(pTokens[i]);
results[i] = uint(addToMarketInternal(pToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param pToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(PToken pToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(pToken)];
// market is not listed, cannot join
if (!marketToJoin.isListed) {
return Error.MARKET_NOT_LISTED;
}
// already joined
if (marketToJoin.accountMembership[borrower] == true) {
return Error.NO_ERROR;
}
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) {
return Error.TOO_MANY_ASSETS;
}
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(pToken);
emit MarketEntered(pToken, borrower);
return Error.NO_ERROR;
}
function exitMarket(address pTokenAddress) external override(IComptroller) returns (uint) {
PToken pToken = PToken(pTokenAddress);
// Get sender tokensHeld and amountOwed underlying from the pToken
(uint oErr, uint tokensHeld, uint amountOwed,) = pToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed");
// Fail if the sender has a borrow balance
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
// Fail if the sender is not permitted to redeem all of their tokens
uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(pToken)];
// Return true if the sender is not already ‘in’ the market
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
// Set pToken account membership to false
delete marketToExit.accountMembership[msg.sender];
// Delete pToken from the account’s list of assets
// load into memory for faster iteration
PToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == pToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
PToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(pToken, msg.sender);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (PToken[] memory) {
PToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param pToken The pToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, PToken pToken) external view returns (bool) {
return markets[address(pToken)].accountMembership[account];
}
/*** Policy Hooks ***/
function mintAllowed(address pToken, address minter, uint mintAmount) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenMintGuardianPaused[pToken], "mint is paused");
//Shh - currently unused. It's written here to eliminate compile-time alarms.
minter;
mintAmount;
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
//will not distribute wpc here!
return uint(Error.NO_ERROR);
}
function mintVerify(address pToken, address minter, uint mintAmount, uint mintTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
minter;
mintAmount;
mintTokens;
}
function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override(IComptroller) returns (uint){
uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
//will not distribute wpc here!
return uint(Error.NO_ERROR);
}
/**
* PIGGY-MODIFY:
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param pToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of pTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[pToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, PToken(pToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
redeemer;
redeemAmount;
redeemTokens;
}
function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override(IComptroller) returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!pTokenBorrowGuardianPaused[pToken], "borrow is paused");
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[pToken].accountMembership[borrower]) {
// only pTokens may call borrowAllowed if borrower not in market
require(msg.sender == pToken, "sender must be pToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(PToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[pToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(PToken(pToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[pToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = PToken(pToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, PToken(pToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function borrowVerify(address pToken, address borrower, uint borrowAmount) external override(IComptroller) {
//Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
borrower;
borrowAmount;
}
function repayBorrowAllowed(address pToken, address payer, address borrower, uint repayAmount) external override(IComptroller) returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Shh - currently unused. It's written here to eliminate compile-time alarms.
payer;
borrower;
repayAmount;
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeRepayBorrowWpc(pToken, borrower, false);
}
return uint(Error.NO_ERROR);
}
function repayBorrowVerify(address pToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
payer;
borrower;
repayAmount;
borrowerIndex;
}
function liquidateBorrowAllowed(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount
) external override(IComptroller) returns (uint){
// Shh - currently unused. It's written here to eliminate compile-time alarms.
liquidator;
if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = PToken(pTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
function liquidateBorrowVerify(
address pTokenBorrowed,
address pTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenBorrowed;
pTokenCollateral;
liquidator;
borrower;
repayAmount;
seizeTokens;
}
function seizeAllowed(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused. It's written here to eliminate compile-time alarms.
seizeTokens;
if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (PToken(pTokenCollateral).comptroller() != PToken(pTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeSeizeWpc(pTokenCollateral, borrower, liquidator, false);
}
return uint(Error.NO_ERROR);
}
function seizeVerify(
address pTokenCollateral,
address pTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pTokenCollateral;
pTokenBorrowed;
liquidator;
borrower;
seizeTokens;
}
function transferAllowed(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) returns (uint){
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(pToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
//distribute wpc
if (distributeWpcPaused == false) {
piggyDistribution.distributeTransferWpc(pToken, src, dst, false);
}
return uint(Error.NO_ERROR);
}
function transferVerify(
address pToken,
address src,
address dst,
uint transferTokens
) external override(IComptroller) {
// Shh - currently unused. It's written here to eliminate compile-time alarms.
pToken;
src;
dst;
transferTokens;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `pTokenBalance` is the number of pTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint pTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, PToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, PToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address pTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, PToken(pTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param account The account to determine liquidity for
* @param pTokenModify The market to hypothetically redeem/borrow in
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
PToken pTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars;
uint oErr;
MathError mErr;
// For each asset the account is in
PToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
PToken asset = assets[i];
// Read the balances and exchange rate from the pToken
(oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> usd (normalized price value)
// pTokenPrice = oraclePrice * exchangeRate
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * pTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with pTokenModify
if (asset == pTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
function liquidateCalculateSeizeTokens(
address pTokenBorrowed,
address pTokenCollateral,
uint actualRepayAmount
) external override(IComptroller) view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(PToken(pTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(PToken(pTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*
* Note: reverts on error
*/
uint exchangeRateMantissa = PToken(pTokenCollateral).exchangeRateStored();
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(IPriceOracle newOracle) public onlyOwner returns (uint) {
// Track the old oracle for the comptroller
IPriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external onlyOwner returns (uint) {
Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param pToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(PToken pToken, uint newCollateralFactorMantissa) external onlyOwner returns (uint) {
// Verify market is listed
Market storage market = markets[address(pToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external onlyOwner returns (uint) {
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external onlyOwner returns (uint) {
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param pToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(PToken pToken) external onlyOwner returns (uint) {
if (markets[address(pToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
markets[address(pToken)] = Market({isListed : true, isMinted : false, collateralFactorMantissa : 0});
_addMarketInternal(address(pToken));
emit MarketListed(pToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address pToken) internal onlyOwner {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != PToken(pToken), "market already added");
}
allMarkets.push(PToken(pToken));
}
/**
* @notice Set the given borrow caps for the given pToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param pTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(PToken[] calldata pTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == owner() || msg.sender == borrowCapGuardian, "only owner or borrow cap guardian can set borrow caps");
uint numMarkets = pTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint i = 0; i < numMarkets; i++) {
borrowCaps[address(pTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(pTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external onlyOwner {
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public onlyOwner returns (uint) {
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(PToken pToken, bool state) public returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
pTokenMintGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Mint", state);
return state;
}
function _setBorrowPaused(PToken pToken, bool state) public returns (bool) {
require(markets[address(pToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
pTokenBorrowGuardianPaused[address(pToken)] = state;
emit ActionPaused(pToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _setDistributeWpcPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == owner(), "only pause guardian and owner can pause");
require(msg.sender == owner() || state == true, "only owner can unpause");
distributeWpcPaused = state;
emit ActionPaused("DistributeWpc", state);
return state;
}
/**
* @notice Sets a new price piggyDistribution for the comptroller
* @dev Admin function to set a new piggy distribution
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
function getAllMarkets() public view returns (PToken[] memory){
return allMarkets;
}
function isMarketMinted(address pToken) public view returns (bool){
return markets[pToken].isMinted;
}
function isMarketListed(address pToken) public view returns (bool){
return markets[pToken].isListed;
}
function _setMarketMinted(address pToken, bool status) public {
require(msg.sender == address(piggyDistribution) || msg.sender == owner(), "only PiggyDistribution or owner can update");
markets[pToken].isMinted = status;
}
} | 15,965 |
60 | // GovernancePhases | bytes32 internal KEY_GOVERNANCE; // 2.x
bytes32 internal KEY_STAKING; // 1.2
bytes32 internal KEY_PROXY_ADMIN; // 1.0
| bytes32 internal KEY_GOVERNANCE; // 2.x
bytes32 internal KEY_STAKING; // 1.2
bytes32 internal KEY_PROXY_ADMIN; // 1.0
| 31,459 |
24 | // Toggle deposit override/pos Hypervisor Address | function toggleDepositOverride(address pos) external onlyOwner onlyAddedPosition(pos) {
Position storage p = positions[pos];
p.depositOverride = !p.depositOverride;
emit DepositOverrideToggled(pos);
}
| function toggleDepositOverride(address pos) external onlyOwner onlyAddedPosition(pos) {
Position storage p = positions[pos];
p.depositOverride = !p.depositOverride;
emit DepositOverrideToggled(pos);
}
| 16,298 |
30 | // alloc tracks | _allocTracks(_num, trackTmps_[_num].length);
for (uint i=0; i<trackTmps_[_num].length; i++) {
_updateTrack(_num, startIndex+i, trackTmps_[_num][i]);
}
| _allocTracks(_num, trackTmps_[_num].length);
for (uint i=0; i<trackTmps_[_num].length; i++) {
_updateTrack(_num, startIndex+i, trackTmps_[_num][i]);
}
| 33,501 |
189 | // Validate reards slippage swapData Swap slippage and path array / | function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual {
if (swapData.length > 0) {
require(
swapData.length == _getRewardSlippageSlots(),
"BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined"
);
}
}
| function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual {
if (swapData.length > 0) {
require(
swapData.length == _getRewardSlippageSlots(),
"BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined"
);
}
}
| 8,146 |
100 | // Copyright (C) 2020 PlotX.io | contract IMaster {
mapping(address => bool) public whitelistedSponsor;
function dAppToken() public view returns(address);
function getLatestAddress(bytes2 _module) public view returns(address);
}
| contract IMaster {
mapping(address => bool) public whitelistedSponsor;
function dAppToken() public view returns(address);
function getLatestAddress(bytes2 _module) public view returns(address);
}
| 13,981 |
22 | // ---------------------------------------------------------------------- Auction Price ---------------------------------------------------------------------- |
function AUCTIONPRICEPARAMETERS855(address _set) //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.AuctionPriceParameters memory);
|
function AUCTIONPRICEPARAMETERS855(address _set) //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.AuctionPriceParameters memory);
| 4,383 |
64 | // Create a uniswap pair for this new token | uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
| uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
| 480 |
73 | // grab time | uint256 _now = now;
| uint256 _now = now;
| 1,739 |
218 | // Init ballot / | ) only_editors() external returns (uint ballotId) {
// calculate the ballotId based on the last 224 bits of the specHash.
ballotId = uint224(specHash) ^ (uint256(NAMESPACE) << 224);
// we need to call the init functions on our libraries
getDb(ballotId).init(specHash, packed, ix, bbAdmin, bytes16(uint128(extraData)));
nBallots += 1;
emit BallotCreatedWithID(ballotId);
}
| ) only_editors() external returns (uint ballotId) {
// calculate the ballotId based on the last 224 bits of the specHash.
ballotId = uint224(specHash) ^ (uint256(NAMESPACE) << 224);
// we need to call the init functions on our libraries
getDb(ballotId).init(specHash, packed, ix, bbAdmin, bytes16(uint128(extraData)));
nBallots += 1;
emit BallotCreatedWithID(ballotId);
}
| 47,150 |
164 | // get the lusd | LUSD.safeTransferFrom(msg.sender, address(this), lusdAmount);
| LUSD.safeTransferFrom(msg.sender, address(this), lusdAmount);
| 28,510 |
23 | // Claim Governance of the contract to a new account (`newGovernor`).Can only be called by the new Governor. / | function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
| function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
| 13,512 |
429 | // revert if applicable transfer recipient is not valid ERC1155Receiver operator executor of transfer from sender of tokens to receiver of tokens ids token IDs amounts quantities of tokens to transfer data data payload / | function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
| function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
| 22,846 |
29 | // Image | metadata = string(
abi.encodePacked(
metadata,
' "image": "',
imageURI(_tokenId),
'",\n'
)
);
| metadata = string(
abi.encodePacked(
metadata,
' "image": "',
imageURI(_tokenId),
'",\n'
)
);
| 24,728 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.