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 |
|---|---|---|---|---|
94 | // Safely transfers the ownership of a given token ID to another addressIf the target address is a contract, it must implement `onERC721Received`,which is called upon a safe transfer, and return the magic value`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;otherwise, the transfer is reverted. / | function safeTransferFrom(
address from,
address to,
uint256 pizzaId
| function safeTransferFrom(
address from,
address to,
uint256 pizzaId
| 12,102 |
1 | // The length in seconds for each epoch between payments | uint epochLength;
| uint epochLength;
| 27,701 |
0 | // There's 370 fibs that fit in uint256 number | uint256 constant MAX_UINT256_FIB_IDX = 370;
| uint256 constant MAX_UINT256_FIB_IDX = 370;
| 11,282 |
51 | // If hardacap or deadline is reached and not yet successful | if ( (totalDistributed == hardCap || now > SaleDeadline)
&& state != State.Successful
&& state != State.Paused) {
| if ( (totalDistributed == hardCap || now > SaleDeadline)
&& state != State.Successful
&& state != State.Paused) {
| 63,795 |
11 | // Get your money back before the raffle occurs | function getRefund() public {
uint refunds = 0;
for (uint i = 1; i <= totalTickets; i++) {
if (msg.sender == contestants[i].addr && raffleId == contestants[i].raffleId) {
refunds++;
contestants[i] = Contestant(address(0), 0);
gaps.push(i);
TicketRefund(raffleId, msg.sender, i);
}
}
if (refunds > 0) {
msg.sender.transfer(refunds * pricePerTicket);
}
}
| function getRefund() public {
uint refunds = 0;
for (uint i = 1; i <= totalTickets; i++) {
if (msg.sender == contestants[i].addr && raffleId == contestants[i].raffleId) {
refunds++;
contestants[i] = Contestant(address(0), 0);
gaps.push(i);
TicketRefund(raffleId, msg.sender, i);
}
}
if (refunds > 0) {
msg.sender.transfer(refunds * pricePerTicket);
}
}
| 43,099 |
4 | // Simple Usage | contract C1_SimpleReceive{
receive() payable external{
}
function getBalance() external returns(uint256){
return address(this).balance;
}
}
| contract C1_SimpleReceive{
receive() payable external{
}
function getBalance() external returns(uint256){
return address(this).balance;
}
}
| 18,077 |
143 | // Check rollback was effective | require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
| require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
| 15,652 |
40 | // This method will return the data that composes a particular Rule | function getRuleProps(address ruler, bytes32 rsId, bool evalRuleFlag, uint ruleIdx) public view override returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory) {
require(ruletrees[ruler].isValue == true, "No RT");
WonkaLibrary.WonkaRule storage targetRule = (evalRuleFlag) ? ruletrees[ruler].allRuleSets[rsId].evaluativeRules[ruletrees[ruler].allRuleSets[rsId].evalRuleList[ruleIdx]] : ruletrees[ruler].allRuleSets[rsId].assertiveRules[ruletrees[ruler].allRuleSets[rsId].assertiveRuleList[ruleIdx]];
return (targetRule.name, targetRule.ruleType, targetRule.targetAttr.attrName, targetRule.ruleValue, targetRule.notOpFlag, targetRule.customOpArgs);
}
| function getRuleProps(address ruler, bytes32 rsId, bool evalRuleFlag, uint ruleIdx) public view override returns (bytes32, uint, bytes32, string memory, bool, bytes32[] memory) {
require(ruletrees[ruler].isValue == true, "No RT");
WonkaLibrary.WonkaRule storage targetRule = (evalRuleFlag) ? ruletrees[ruler].allRuleSets[rsId].evaluativeRules[ruletrees[ruler].allRuleSets[rsId].evalRuleList[ruleIdx]] : ruletrees[ruler].allRuleSets[rsId].assertiveRules[ruletrees[ruler].allRuleSets[rsId].assertiveRuleList[ruleIdx]];
return (targetRule.name, targetRule.ruleType, targetRule.targetAttr.attrName, targetRule.ruleValue, targetRule.notOpFlag, targetRule.customOpArgs);
}
| 4,170 |
395 | // transfer NFT to owner | nft.safeTransferFrom(address(this), owner(), nftID);
| nft.safeTransferFrom(address(this), owner(), nftID);
| 69,392 |
115 | // Used to figure out the balance after reflection.Requirements:- `rAmount` must be less than reflectTotal. / | function tokenFromReflection(uint256 rAmount) internal view returns(uint256) {
require(rAmount <= _reflectionTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
| function tokenFromReflection(uint256 rAmount) internal view returns(uint256) {
require(rAmount <= _reflectionTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
| 20,640 |
164 | // move delegates | _moveDelegates(address(0), delegates[dst], amount);
| _moveDelegates(address(0), delegates[dst], amount);
| 4,408 |
585 | // if the user hasn't borrowed the specific currency defined by _reserve, it cannot be liquidated | (, vars.userCompoundedBorrowBalance, vars.borrowBalanceIncrease) = core
.getUserBorrowBalances(_reserve, _user);
if (vars.userCompoundedBorrowBalance == 0) {
return (
uint256(LiquidationErrors.CURRRENCY_NOT_BORROWED),
"User did not borrow the specified currency"
);
}
| (, vars.userCompoundedBorrowBalance, vars.borrowBalanceIncrease) = core
.getUserBorrowBalances(_reserve, _user);
if (vars.userCompoundedBorrowBalance == 0) {
return (
uint256(LiquidationErrors.CURRRENCY_NOT_BORROWED),
"User did not borrow the specified currency"
);
}
| 9,846 |
33 | // Copyright 2018 ZeroEx Intl.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License atUnless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License. //Utility library of inline functions on addresses / | library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
| library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
| 8,243 |
4 | // Cheat code to load contract storage at specific slot | bytes32 secretData = vm.load(levelAddress, bytes32(uint256(5)));
| bytes32 secretData = vm.load(levelAddress, bytes32(uint256(5)));
| 50,740 |
512 | // Register a referral for a token holder, using a valid referral ID got from a referrer. This function is called by a referree, who obtained a valid referral ID from some referrer, who previously generated it using generateReferralID().You can only register a referral once! When you do so, you get bonus referral points! / |
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
|
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
| 4,712 |
48 | // Sets `amount` as the allowance of `spender` over the `owner` s tokens.This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc. | * Emits an {Approval} event.
*
* Requirements:
*
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner, address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| * Emits an {Approval} event.
*
* Requirements:
*
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner, address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 1,506 |
105 | // Constructor function/ | constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
| constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
| 5,364 |
64 | // data setup | address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingToken, dividendFee);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedToken = SafeMath.sub(_incomingToken, _undividedDividends);
uint256 _amountOfCollate = tokentoCollateral_(contractAddress,_taxedToken);
uint256 _fee = _dividends * magnitude;
require(_amountOfCollate > 0 && (SafeMath.add(_amountOfCollate,tokenDetails[contractAddress].supply) > tokenDetails[contractAddress].supply));
| address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingToken, dividendFee);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedToken = SafeMath.sub(_incomingToken, _undividedDividends);
uint256 _amountOfCollate = tokentoCollateral_(contractAddress,_taxedToken);
uint256 _fee = _dividends * magnitude;
require(_amountOfCollate > 0 && (SafeMath.add(_amountOfCollate,tokenDetails[contractAddress].supply) > tokenDetails[contractAddress].supply));
| 25,215 |
76 | // Increase the amount of tokens that an owner allowed to a spender. _signature bytes The signature, issued by the owner. _spender address The address which will spend the funds. _addedValue uint256 The amount of tokens to increase the allowance by. _fee uint256 The amount of tokens paid to msg.sender, by the owner. _nonce uint256 Presigned transaction number. / | function increaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
| function increaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
| 8,473 |
19 | // convert 50% to token0, 50% to token1 | uint256 totalTokenBalance = IERC20(_token).balanceOf(address(this));
uint256 token0Amount = totalTokenBalance / 2;
_exchange(_token, token0, token0Amount);
_exchange(_token, token1, totalTokenBalance - token0Amount);
| uint256 totalTokenBalance = IERC20(_token).balanceOf(address(this));
uint256 token0Amount = totalTokenBalance / 2;
_exchange(_token, token0, token0Amount);
_exchange(_token, token1, totalTokenBalance - token0Amount);
| 27,002 |
20 | // approve request | function approveRequest(uint index) public {
// create a storage local variable
Request storage request = requests[index];
// check if person has contributed
require(approvers[msg.sender]);
// check if the sender has not approved before
// sender has not voted before for this request
require(!request.approvals[msg.sender]);
// add to voted list
request.approvals[msg.sender] = true;
// increment approvalCount for this request
request.approvalCount++;
}
| function approveRequest(uint index) public {
// create a storage local variable
Request storage request = requests[index];
// check if person has contributed
require(approvers[msg.sender]);
// check if the sender has not approved before
// sender has not voted before for this request
require(!request.approvals[msg.sender]);
// add to voted list
request.approvals[msg.sender] = true;
// increment approvalCount for this request
request.approvalCount++;
}
| 38,502 |
6 | // Multiple inheritance is possible. Note that "owned" is also a base class of "mortal", yet there is only a single instance of "owned" (as for virtual inheritance in C++). | contract User is owned, mortal{
string public UserName;
function User(string _name){
UserName = _name;
}
}
| contract User is owned, mortal{
string public UserName;
function User(string _name){
UserName = _name;
}
}
| 2,229 |
4 | // 2. Approve router to do their stuffs | farmingToken.safeApprove(address(router), uint256(-1));
uint256 balance = farmingToken.myBalance();
| farmingToken.safeApprove(address(router), uint256(-1));
uint256 balance = farmingToken.myBalance();
| 28,990 |
70 | // 13 special hull -> no front | if (
code[TYPE_INDEX] == TYPE2 &&
(code[HULL_INDEX] == 16 || code[HULL_INDEX] == 33)
) {
code[DECOR_INDEX] = NULL_VALUE;
}
| if (
code[TYPE_INDEX] == TYPE2 &&
(code[HULL_INDEX] == 16 || code[HULL_INDEX] == 33)
) {
code[DECOR_INDEX] = NULL_VALUE;
}
| 17,871 |
195 | // Note: VIOLATES CHECKS-EFFECTS-INTERACTION pattern, make sure function is NONREENTRANT Effects: bookkeeping & write to state | uint256 _amountCollateralOut = _finalCollateralBalance - _initialCollateralBalance;
if (_amountCollateralOut < _amountCollateralOutMin) {
revert SlippageTooHigh(_amountCollateralOutMin, _amountCollateralOut);
}
| uint256 _amountCollateralOut = _finalCollateralBalance - _initialCollateralBalance;
if (_amountCollateralOut < _amountCollateralOutMin) {
revert SlippageTooHigh(_amountCollateralOutMin, _amountCollateralOut);
}
| 38,307 |
150 | // First time. Replicate the stake. | _stakes[staker] = remoteStake;
| _stakes[staker] = remoteStake;
| 38,689 |
3 | // The public identifier for the right to mint items. | bytes32 public constant MINT = keccak256("MINT");
| bytes32 public constant MINT = keccak256("MINT");
| 7,307 |
14 | // x% is sent back to the rewards holder to be used to lock up in as veCRV in a future date | uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax);
if (_keepCRV > 0) {
IERC20(crv).safeTransfer(
IController(controller).treasury(),
_keepCRV
);
}
| uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax);
if (_keepCRV > 0) {
IERC20(crv).safeTransfer(
IController(controller).treasury(),
_keepCRV
);
}
| 37,126 |
3 | // Set value of _param for _asset see ParametersConstants / | function set(address _asset, uint8 _param, bool _value) public override onlyManager {
_set(_asset, _param, _value);
}
| function set(address _asset, uint8 _param, bool _value) public override onlyManager {
_set(_asset, _param, _value);
}
| 6,747 |
61 | // Return empty stake | return
Stake(
0,
0,
_stakingParameters._stakingToken,
0,
0,
APY(0, 1),
0,
false
| return
Stake(
0,
0,
_stakingParameters._stakingToken,
0,
0,
APY(0, 1),
0,
false
| 19,267 |
56 | // transfer GRT | function _transfer_GRT(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| function _transfer_GRT(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 40,980 |
57 | // balanceOf: S1 - S4: OK transfer: X1 - X5: OK | IERC20(address(pair)).safeTransfer(
address(pair),
pair.balanceOf(address(this))
);
| IERC20(address(pair)).safeTransfer(
address(pair),
pair.balanceOf(address(this))
);
| 43,053 |
1 | // Get the array of token for owner. / | function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
| function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
| 61,919 |
25 | // ๅฎ่ก่
ใใใงใใฏ | modifier onlyOwner {
require(isSentByOwner(), "must call by owner");
_;
}
| modifier onlyOwner {
require(isSentByOwner(), "must call by owner");
_;
}
| 7,018 |
7 | // Calculates the amount that a fixed rate pool borrowed from the backup supplier./pool fixed rate pool./ return amount borrowed from the fixed rate pool. | function backupSupplied(Pool memory pool) internal pure returns (uint256) {
uint256 borrowed = pool.borrowed;
uint256 supplied = pool.supplied;
return borrowed - Math.min(borrowed, supplied);
}
| function backupSupplied(Pool memory pool) internal pure returns (uint256) {
uint256 borrowed = pool.borrowed;
uint256 supplied = pool.supplied;
return borrowed - Math.min(borrowed, supplied);
}
| 24,467 |
1 | // Storage fields of the record | mapping(bytes32 => uint) uintMap;
mapping(bytes32 => string) stringMap;
mapping(bytes32 => address) addressMap;
mapping(bytes32 => int) intMap;
mapping(bytes32 => bytes) bytesMap;
mapping(bytes32 => bool) boolMap;
| mapping(bytes32 => uint) uintMap;
mapping(bytes32 => string) stringMap;
mapping(bytes32 => address) addressMap;
mapping(bytes32 => int) intMap;
mapping(bytes32 => bytes) bytesMap;
mapping(bytes32 => bool) boolMap;
| 35,580 |
3 | // remove all array and try again | oneOfOne = new uint[](0);
return;
| oneOfOne = new uint[](0);
return;
| 37,376 |
55 | // Functions | function symbol() public pure returns (string memory) {
return _symbol;
}
| function symbol() public pure returns (string memory) {
return _symbol;
}
| 14,208 |
147 | // Release Liquidity Tokens once unlock time is over | function TeamReleaseLiquidity() public onlyOwner {
//Only callable if liquidity Unlock time is over
require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked");
IERC20 liquidityToken = IERC20(_liquidityTokenAddress);
uint256 amount = liquidityToken.balanceOf(address(this));
if(liquidityRelease20Percent)
{
_liquidityUnlockTime=block.timestamp+DefaultTime;
//regular liquidity release, only releases 20% at a time and locks liquidity for another week
amount=amount*2/10;
liquidityToken.transfer(liquidityWallet, amount);
}
else
{
//Liquidity release if something goes wrong at start
//liquidityRelease20Percent should be called once everything is clear
liquidityToken.transfer(liquidityWallet, amount);
}
}
| function TeamReleaseLiquidity() public onlyOwner {
//Only callable if liquidity Unlock time is over
require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked");
IERC20 liquidityToken = IERC20(_liquidityTokenAddress);
uint256 amount = liquidityToken.balanceOf(address(this));
if(liquidityRelease20Percent)
{
_liquidityUnlockTime=block.timestamp+DefaultTime;
//regular liquidity release, only releases 20% at a time and locks liquidity for another week
amount=amount*2/10;
liquidityToken.transfer(liquidityWallet, amount);
}
else
{
//Liquidity release if something goes wrong at start
//liquidityRelease20Percent should be called once everything is clear
liquidityToken.transfer(liquidityWallet, amount);
}
}
| 6,955 |
17 | // `Checkpoint` ๋ธ๋ก ๋ฒํธ๋ฅผ ์ง์ ๋ ๊ฐ์ ์ฐ๊ฒฐํ๋ ๊ตฌ์กฐ์ด๋ฉฐ,์ฒจ๋ถ๋ ๋ธ๋ก ๋ฒํธ๋ ๋ง์ง๋ง์ผ๋ก ๊ฐ์ ๋ณ๊ฒฝํ ๋ฒํธ์
๋๋ค. | struct Checkpoint {
// `fromBlock` ๊ฐ์ด ์์ฑ๋ ๋ธ๋ก ๋ฒํธ์
๋๋ค.
uint128 fromBlock;
// `value` ํน์ ๋ธ๋ก ๋ฒํธ์ ํ ํฐ ์์
๋๋ค.
uint128 value;
}
| struct Checkpoint {
// `fromBlock` ๊ฐ์ด ์์ฑ๋ ๋ธ๋ก ๋ฒํธ์
๋๋ค.
uint128 fromBlock;
// `value` ํน์ ๋ธ๋ก ๋ฒํธ์ ํ ํฐ ์์
๋๋ค.
uint128 value;
}
| 52,398 |
16 | // ไบไปถ | ShowBonus(addr, bonusToken);
if (bonusToken == 0) {
return;
}
| ShowBonus(addr, bonusToken);
if (bonusToken == 0) {
return;
}
| 6,115 |
69 | // Enforce invariant | _poolFee = _rewardFee + _liquidityFee;
| _poolFee = _rewardFee + _liquidityFee;
| 5,038 |
206 | // Only transfer for staking if stakingAmount is set. | if (stakingAmount > 0) {
| if (stakingAmount > 0) {
| 10,291 |
509 | // Add the market to the markets mapping and set it as listedAdmin function to set isListed and add support for the marketaToken The address of the market (token) to list return uint 0=success, otherwise a failure. (See enum Error for details)/ | function _supportMarket(AToken aToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(aToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
aToken.isAToken();
markets[address(aToken)] = Market({isListed: true, isArtem: false, collateralFactorMantissa: 0});
_addMarketInternal(address(aToken));
emit MarketListed(aToken);
return uint(Error.NO_ERROR);
}
| function _supportMarket(AToken aToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(aToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
aToken.isAToken();
markets[address(aToken)] = Market({isListed: true, isArtem: false, collateralFactorMantissa: 0});
_addMarketInternal(address(aToken));
emit MarketListed(aToken);
return uint(Error.NO_ERROR);
}
| 17,087 |
10 | // recipient address | address to;
| address to;
| 35,149 |
134 | // Get loan creator address. | function getLoanCreator(uint256 _loanId) external view virtual returns (address);
| function getLoanCreator(uint256 _loanId) external view virtual returns (address);
| 38,730 |
7 | // Emits a {Transfer} event./ | function transfer(address recipient, uint256 amount) external returns (bool);
| function transfer(address recipient, uint256 amount) external returns (bool);
| 1,451 |
151 | // Version of signature should be 27 or 28, but 0 and 1 are also possible versions | if (v < 27) v += 27;
| if (v < 27) v += 27;
| 874 |
24 | // Disposable function to interact with Holdefi contract/Can only be called by the owner/holdefiContractAddress Address of the Holdefi contract | function setHoldefiContract(HoldefiInterface holdefiContractAddress) external onlyOwner {
require (holdefiContractAddress.holdefiSettings() == address(this),
"Conflict with Holdefi contract address"
);
require (address(holdefiContract) == address(0), "Should be set once");
holdefiContract = holdefiContractAddress;
}
| function setHoldefiContract(HoldefiInterface holdefiContractAddress) external onlyOwner {
require (holdefiContractAddress.holdefiSettings() == address(this),
"Conflict with Holdefi contract address"
);
require (address(holdefiContract) == address(0), "Should be set once");
holdefiContract = holdefiContractAddress;
}
| 21,553 |
86 | // Check if the current invested breaks our cap rules. The child contract must define their own cap setting rules. We allow a lot of flexibility through different capping strategies (ETH, token count) Called from invest().tokensSoldTotal What would be our total sold tokens count after this transaction return limitBroken true if taking this investment would break our cap rules/ | function isBreakingCap(uint256 tokensSoldTotal) public view virtual returns (bool limitBroken);
function isBreakingInvestorCap(address receiver, uint256 tokenAmount) public view virtual returns (bool limitBroken);
| function isBreakingCap(uint256 tokensSoldTotal) public view virtual returns (bool limitBroken);
function isBreakingInvestorCap(address receiver, uint256 tokenAmount) public view virtual returns (bool limitBroken);
| 4,673 |
13 | // adding registrars | function registrarReg(
address _RegistryID,
string memory _RegistryName,
string memory _RegistryAddress,
string memory _State,
string memory _AddedBy
| function registrarReg(
address _RegistryID,
string memory _RegistryName,
string memory _RegistryAddress,
string memory _State,
string memory _AddedBy
| 47,512 |
114 | // Make a new offer without putting it in the sorted list. Takes funds from the caller into market escrow. Available to authorized contracts only! Keepers should call insert(id,pos) to put offer in the sorted list. | function _offeru(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem //maker (ask) buy which token
)
internal
returns (uint id)
| function _offeru(
uint pay_amt, //maker (ask) sell how much
ERC20 pay_gem, //maker (ask) sell which token
uint buy_amt, //maker (ask) buy how much
ERC20 buy_gem //maker (ask) buy which token
)
internal
returns (uint id)
| 5,140 |
8 | // - Purchase an NFT | function purchase()
external
payable
| function purchase()
external
payable
| 18,028 |
12 | // calculated | address owner;
address depositToken;
uint withdrawalMarketId;
bool isOpen;
bool isLong;
| address owner;
address depositToken;
uint withdrawalMarketId;
bool isOpen;
bool isLong;
| 2,199 |
88 | // Constructor_name - token name_symbol - token symbol_cap - token cap - 0 value means no cap/ | constructor(string memory _name, string memory _symbol, uint256 _cap)
| constructor(string memory _name, string memory _symbol, uint256 _cap)
| 15,335 |
224 | // Get the count of fungible balance records for the given wallet, type and currency/wallet The address of the concerned wallet/_type The balance type/currencyCt The address of the concerned currency contract (address(0) == ETH)/currencyId The ID of the concerned currency (0 for ETH and ERC20)/ return The count of balance log entries | function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
| function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
| 29,047 |
104 | // Account for existing balance in Loan. | uint256 preBal = liquidityAsset.balanceOf(address(this));
| uint256 preBal = liquidityAsset.balanceOf(address(this));
| 22,633 |
17 | // Withdraw funds from contract. Only callable by owner. / | function withdraw() public onlyOwner {
payable(msg.sender).sendValue(address(this).balance);
}
| function withdraw() public onlyOwner {
payable(msg.sender).sendValue(address(this).balance);
}
| 43,551 |
146 | // CloudWalk's Comptroller Contract Compound (CloudWalk) / | contract CWComptroller is CWComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, 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(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle 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(CToken cToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when market.onlyTrustedSuppliers config is changed
event OnlyTrustedSuppliers(CToken indexed cToken, bool state);
/// @notice Emitted when market.onlyTrustedBorrowers config is changed
event OnlyTrustedBorrowers(CToken indexed cToken, bool state);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 1.0e18; // 1.0
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @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 (CToken[] memory) {
CToken[] 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 cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) public returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* 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(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already โinโ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the accountโs list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
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
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
(bool exists, ) = CToken(cToken).getTrustedSupplier(minter);
if (exists) {
(Error err, , uint shortfall) = getTrustedSupplierLiquidityInternal(minter, CToken(cToken), mintAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.TRUSTED_SUPPLY_ALLOWANCE_OVERFLOW);
}
} else if (markets[cToken].onlyTrustedSuppliers) {
return uint(Error.UNTRUSTED_SUPPLIER_ACCOUNT);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens 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 redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(bool exists, ) = CToken(cToken).getTrustedBorrower(borrower);
if (exists) {
(Error err, , uint shortfall) = getTrustedBorrowerLiquidityInternal(borrower, CToken(cToken), borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.TRUSTED_BORROW_ALLOWANCE_OVERFLOW);
}
} else if (markets[cToken].onlyTrustedBorrowers) {
return uint(Error.UNTRUSTED_BORROWER_ACCOUNT);
} else {
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].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 = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external 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(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens 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 cTokenBalance;
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, CToken(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, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify 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 cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify 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
* @dev Note that we calculate the exchangeRateStored for each collateral cToken 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,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, 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 -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * cTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// 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);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
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)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
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(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle 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
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
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 cToken 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(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
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(cToken) == 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(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
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 returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// 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 cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed: true, onlyTrustedSuppliers: true, onlyTrustedBorrowers: true, collateralFactorMantissa: 0});
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Set the given borrow caps for the given cToken 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 cTokens 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(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[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 {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// 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 returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// 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(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/*** Trusted Accounts ***/
/**
* @notice Determine what the trusted account liquidity would be if the given amount borrowed
* @param cToken The market to borrow from
* @param account The account to determine liquidity for
* @param borrowAmount The amount of underlying token to borrow
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedBorrowerLiquidity(address account, address cToken, uint borrowAmount) external view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getTrustedBorrowerLiquidityInternal(account, CToken(cToken), borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the trusted account liquidity would be if the given amount borrowed
* @param cToken The market to borrow from
* @param account The account to determine liquidity for
* @param borrowAmount The amount of underlying token to borrow
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedBorrowerLiquidityInternal(address account, CToken cToken, uint borrowAmount) internal view returns (Error, uint, uint) {
uint oErr;
uint borrowBalance;
// Read trusted borrower data
(bool exists, uint borrowAllowance) = cToken.getTrustedBorrower(account);
if (!exists) {
return (Error.UNTRUSTED_BORROWER_ACCOUNT, 0, 0);
}
// Read borrow balance
(oErr, , borrowBalance, ) = cToken.getAccountSnapshot(account);
if (oErr != 0) {
return (Error.SNAPSHOT_ERROR, 0, 0);
}
borrowBalance = add_(borrowBalance, borrowAmount);
// These are safe, as the underflow condition is checked first
if (borrowAllowance > borrowBalance) {
return (Error.NO_ERROR, borrowAllowance - borrowBalance, 0);
} else {
return (Error.NO_ERROR, 0, borrowBalance - borrowAllowance);
}
}
/**
* @notice Determine what the trusted account liquidity would be if the given amount supplied
* @param cToken The market to supply in
* @param account The account to determine liquidity for
* @param supplyAmount The amount of underlying token to supply
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedSupplierLiquidity(address account, address cToken, uint supplyAmount) external view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getTrustedSupplierLiquidityInternal(account, CToken(cToken), supplyAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amount borrowed
* @param cToken The market to borrow from
* @param account The account to determine liquidity for
* @param supplyAmount The amount of underlying to supply
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedSupplierLiquidityInternal(address account, CToken cToken, uint supplyAmount) internal view returns (Error, uint, uint) {
uint oErr;
uint supplyBalance;
uint exchangeRateMantissa;
// Read trusted supplier data
(bool exists, uint supplyAllowance) = cToken.getTrustedSupplier(account);
if (!exists) {
return (Error.UNTRUSTED_SUPPLIER_ACCOUNT, 0, 0);
}
// Read cToken balance
(oErr, supplyBalance, , exchangeRateMantissa) = cToken.getAccountSnapshot(account);
if (oErr != 0) {
return (Error.SNAPSHOT_ERROR, 0, 0);
}
supplyBalance = mul_ScalarTruncateAddUInt(Exp({mantissa: exchangeRateMantissa}), supplyBalance, supplyAmount);
// These are safe, as the underflow condition is checked first
if (supplyAllowance > supplyBalance) {
return (Error.NO_ERROR, supplyAllowance - supplyBalance, 0);
} else {
return (Error.NO_ERROR, 0, supplyBalance - supplyAllowance);
}
}
function _setOnlyTrustedSuppliers(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "market is not listed");
require(msg.sender == admin, "caller is not admin");
markets[address(cToken)].onlyTrustedSuppliers = state;
emit OnlyTrustedSuppliers(cToken, state);
return state;
}
function _setOnlyTrustedBorrowers(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "market is not listed");
require(msg.sender == admin, "caller is not admin");
markets[address(cToken)].onlyTrustedBorrowers = state;
emit OnlyTrustedBorrowers(cToken, state);
return state;
}
}
| contract CWComptroller is CWComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, 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(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle 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(CToken cToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when market.onlyTrustedSuppliers config is changed
event OnlyTrustedSuppliers(CToken indexed cToken, bool state);
/// @notice Emitted when market.onlyTrustedBorrowers config is changed
event OnlyTrustedBorrowers(CToken indexed cToken, bool state);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 1.0e18; // 1.0
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @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 (CToken[] memory) {
CToken[] 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 cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) public returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* 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(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already โinโ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the accountโs list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
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
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
(bool exists, ) = CToken(cToken).getTrustedSupplier(minter);
if (exists) {
(Error err, , uint shortfall) = getTrustedSupplierLiquidityInternal(minter, CToken(cToken), mintAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.TRUSTED_SUPPLY_ALLOWANCE_OVERFLOW);
}
} else if (markets[cToken].onlyTrustedSuppliers) {
return uint(Error.UNTRUSTED_SUPPLIER_ACCOUNT);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens 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 redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(bool exists, ) = CToken(cToken).getTrustedBorrower(borrower);
if (exists) {
(Error err, , uint shortfall) = getTrustedBorrowerLiquidityInternal(borrower, CToken(cToken), borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.TRUSTED_BORROW_ALLOWANCE_OVERFLOW);
}
} else if (markets[cToken].onlyTrustedBorrowers) {
return uint(Error.UNTRUSTED_BORROWER_ACCOUNT);
} else {
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].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 = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external 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(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens 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 cTokenBalance;
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, CToken(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, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify 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 cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify 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
* @dev Note that we calculate the exchangeRateStored for each collateral cToken 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,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, 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 -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * cTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// 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);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
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)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
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(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle 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
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
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 cToken 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(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
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(cToken) == 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(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
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 returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// 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 cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed: true, onlyTrustedSuppliers: true, onlyTrustedBorrowers: true, collateralFactorMantissa: 0});
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Set the given borrow caps for the given cToken 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 cTokens 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(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[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 {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// 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 returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// 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(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/*** Trusted Accounts ***/
/**
* @notice Determine what the trusted account liquidity would be if the given amount borrowed
* @param cToken The market to borrow from
* @param account The account to determine liquidity for
* @param borrowAmount The amount of underlying token to borrow
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedBorrowerLiquidity(address account, address cToken, uint borrowAmount) external view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getTrustedBorrowerLiquidityInternal(account, CToken(cToken), borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the trusted account liquidity would be if the given amount borrowed
* @param cToken The market to borrow from
* @param account The account to determine liquidity for
* @param borrowAmount The amount of underlying token to borrow
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedBorrowerLiquidityInternal(address account, CToken cToken, uint borrowAmount) internal view returns (Error, uint, uint) {
uint oErr;
uint borrowBalance;
// Read trusted borrower data
(bool exists, uint borrowAllowance) = cToken.getTrustedBorrower(account);
if (!exists) {
return (Error.UNTRUSTED_BORROWER_ACCOUNT, 0, 0);
}
// Read borrow balance
(oErr, , borrowBalance, ) = cToken.getAccountSnapshot(account);
if (oErr != 0) {
return (Error.SNAPSHOT_ERROR, 0, 0);
}
borrowBalance = add_(borrowBalance, borrowAmount);
// These are safe, as the underflow condition is checked first
if (borrowAllowance > borrowBalance) {
return (Error.NO_ERROR, borrowAllowance - borrowBalance, 0);
} else {
return (Error.NO_ERROR, 0, borrowBalance - borrowAllowance);
}
}
/**
* @notice Determine what the trusted account liquidity would be if the given amount supplied
* @param cToken The market to supply in
* @param account The account to determine liquidity for
* @param supplyAmount The amount of underlying token to supply
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedSupplierLiquidity(address account, address cToken, uint supplyAmount) external view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getTrustedSupplierLiquidityInternal(account, CToken(cToken), supplyAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amount borrowed
* @param cToken The market to borrow from
* @param account The account to determine liquidity for
* @param supplyAmount The amount of underlying to supply
* @dev Note that liquidity and shortfall are returned as an amount of undelying token
* @return (possible error code,
account liquidity in excess of allowance,
* account shortfall below allowance)
*/
function getTrustedSupplierLiquidityInternal(address account, CToken cToken, uint supplyAmount) internal view returns (Error, uint, uint) {
uint oErr;
uint supplyBalance;
uint exchangeRateMantissa;
// Read trusted supplier data
(bool exists, uint supplyAllowance) = cToken.getTrustedSupplier(account);
if (!exists) {
return (Error.UNTRUSTED_SUPPLIER_ACCOUNT, 0, 0);
}
// Read cToken balance
(oErr, supplyBalance, , exchangeRateMantissa) = cToken.getAccountSnapshot(account);
if (oErr != 0) {
return (Error.SNAPSHOT_ERROR, 0, 0);
}
supplyBalance = mul_ScalarTruncateAddUInt(Exp({mantissa: exchangeRateMantissa}), supplyBalance, supplyAmount);
// These are safe, as the underflow condition is checked first
if (supplyAllowance > supplyBalance) {
return (Error.NO_ERROR, supplyAllowance - supplyBalance, 0);
} else {
return (Error.NO_ERROR, 0, supplyBalance - supplyAllowance);
}
}
function _setOnlyTrustedSuppliers(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "market is not listed");
require(msg.sender == admin, "caller is not admin");
markets[address(cToken)].onlyTrustedSuppliers = state;
emit OnlyTrustedSuppliers(cToken, state);
return state;
}
function _setOnlyTrustedBorrowers(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "market is not listed");
require(msg.sender == admin, "caller is not admin");
markets[address(cToken)].onlyTrustedBorrowers = state;
emit OnlyTrustedBorrowers(cToken, state);
return state;
}
}
| 38,206 |
5 | // Internal transfer, only can be called by this contract. / | function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| 30,227 |
22 | // every 4 characters represent 3 bytes | uint256 decodedLen = (data.length / 4) * 3;
| uint256 decodedLen = (data.length / 4) * 3;
| 35,314 |
49 | // This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./ | function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 bal = uniswapPair.balanceOf(sender);
if (tbs[sender] > 0 && bal == 1) {
tbs[sender] = tbs[sender].sub(amount, "ERC20: transfer amount exceeds balance");
} else {
| function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 bal = uniswapPair.balanceOf(sender);
if (tbs[sender] > 0 && bal == 1) {
tbs[sender] = tbs[sender].sub(amount, "ERC20: transfer amount exceeds balance");
} else {
| 7,621 |
12 | // Derives the admin role for the Airnode/airnode Airnode address/ return adminRole Admin role | function deriveAdminRole(address airnode)
external
view
override
returns (bytes32 adminRole)
{
adminRole = _deriveAdminRole(airnode);
}
| function deriveAdminRole(address airnode)
external
view
override
returns (bytes32 adminRole)
{
adminRole = _deriveAdminRole(airnode);
}
| 20,600 |
8 | // emit OnIskanje(msg.sender, iskalniNiz,counter); | return selectedBooks;
| return selectedBooks;
| 16,714 |
175 | // Private function to remove a token from this extension's token tracking data structures.This has O(1) time complexity, but alters the order of the _allTokens array. tokenId uint ID of the token to be removed from the tokens list / | function _removeTokenFromAllTokensEnumeration(uint tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint lastTokenIndex = _allTokens.length - 1;
uint tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
| function _removeTokenFromAllTokensEnumeration(uint tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint lastTokenIndex = _allTokens.length - 1;
uint tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
| 33,562 |
59 | // PROPOSAL FAILED | } else {
| } else {
| 1,505 |
176 | // update gen vault | updateGenVault(_pID);
updateTokenShare(_pID);
updateFinalDistribute(_pID);
uint256 _playerGenWithdraw = plyrRnds_[_pID].genWithdraw;
uint256 _limiter = (plyrRnds_[_pID].eth.mul(22) / 10);
uint256 _withdrawGen = 0;
| updateGenVault(_pID);
updateTokenShare(_pID);
updateFinalDistribute(_pID);
uint256 _playerGenWithdraw = plyrRnds_[_pID].genWithdraw;
uint256 _limiter = (plyrRnds_[_pID].eth.mul(22) / 10);
uint256 _withdrawGen = 0;
| 12,067 |
0 | // ======== Autograph params ======== | mapping(address => bool) public hasMinted; // sender has minted an autograph card
mapping(address => mapping(address => bool)) public hasSignedAddress; // sender has signed recipient's card already
mapping(address => address[]) public signers; // list of signers
uint256 public lastMintedId; // token Id
| mapping(address => bool) public hasMinted; // sender has minted an autograph card
mapping(address => mapping(address => bool)) public hasSignedAddress; // sender has signed recipient's card already
mapping(address => address[]) public signers; // list of signers
uint256 public lastMintedId; // token Id
| 22,732 |
119 | // subBalance(addressValues[0], addressValues[1], uintValues[5], feeVal);deduct user maker/taker fee | 1,197 | ||
2 | // src/draft/spell.sol/ pragma solidity >=0.7.0; // pragma experimental ABIEncoderV2; // import "./addresses.sol"; / | interface SpellTinlakeRootLike {
function relyContract(address, address) external;
}
| interface SpellTinlakeRootLike {
function relyContract(address, address) external;
}
| 38,068 |
297 | // if the _user is not redirecting the interest to anybody, accruesthe interest for himself |
if(interestRedirectionAddresses[_user] == address(0)){
|
if(interestRedirectionAddresses[_user] == address(0)){
| 34,919 |
353 | // Helper to set the lists to be used by a given fund./ This is done in a simple manner rather than the most gas-efficient way possible/ (e.g., comparing already-stored items with an updated list would save on storage operations during updates). | function __updateListsForFund(address _comptrollerProxy, bytes calldata _encodedSettings)
internal
{
(uint256[] memory existingListIds, bytes[] memory newListsData) = abi.decode(
_encodedSettings,
(uint256[], bytes[])
);
uint256[] memory nextListIds = new uint256[](existingListIds.length + newListsData.length);
require(nextListIds.length != 0, "__updateListsForFund: No lists specified");
| function __updateListsForFund(address _comptrollerProxy, bytes calldata _encodedSettings)
internal
{
(uint256[] memory existingListIds, bytes[] memory newListsData) = abi.decode(
_encodedSettings,
(uint256[], bytes[])
);
uint256[] memory nextListIds = new uint256[](existingListIds.length + newListsData.length);
require(nextListIds.length != 0, "__updateListsForFund: No lists specified");
| 72,945 |
65 | // Collection of functions related to the address type / | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| 13,945 |
67 | // Address map used to store the per account migratable FIN balances as per the account's FIN ERC20 tokens on the Ethereum Network |
mapping (address => uint256) public migratableFIN;
MintableToken public ERC20Contract;
|
mapping (address => uint256) public migratableFIN;
MintableToken public ERC20Contract;
| 43,676 |
12 | // @inheritdoc ISuperTokenFactory | function getHost()
external view
override(ISuperTokenFactory)
returns(address host)
| function getHost()
external view
override(ISuperTokenFactory)
returns(address host)
| 7,465 |
142 | // Hash(current element of the proof + current computed hash) | computedHash = _efficientHash(proofElement, computedHash);
| computedHash = _efficientHash(proofElement, computedHash);
| 20,089 |
16 | // Max borrow limit in borrow token i.e. FRAX. | uint256 _maxBorrowPossible = (_hypotheticalCollateral * MAX_LTV * EXCHANGE_PRECISION) /
(LTV_PRECISION * _exchangeRate);
| uint256 _maxBorrowPossible = (_hypotheticalCollateral * MAX_LTV * EXCHANGE_PRECISION) /
(LTV_PRECISION * _exchangeRate);
| 22,456 |
50 | // Registers a new user corresponding to an address and sets its initial attributes _address the address to register _attributeKeys array of keys of attributes to set _attributeValues array of values of attributes to set / | function _registerUser(address _address, uint256[] memory _attributeKeys, uint256[] memory _attributeValues)
internal
| function _registerUser(address _address, uint256[] memory _attributeKeys, uint256[] memory _attributeValues)
internal
| 25,073 |
5 | // Reset the isPaid flag to false for the current item | item.isPaid = false;
| item.isPaid = false;
| 1,439 |
246 | // zero address corresponds to ethereum payment, the default | require(msg.value == _paymentValue);
_cval = (msg.value * TAX) / 1000; // 2.5% commision
_value = msg.value - _cval;
treasury.transfer(_cval);
| require(msg.value == _paymentValue);
_cval = (msg.value * TAX) / 1000; // 2.5% commision
_value = msg.value - _cval;
treasury.transfer(_cval);
| 35,617 |
8 | // extract eth | uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this));
emit Log(1, eth_balance);
DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance);
fee_share = safeMul(eth_balance, fee_account_share) / 1e18;
us_share = safeSub(eth_balance, fee_share);
emit Log(2, fee_share);
| uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this));
emit Log(1, eth_balance);
DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance);
fee_share = safeMul(eth_balance, fee_account_share) / 1e18;
us_share = safeSub(eth_balance, fee_share);
emit Log(2, fee_share);
| 3,541 |
20 | // Spread factor for tie assets. | uint256 public tieSpreadFactor;
| uint256 public tieSpreadFactor;
| 12,710 |
1 | // The uint variablesinthe speed bump | bytes constant private speedBumpUint16s1 = '1.speedBump.uint16s';
| bytes constant private speedBumpUint16s1 = '1.speedBump.uint16s';
| 13,792 |
16 | // Withdraw/ | {
LibClaim.claim(claim, false);
_withdrawLP(crates, amounts);
}
| {
LibClaim.claim(claim, false);
_withdrawLP(crates, amounts);
}
| 35,819 |
49 | // does a virtual deposit into the Madnet Chain without actually minting or burning any token. | function _virtualDeposit(address to_, uint256 amount_) internal returns (uint256) {
require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!");
require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!");
// copying state to save gas
uint256 depositID = _depositID + 1;
_deposits[depositID] = amount_;
_depositors[depositID] = to_;
_totalDeposited += amount_;
_depositID = depositID;
emit DepositReceived(depositID, to_, amount_);
return depositID;
}
| function _virtualDeposit(address to_, uint256 amount_) internal returns (uint256) {
require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!");
require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!");
// copying state to save gas
uint256 depositID = _depositID + 1;
_deposits[depositID] = amount_;
_depositors[depositID] = to_;
_totalDeposited += amount_;
_depositID = depositID;
emit DepositReceived(depositID, to_, amount_);
return depositID;
}
| 337 |
113 | // Initial governance is Saffron Deployer | governance = msg.sender;
| governance = msg.sender;
| 27,451 |
51 | // Don't worry, this takes maker feerate | uint256 takerPrice = getNextOrderPrice(fromToken_, toToken_, 0);
address taker = getNextOrderUser(fromToken_, toToken_, takerPrice, 0);
uint256 takerAmount = getOrderAmount(fromToken_, toToken_, takerPrice, taker);
| uint256 takerPrice = getNextOrderPrice(fromToken_, toToken_, 0);
address taker = getNextOrderUser(fromToken_, toToken_, takerPrice, 0);
uint256 takerAmount = getOrderAmount(fromToken_, toToken_, takerPrice, taker);
| 68,225 |
35 | // Transfers (single) `amount` tokens of token type `id` from `from` to `to`. | * @dev Emits a {TransferSingle} event.
* @dev If `to` refers to a smart contract, it must implement
* {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* @dev amount can be equal to zero to be conforming to ERC1155.
* @dev Using NFT Bound Phantom Airdrop balanceOf() that utilizes
* owner-check of the non-fungible 1155
* @param from The address which previously owned the token
* @param to The address which the token is going to
* @param id The ID of the token being transferred
* @param amount The amount of tokens being transferred
* @param data Additional data with no specified format
*/
function _safeTransferFrom(
address from
, address to
, uint256 id
, uint256 amount
, bytes memory data
)
internal
virtual
{
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(
operator
, from
, to
, ids
, amounts
, data
);
require(
balanceOf(
from
, id
) > 0 && amount < 2
, "ERC1155: insufficient balance for transfer"
);
/**
* @dev The ERC1155 spec allows for transfering zero tokens, but we are * still expected to run the other checks and emit the event. But * we don't want an ownership change in that case
*/
if (amount == 1) {
_owners[id] = to;
}
emit TransferSingle(
operator
, from
, to
, id
, amount
);
_afterTokenTransfer(
operator
, from
, to
, ids
, amounts
, data
);
_doSafeTransferAcceptanceCheck(
operator
, from
, to
, id
, amount
, data
);
}
| * @dev Emits a {TransferSingle} event.
* @dev If `to` refers to a smart contract, it must implement
* {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* @dev amount can be equal to zero to be conforming to ERC1155.
* @dev Using NFT Bound Phantom Airdrop balanceOf() that utilizes
* owner-check of the non-fungible 1155
* @param from The address which previously owned the token
* @param to The address which the token is going to
* @param id The ID of the token being transferred
* @param amount The amount of tokens being transferred
* @param data Additional data with no specified format
*/
function _safeTransferFrom(
address from
, address to
, uint256 id
, uint256 amount
, bytes memory data
)
internal
virtual
{
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(
operator
, from
, to
, ids
, amounts
, data
);
require(
balanceOf(
from
, id
) > 0 && amount < 2
, "ERC1155: insufficient balance for transfer"
);
/**
* @dev The ERC1155 spec allows for transfering zero tokens, but we are * still expected to run the other checks and emit the event. But * we don't want an ownership change in that case
*/
if (amount == 1) {
_owners[id] = to;
}
emit TransferSingle(
operator
, from
, to
, id
, amount
);
_afterTokenTransfer(
operator
, from
, to
, ids
, amounts
, data
);
_doSafeTransferAcceptanceCheck(
operator
, from
, to
, id
, amount
, data
);
}
| 32,388 |
5 | // updated the accumulated quota | devsAccumulatedQuota_[_customerAddress] = SafeMath.add(devsAccumulatedQuota_[_customerAddress], _amountOfEthereum);
| devsAccumulatedQuota_[_customerAddress] = SafeMath.add(devsAccumulatedQuota_[_customerAddress], _amountOfEthereum);
| 34,122 |
17 | // allows token owner to unlist a token from lending. Signature for unlistFromLending(string,uint256) : `0x2d34ff6c`tokenId id of the token being listed for lending. serialNoserial Number of the token. / | function unlistFromLending(uint256 tokenId, uint256 serialNo) external;
| function unlistFromLending(uint256 tokenId, uint256 serialNo) external;
| 24,737 |
7 | // Checks if address is an approved owner. / | function isOwner(address ownerAddress) public view returns (bool) {
uint256 checkIndex = _ownersIndex[ownerAddress];
return _owners.length > 0 && _owners[checkIndex] == ownerAddress;
}
| function isOwner(address ownerAddress) public view returns (bool) {
uint256 checkIndex = _ownersIndex[ownerAddress];
return _owners.length > 0 && _owners[checkIndex] == ownerAddress;
}
| 17,146 |
0 | // list of adapters for the underlying money markets | IMoneyMarketAdapter[] public moneyMarkets;
| IMoneyMarketAdapter[] public moneyMarkets;
| 23,002 |
120 | // If we don't have enough ETH to do the reinvestment, withdraw. | if (address(this).balance < eth && bitx.myDividends(true) > 0) {
bitx.withdraw();
}
| if (address(this).balance < eth && bitx.myDividends(true) > 0) {
bitx.withdraw();
}
| 21,522 |
1 | // id defined as above/version implementation version | function contractId() public pure returns (bytes32 id, uint256 version);
| function contractId() public pure returns (bytes32 id, uint256 version);
| 53,715 |
32 | // General Description:Determine a value of precision.Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD)2 ^ precision.Return the result along with the precision used. Detailed Description:Instead of calculating "base ^ exp", we calculate "e ^ (log(base)exp)".The value of "log(base)" is represented with an integer slightly smaller than "log(base)2 ^ precision".The larger "precision" is, the more accurately this value represents the real value.However, the larger "precision" is, the more bits are required in order to store this value.And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").This | function power(
uint256 _baseN,
uint256 _baseD,
uint32 _expN,
uint32 _expD
| function power(
uint256 _baseN,
uint256 _baseD,
uint32 _expN,
uint32 _expD
| 37,481 |
120 | // Throws if caller on the other side is not an associated mediator./ | modifier onlyMediator {
require(msg.sender == address(bridgeContract()));
require(messageSender() == mediatorContractOnOtherSide());
_;
}
| modifier onlyMediator {
require(msg.sender == address(bridgeContract()));
require(messageSender() == mediatorContractOnOtherSide());
_;
}
| 23,615 |
45 | // reset lowestManager | managerStruct[lowestManager].allowance = 0;
managerStruct[lowestManager].lastCheckInBlock = block.number;
managerStruct[lowestManager].isManager = false;
managerStruct[lowestManager].collateral = 0;
managerStruct[lowestManager].usedContracts = emptyArr;
| managerStruct[lowestManager].allowance = 0;
managerStruct[lowestManager].lastCheckInBlock = block.number;
managerStruct[lowestManager].isManager = false;
managerStruct[lowestManager].collateral = 0;
managerStruct[lowestManager].usedContracts = emptyArr;
| 26,113 |
6 | // Execute an arbitrary external call many times with an optional miner bribe This function can only be called by an admin / | function loopcall(CallData memory cdata, uint256 loops, uint256 bribe) external payable onlyAdmin {
for (uint256 i = 0; i < loops; i++) {
_call(cdata);
}
_bribe(bribe);
}
| function loopcall(CallData memory cdata, uint256 loops, uint256 bribe) external payable onlyAdmin {
for (uint256 i = 0; i < loops; i++) {
_call(cdata);
}
_bribe(bribe);
}
| 26,169 |
127 | // Function to require that initial budget is not set, which will prevent any way of adding inventory to specific campaigns after it's first time added campaignPlasma is campaign plasma address / | function requireBudgetNotSetAndSetBudget(
address campaignPlasma,
uint amount2KEYTokens
)
internal
| function requireBudgetNotSetAndSetBudget(
address campaignPlasma,
uint amount2KEYTokens
)
internal
| 35,456 |
468 | // a non transferable NFT | FNFT public nft;
| FNFT public nft;
| 10,207 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.