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
143
// Auction start price is fair value minus half price range to center the auction at fair value
uint256 auctionStartPrice = fairValue.sub(halfPriceRange);
uint256 auctionStartPrice = fairValue.sub(halfPriceRange);
32,753
73
// Calculate share (member / totaltokens)
return (factoredWeight + factoredContributed) * totalTokensReceived / (factoredTotalWeight + factoredTotalContributed);
return (factoredWeight + factoredContributed) * totalTokensReceived / (factoredTotalWeight + factoredTotalContributed);
54,458
8
// Transfers the ownership of an NFT from one address to another address/Throws unless `msg.sender` is the current owner, an authorized/operator, or the approved address for this NFT. Throws if `_from` is/not the current owner. Throws if `_to` is the zero address. Throws if/`_tokenId` is not a valid NFT. When transfer is complete, this function/checks if `_to` is a smart contract (code size > 0). If so, it calls/`onERC721Received` on `_to` and throws if the return value is not/`bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`./_from The current owner of the NFT/_to The new owner/_tokenId The NFT to transfer/_data Additional data with no specified format, sent in call
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { _transfer(_from, _to, _tokenId); require(_checkOnERC721Received(_from, _to, _tokenId, _data), "Transfer to non ERC721 receiver"); }
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public { _transfer(_from, _to, _tokenId); require(_checkOnERC721Received(_from, _to, _tokenId, _data), "Transfer to non ERC721 receiver"); }
50,479
1
// Prevents a contract from calling itself, directly or indirectly. If you mark a function `nonReentrant`, you should alsomark it `external`. Calling one nonReentrant function fromanother is not supported. Instead, you can implement a`private` function doing the actual work, and a `external`wrapper marked as `nonReentrant`. /
modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; }
modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; }
6,755
398
// reference to the Staking for choosing random Dog thieves
IStaking public staking;
IStaking public staking;
12,735
2
// 0: bg 1: back 2: body 3: hat 4: face 5: front 6: 1_1
uint24[7] public _layerByteBoundaries = [3320, 3655, 85316, 138435, 168455, 169590, 201423]; uint8[] public _faceMaskingList = [39];
uint24[7] public _layerByteBoundaries = [3320, 3655, 85316, 138435, 168455, 169590, 201423]; uint8[] public _faceMaskingList = [39];
31,583
71
// Mints new tokens, increasing totalSupply, and a users balance.Limited to onlyMinter modifier/
function mint(address to, uint256 amount) external onlyMinter returns (bool)
function mint(address to, uint256 amount) external onlyMinter returns (bool)
12,610
148
// Emit this event when the owner changes the standard sale's packPrice.
event StandardPackPriceChanged(uint256 packPrice);
event StandardPackPriceChanged(uint256 packPrice);
70,683
521
// returns provider's pending rewards requirements: - the specified program ids array needs to consist from unique and existing program ids with the same rewardtoken /
function pendingRewards(address provider, uint256[] calldata ids) external view returns (uint256);
function pendingRewards(address provider, uint256[] calldata ids) external view returns (uint256);
28,093
13
// Returns whether a Draw can be completed.return True if a Draw can be completed, false otherwise. /
function canCompleteDraw() external view returns (bool);
function canCompleteDraw() external view returns (bool);
24,663
5
// ToDo: create a sellTokens() function:
/*function sellTokens(uint amountToSell) public payable returns(uint ethAmount) { //yourToken.transferFrom(msg.sender, address(this), theAmount) require(msg.value > 0, "Tokens needed to get the eth!"); uint ethAmount = msg.value/tokensPerEth; uint256 sellerBalance = yourToken.balanceOf(msg.sender); require(sellerBalance >= amountToSell, "Your balance is lower than the amount of tokens you want to sell"); yourToken.transferFrom(msg.sender, address(this), msg.value); emit SellTokens(msg.sender, msg.value, ethAmount); return (ethAmount); }*/
/*function sellTokens(uint amountToSell) public payable returns(uint ethAmount) { //yourToken.transferFrom(msg.sender, address(this), theAmount) require(msg.value > 0, "Tokens needed to get the eth!"); uint ethAmount = msg.value/tokensPerEth; uint256 sellerBalance = yourToken.balanceOf(msg.sender); require(sellerBalance >= amountToSell, "Your balance is lower than the amount of tokens you want to sell"); yourToken.transferFrom(msg.sender, address(this), msg.value); emit SellTokens(msg.sender, msg.value, ethAmount); return (ethAmount); }*/
25,968
54
// token holders
address[] public holders;
address[] public holders;
51,831
18
// called by the governor to pause, triggers stopped state /
function pause() public onlyGovernor whenNotPaused { _pause(); }
function pause() public onlyGovernor whenNotPaused { _pause(); }
18,190
16
// Withdraw ERC20 Balance and transfer out to payoutAddressErc20/ tokenAddress ERC20 Token Address
function drainErc20Balance(address tokenAddress) external adminRequired nonReentrant{ uint256 amount; if (IERC20(tokenAddress).balanceOf(address(this)) > 0) { amount = IERC20(tokenAddress).balanceOf(address(this)); uint256 platfromCommission = ((amount * platformFeeBps) / 10000); if(platfromCommission != 0) { IERC20(tokenAddress).transfer(platofrmAddress, platfromCommission); } IERC20(tokenAddress).transfer(payoutAddressErc20, amount-platfromCommission); emit balanceDrained(tokenAddress, payoutAddressErc20, amount-platfromCommission,platofrmAddress,platfromCommission); } else { revert( "there is no balance in the contract on the provided currency to drain" ); } }
function drainErc20Balance(address tokenAddress) external adminRequired nonReentrant{ uint256 amount; if (IERC20(tokenAddress).balanceOf(address(this)) > 0) { amount = IERC20(tokenAddress).balanceOf(address(this)); uint256 platfromCommission = ((amount * platformFeeBps) / 10000); if(platfromCommission != 0) { IERC20(tokenAddress).transfer(platofrmAddress, platfromCommission); } IERC20(tokenAddress).transfer(payoutAddressErc20, amount-platfromCommission); emit balanceDrained(tokenAddress, payoutAddressErc20, amount-platfromCommission,platofrmAddress,platfromCommission); } else { revert( "there is no balance in the contract on the provided currency to drain" ); } }
22,321
51
// Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: Emits an {Approval} event./
function approve(address spender, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
4,311
82
// booster variables variables to keep track of totalSupply and balances (after accounting for multiplier)
uint256 public boostedTotalSupply; uint256 public lastBoostPurchase; // timestamp of lastBoostPurchase mapping(address => uint256) public boostedBalances; mapping(address => uint256) public numBoostersBought; // each booster = 5% increase in stake amt mapping(address => uint256) public nextBoostPurchaseTime; // timestamp for which user is eligible to purchase another booster uint256 public globalBoosterPrice = 1e18; uint256 public boostThreshold = 10; uint256 public boostScaleFactor = 20; uint256 public scaleFactor = 320;
uint256 public boostedTotalSupply; uint256 public lastBoostPurchase; // timestamp of lastBoostPurchase mapping(address => uint256) public boostedBalances; mapping(address => uint256) public numBoostersBought; // each booster = 5% increase in stake amt mapping(address => uint256) public nextBoostPurchaseTime; // timestamp for which user is eligible to purchase another booster uint256 public globalBoosterPrice = 1e18; uint256 public boostThreshold = 10; uint256 public boostScaleFactor = 20; uint256 public scaleFactor = 320;
55,125
414
// We write previously calculated values into storage //We invoke doTransferOut for the redeemer and the redeemAmount. Note: The cToken must handle variations between ERC-20 and ETH underlying. On success, the cToken has redeemAmount less of cash. doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. /
doTransferOut(redeemer, vars.redeemAmount, isNative);
doTransferOut(redeemer, vars.redeemAmount, isNative);
18,386
51
// HoldefiSettings contract/Holdefi Team/This contract is for Holdefi settings implementation
contract HoldefiSettings is HoldefiOwnable { using SafeMath for uint256; /// @notice Markets Features struct MarketSettings { bool isExist; // Market is exist or not bool isActive; // Market is open for deposit or not uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; // Collateral is exist or not bool isActive; // Collateral is open for deposit or not uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } uint256 constant public rateDecimals = 10 ** 4; address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 constant public periodBetweenUpdates = 864000; // seconds per ten days uint256 constant public maxBorrowRate = 4000; // 40% uint256 constant public borrowRateMaxIncrease = 500; // 5% uint256 constant public minSuppliersShareRate = 5000; // 50% uint256 constant public suppliersShareRateMaxDecrease = 500; // 5% uint256 constant public maxValueToLoanRate = 20000; // 200% uint256 constant public valueToLoanRateMaxIncrease = 500; // 5% uint256 constant public maxPenaltyRate = 13000; // 130% uint256 constant public penaltyRateMaxIncrease = 500; // 5% uint256 constant public maxPromotionRate = 3000; // 30% uint256 constant public maxListsLength = 25; /// @dev Used for calculating liquidation threshold /// There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; mapping (address => MarketSettings) public marketAssets; address[] public marketsList; mapping (address => CollateralSettings) public collateralAssets; HoldefiInterface public holdefiContract; /// @notice Event emitted when market activation status is changed event MarketActivationChanged(address indexed market, bool status); /// @notice Event emitted when collateral activation status is changed event CollateralActivationChanged(address indexed collateral, bool status); /// @notice Event emitted when market existence status is changed event MarketExistenceChanged(address indexed market, bool status); /// @notice Event emitted when collateral existence status is changed event CollateralExistenceChanged(address indexed collateral, bool status); /// @notice Event emitted when market borrow rate is changed event BorrowRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when market suppliers share rate is changed event SuppliersShareRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when market promotion rate is changed event PromotionRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral value to loan rate is changed event ValueToLoanRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral penalty rate is changed event PenaltyRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral bonus rate is changed event BonusRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @dev Modifier to make a function callable only when the market is exist /// @param market Address of the given market modifier marketIsExist(address market) { require (marketAssets[market].isExist, "The market is not exist"); _; } /// @dev Modifier to make a function callable only when the collateral is exist /// @param collateral Address of the given collateral modifier collateralIsExist(address collateral) { require (collateralAssets[collateral].isExist, "The collateral is not exist"); _; } /// @notice you cannot send ETH to this contract receive() external payable { revert(); } /// @notice Activate a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function activateMarket (address market) public onlyOwner marketIsExist(market) { activateMarketInternal(market); } /// @notice Deactivate a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function deactivateMarket (address market) public onlyOwner marketIsExist(market) { marketAssets[market].isActive = false; emit MarketActivationChanged(market, false); } /// @notice Activate a collateral asset /// @dev Can only be called by the owner /// @param collateral Address the given collateral function activateCollateral (address collateral) public onlyOwner collateralIsExist(collateral) { activateCollateralInternal(collateral); } /// @notice Deactivate a collateral asset /// @dev Can only be called by the owner /// @param collateral Address of the given collateral function deactivateCollateral (address collateral) public onlyOwner collateralIsExist(collateral) { collateralAssets[collateral].isActive = false; emit CollateralActivationChanged(collateral, false); } /// @notice Returns the list of markets /// @return res List of markets function getMarketsList() external view returns (address[] memory res){ res = marketsList; } /// @notice Disposable function to interact with Holdefi contract /// @dev Can only be called by the owner /// @param 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; } /// @notice Returns supply, borrow and promotion rate of the given market /// @dev supplyRate = (totalBorrow * borrowRate) * suppliersShareRate / totalSupply /// @param market Address of the given market /// @return borrowRate Borrow rate of the given market /// @return supplyRateBase Supply rate base of the given market /// @return promotionRate Promotion rate of the given market function getInterests (address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate) { uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow; uint256 totalSupply = holdefiContract.marketAssets(market).totalSupply; borrowRate = marketAssets[market].borrowRate; if (totalSupply == 0) { supplyRateBase = 0; } else { uint256 totalInterestFromBorrow = totalBorrow.mul(borrowRate); uint256 suppliersShare = totalInterestFromBorrow.mul(marketAssets[market].suppliersShareRate); suppliersShare = suppliersShare.div(rateDecimals); supplyRateBase = suppliersShare.div(totalSupply); } promotionRate = marketAssets[market].promotionRate; } /// @notice Set promotion rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newPromotionRate New promotion rate function setPromotionRate (address market, uint256 newPromotionRate) external onlyOwner { require (newPromotionRate <= maxPromotionRate, "Rate should be in allowed range"); holdefiContract.beforeChangeSupplyRate(market); holdefiContract.reserveSettlement(market); emit PromotionRateChanged(market, newPromotionRate, marketAssets[market].promotionRate); marketAssets[market].promotionRate = newPromotionRate; } /// @notice Reset promotion rate of the market to zero /// @dev Can only be called by holdefi contract /// @param market Address of the given market function resetPromotionRate (address market) external { require (msg.sender == address(holdefiContract), "Sender is not Holdefi contract"); emit PromotionRateChanged(market, 0, marketAssets[market].promotionRate); marketAssets[market].promotionRate = 0; } /// @notice Set borrow rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newBorrowRate New borrow rate function setBorrowRate (address market, uint256 newBorrowRate) external onlyOwner marketIsExist(market) { setBorrowRateInternal(market, newBorrowRate); } /// @notice Set suppliers share rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newSuppliersShareRate New suppliers share rate function setSuppliersShareRate (address market, uint256 newSuppliersShareRate) external onlyOwner marketIsExist(market) { setSuppliersShareRateInternal(market, newSuppliersShareRate); } /// @notice Set value to loan rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newValueToLoanRate New value to loan rate function setValueToLoanRate (address collateral, uint256 newValueToLoanRate) external onlyOwner collateralIsExist(collateral) { setValueToLoanRateInternal(collateral, newValueToLoanRate); } /// @notice Set penalty rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newPenaltyRate New penalty rate function setPenaltyRate (address collateral, uint256 newPenaltyRate) external onlyOwner collateralIsExist(collateral) { setPenaltyRateInternal(collateral, newPenaltyRate); } /// @notice Set bonus rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newBonusRate New bonus rate function setBonusRate (address collateral, uint256 newBonusRate) external onlyOwner collateralIsExist(collateral) { setBonusRateInternal(collateral, newBonusRate); } /// @notice Add a new asset as a market /// @dev Can only be called by the owner /// @param market Address of the new market /// @param borrowRate BorrowRate of the new market /// @param suppliersShareRate SuppliersShareRate of the new market function addMarket (address market, uint256 borrowRate, uint256 suppliersShareRate) external onlyOwner { require (!marketAssets[market].isExist, "The market is exist"); require (marketsList.length < maxListsLength, "Market list is full"); if (market != ethAddress) { IERC20(market); } marketsList.push(market); marketAssets[market].isExist = true; emit MarketExistenceChanged(market, true); setBorrowRateInternal(market, borrowRate); setSuppliersShareRateInternal(market, suppliersShareRate); activateMarketInternal(market); } /// @notice Remove a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function removeMarket (address market) external onlyOwner marketIsExist(market) { uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow; require (totalBorrow == 0, "Total borrow is not zero"); holdefiContract.beforeChangeBorrowRate(market); uint256 i; uint256 index; uint256 marketListLength = marketsList.length; for (i = 0 ; i < marketListLength ; i++) { if (marketsList[i] == market) { index = i; } } if (index != marketListLength-1) { for (i = index ; i < marketListLength-1 ; i++) { marketsList[i] = marketsList[i+1]; } } marketsList.pop(); delete marketAssets[market]; emit MarketExistenceChanged(market, false); } /// @notice Add a new asset as a collateral /// @dev Can only be called by the owner /// @param collateral Address of the new collateral /// @param valueToLoanRate ValueToLoanRate of the new collateral /// @param penaltyRate PenaltyRate of the new collateral /// @param bonusRate BonusRate of the new collateral function addCollateral ( address collateral, uint256 valueToLoanRate, uint256 penaltyRate, uint256 bonusRate ) external onlyOwner { require (!collateralAssets[collateral].isExist, "The collateral is exist"); if (collateral != ethAddress) { IERC20(collateral); } collateralAssets[collateral].isExist = true; emit CollateralExistenceChanged(collateral, true); setValueToLoanRateInternal(collateral, valueToLoanRate); setPenaltyRateInternal(collateral, penaltyRate); setBonusRateInternal(collateral, bonusRate); activateCollateralInternal(collateral); } /// @notice Activate the market function activateMarketInternal (address market) internal { marketAssets[market].isActive = true; emit MarketActivationChanged(market, true); } /// @notice Activate the collateral function activateCollateralInternal (address collateral) internal { collateralAssets[collateral].isActive = true; emit CollateralActivationChanged(collateral, true); } /// @notice Set borrow rate operation function setBorrowRateInternal (address market, uint256 newBorrowRate) internal { require (newBorrowRate <= maxBorrowRate, "Rate should be less than max"); uint256 currentTime = block.timestamp; if (marketAssets[market].borrowRateUpdateTime != 0) { if (newBorrowRate > marketAssets[market].borrowRate) { uint256 deltaTime = currentTime.sub(marketAssets[market].borrowRateUpdateTime); require (deltaTime >= periodBetweenUpdates, "Increasing rate is not allowed at this time"); uint256 maxIncrease = marketAssets[market].borrowRate.add(borrowRateMaxIncrease); require (newBorrowRate <= maxIncrease, "Rate should be increased less than max allowed"); } holdefiContract.beforeChangeBorrowRate(market); } emit BorrowRateChanged(market, newBorrowRate, marketAssets[market].borrowRate); marketAssets[market].borrowRate = newBorrowRate; marketAssets[market].borrowRateUpdateTime = currentTime; } /// @notice Set suppliers share rate operation function setSuppliersShareRateInternal (address market, uint256 newSuppliersShareRate) internal { require ( newSuppliersShareRate >= minSuppliersShareRate && newSuppliersShareRate <= rateDecimals, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if (marketAssets[market].suppliersShareRateUpdateTime != 0) { if (newSuppliersShareRate < marketAssets[market].suppliersShareRate) { uint256 deltaTime = currentTime.sub(marketAssets[market].suppliersShareRateUpdateTime); require (deltaTime >= periodBetweenUpdates, "Decreasing rate is not allowed at this time"); uint256 decreasedAllowed = newSuppliersShareRate.add(suppliersShareRateMaxDecrease); require ( marketAssets[market].suppliersShareRate <= decreasedAllowed, "Rate should be decreased less than max allowed" ); } holdefiContract.beforeChangeSupplyRate(market); } emit SuppliersShareRateChanged( market, newSuppliersShareRate, marketAssets[market].suppliersShareRate ); marketAssets[market].suppliersShareRate = newSuppliersShareRate; marketAssets[market].suppliersShareRateUpdateTime = currentTime; } /// @notice Set value to loan rate operation function setValueToLoanRateInternal (address collateral, uint256 newValueToLoanRate) internal { require ( newValueToLoanRate <= maxValueToLoanRate && collateralAssets[collateral].penaltyRate.add(fivePercentLiquidationGap) <= newValueToLoanRate, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if ( collateralAssets[collateral].VTLUpdateTime != 0 && newValueToLoanRate > collateralAssets[collateral].valueToLoanRate ) { uint256 deltaTime = currentTime.sub(collateralAssets[collateral].VTLUpdateTime); require (deltaTime >= periodBetweenUpdates,"Increasing rate is not allowed at this time"); uint256 maxIncrease = collateralAssets[collateral].valueToLoanRate.add( valueToLoanRateMaxIncrease ); require (newValueToLoanRate <= maxIncrease,"Rate should be increased less than max allowed"); } emit ValueToLoanRateChanged( collateral, newValueToLoanRate, collateralAssets[collateral].valueToLoanRate ); collateralAssets[collateral].valueToLoanRate = newValueToLoanRate; collateralAssets[collateral].VTLUpdateTime = currentTime; } /// @notice Set penalty rate operation function setPenaltyRateInternal (address collateral, uint256 newPenaltyRate) internal { require ( newPenaltyRate <= maxPenaltyRate && newPenaltyRate <= collateralAssets[collateral].valueToLoanRate.sub(fivePercentLiquidationGap) && collateralAssets[collateral].bonusRate <= newPenaltyRate, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if ( collateralAssets[collateral].penaltyUpdateTime != 0 && newPenaltyRate > collateralAssets[collateral].penaltyRate ) { uint256 deltaTime = currentTime.sub(collateralAssets[collateral].penaltyUpdateTime); require (deltaTime >= periodBetweenUpdates, "Increasing rate is not allowed at this time"); uint256 maxIncrease = collateralAssets[collateral].penaltyRate.add(penaltyRateMaxIncrease); require (newPenaltyRate <= maxIncrease, "Rate should be increased less than max allowed"); } emit PenaltyRateChanged(collateral, newPenaltyRate, collateralAssets[collateral].penaltyRate); collateralAssets[collateral].penaltyRate = newPenaltyRate; collateralAssets[collateral].penaltyUpdateTime = currentTime; } /// @notice Set Bonus rate operation function setBonusRateInternal (address collateral, uint256 newBonusRate) internal { require ( newBonusRate <= collateralAssets[collateral].penaltyRate && newBonusRate >= rateDecimals, "Rate should be in allowed range" ); emit BonusRateChanged(collateral, newBonusRate, collateralAssets[collateral].bonusRate); collateralAssets[collateral].bonusRate = newBonusRate; } }
contract HoldefiSettings is HoldefiOwnable { using SafeMath for uint256; /// @notice Markets Features struct MarketSettings { bool isExist; // Market is exist or not bool isActive; // Market is open for deposit or not uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; // Collateral is exist or not bool isActive; // Collateral is open for deposit or not uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } uint256 constant public rateDecimals = 10 ** 4; address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 constant public periodBetweenUpdates = 864000; // seconds per ten days uint256 constant public maxBorrowRate = 4000; // 40% uint256 constant public borrowRateMaxIncrease = 500; // 5% uint256 constant public minSuppliersShareRate = 5000; // 50% uint256 constant public suppliersShareRateMaxDecrease = 500; // 5% uint256 constant public maxValueToLoanRate = 20000; // 200% uint256 constant public valueToLoanRateMaxIncrease = 500; // 5% uint256 constant public maxPenaltyRate = 13000; // 130% uint256 constant public penaltyRateMaxIncrease = 500; // 5% uint256 constant public maxPromotionRate = 3000; // 30% uint256 constant public maxListsLength = 25; /// @dev Used for calculating liquidation threshold /// There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; mapping (address => MarketSettings) public marketAssets; address[] public marketsList; mapping (address => CollateralSettings) public collateralAssets; HoldefiInterface public holdefiContract; /// @notice Event emitted when market activation status is changed event MarketActivationChanged(address indexed market, bool status); /// @notice Event emitted when collateral activation status is changed event CollateralActivationChanged(address indexed collateral, bool status); /// @notice Event emitted when market existence status is changed event MarketExistenceChanged(address indexed market, bool status); /// @notice Event emitted when collateral existence status is changed event CollateralExistenceChanged(address indexed collateral, bool status); /// @notice Event emitted when market borrow rate is changed event BorrowRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when market suppliers share rate is changed event SuppliersShareRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when market promotion rate is changed event PromotionRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral value to loan rate is changed event ValueToLoanRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral penalty rate is changed event PenaltyRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral bonus rate is changed event BonusRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @dev Modifier to make a function callable only when the market is exist /// @param market Address of the given market modifier marketIsExist(address market) { require (marketAssets[market].isExist, "The market is not exist"); _; } /// @dev Modifier to make a function callable only when the collateral is exist /// @param collateral Address of the given collateral modifier collateralIsExist(address collateral) { require (collateralAssets[collateral].isExist, "The collateral is not exist"); _; } /// @notice you cannot send ETH to this contract receive() external payable { revert(); } /// @notice Activate a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function activateMarket (address market) public onlyOwner marketIsExist(market) { activateMarketInternal(market); } /// @notice Deactivate a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function deactivateMarket (address market) public onlyOwner marketIsExist(market) { marketAssets[market].isActive = false; emit MarketActivationChanged(market, false); } /// @notice Activate a collateral asset /// @dev Can only be called by the owner /// @param collateral Address the given collateral function activateCollateral (address collateral) public onlyOwner collateralIsExist(collateral) { activateCollateralInternal(collateral); } /// @notice Deactivate a collateral asset /// @dev Can only be called by the owner /// @param collateral Address of the given collateral function deactivateCollateral (address collateral) public onlyOwner collateralIsExist(collateral) { collateralAssets[collateral].isActive = false; emit CollateralActivationChanged(collateral, false); } /// @notice Returns the list of markets /// @return res List of markets function getMarketsList() external view returns (address[] memory res){ res = marketsList; } /// @notice Disposable function to interact with Holdefi contract /// @dev Can only be called by the owner /// @param 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; } /// @notice Returns supply, borrow and promotion rate of the given market /// @dev supplyRate = (totalBorrow * borrowRate) * suppliersShareRate / totalSupply /// @param market Address of the given market /// @return borrowRate Borrow rate of the given market /// @return supplyRateBase Supply rate base of the given market /// @return promotionRate Promotion rate of the given market function getInterests (address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate) { uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow; uint256 totalSupply = holdefiContract.marketAssets(market).totalSupply; borrowRate = marketAssets[market].borrowRate; if (totalSupply == 0) { supplyRateBase = 0; } else { uint256 totalInterestFromBorrow = totalBorrow.mul(borrowRate); uint256 suppliersShare = totalInterestFromBorrow.mul(marketAssets[market].suppliersShareRate); suppliersShare = suppliersShare.div(rateDecimals); supplyRateBase = suppliersShare.div(totalSupply); } promotionRate = marketAssets[market].promotionRate; } /// @notice Set promotion rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newPromotionRate New promotion rate function setPromotionRate (address market, uint256 newPromotionRate) external onlyOwner { require (newPromotionRate <= maxPromotionRate, "Rate should be in allowed range"); holdefiContract.beforeChangeSupplyRate(market); holdefiContract.reserveSettlement(market); emit PromotionRateChanged(market, newPromotionRate, marketAssets[market].promotionRate); marketAssets[market].promotionRate = newPromotionRate; } /// @notice Reset promotion rate of the market to zero /// @dev Can only be called by holdefi contract /// @param market Address of the given market function resetPromotionRate (address market) external { require (msg.sender == address(holdefiContract), "Sender is not Holdefi contract"); emit PromotionRateChanged(market, 0, marketAssets[market].promotionRate); marketAssets[market].promotionRate = 0; } /// @notice Set borrow rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newBorrowRate New borrow rate function setBorrowRate (address market, uint256 newBorrowRate) external onlyOwner marketIsExist(market) { setBorrowRateInternal(market, newBorrowRate); } /// @notice Set suppliers share rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newSuppliersShareRate New suppliers share rate function setSuppliersShareRate (address market, uint256 newSuppliersShareRate) external onlyOwner marketIsExist(market) { setSuppliersShareRateInternal(market, newSuppliersShareRate); } /// @notice Set value to loan rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newValueToLoanRate New value to loan rate function setValueToLoanRate (address collateral, uint256 newValueToLoanRate) external onlyOwner collateralIsExist(collateral) { setValueToLoanRateInternal(collateral, newValueToLoanRate); } /// @notice Set penalty rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newPenaltyRate New penalty rate function setPenaltyRate (address collateral, uint256 newPenaltyRate) external onlyOwner collateralIsExist(collateral) { setPenaltyRateInternal(collateral, newPenaltyRate); } /// @notice Set bonus rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newBonusRate New bonus rate function setBonusRate (address collateral, uint256 newBonusRate) external onlyOwner collateralIsExist(collateral) { setBonusRateInternal(collateral, newBonusRate); } /// @notice Add a new asset as a market /// @dev Can only be called by the owner /// @param market Address of the new market /// @param borrowRate BorrowRate of the new market /// @param suppliersShareRate SuppliersShareRate of the new market function addMarket (address market, uint256 borrowRate, uint256 suppliersShareRate) external onlyOwner { require (!marketAssets[market].isExist, "The market is exist"); require (marketsList.length < maxListsLength, "Market list is full"); if (market != ethAddress) { IERC20(market); } marketsList.push(market); marketAssets[market].isExist = true; emit MarketExistenceChanged(market, true); setBorrowRateInternal(market, borrowRate); setSuppliersShareRateInternal(market, suppliersShareRate); activateMarketInternal(market); } /// @notice Remove a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function removeMarket (address market) external onlyOwner marketIsExist(market) { uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow; require (totalBorrow == 0, "Total borrow is not zero"); holdefiContract.beforeChangeBorrowRate(market); uint256 i; uint256 index; uint256 marketListLength = marketsList.length; for (i = 0 ; i < marketListLength ; i++) { if (marketsList[i] == market) { index = i; } } if (index != marketListLength-1) { for (i = index ; i < marketListLength-1 ; i++) { marketsList[i] = marketsList[i+1]; } } marketsList.pop(); delete marketAssets[market]; emit MarketExistenceChanged(market, false); } /// @notice Add a new asset as a collateral /// @dev Can only be called by the owner /// @param collateral Address of the new collateral /// @param valueToLoanRate ValueToLoanRate of the new collateral /// @param penaltyRate PenaltyRate of the new collateral /// @param bonusRate BonusRate of the new collateral function addCollateral ( address collateral, uint256 valueToLoanRate, uint256 penaltyRate, uint256 bonusRate ) external onlyOwner { require (!collateralAssets[collateral].isExist, "The collateral is exist"); if (collateral != ethAddress) { IERC20(collateral); } collateralAssets[collateral].isExist = true; emit CollateralExistenceChanged(collateral, true); setValueToLoanRateInternal(collateral, valueToLoanRate); setPenaltyRateInternal(collateral, penaltyRate); setBonusRateInternal(collateral, bonusRate); activateCollateralInternal(collateral); } /// @notice Activate the market function activateMarketInternal (address market) internal { marketAssets[market].isActive = true; emit MarketActivationChanged(market, true); } /// @notice Activate the collateral function activateCollateralInternal (address collateral) internal { collateralAssets[collateral].isActive = true; emit CollateralActivationChanged(collateral, true); } /// @notice Set borrow rate operation function setBorrowRateInternal (address market, uint256 newBorrowRate) internal { require (newBorrowRate <= maxBorrowRate, "Rate should be less than max"); uint256 currentTime = block.timestamp; if (marketAssets[market].borrowRateUpdateTime != 0) { if (newBorrowRate > marketAssets[market].borrowRate) { uint256 deltaTime = currentTime.sub(marketAssets[market].borrowRateUpdateTime); require (deltaTime >= periodBetweenUpdates, "Increasing rate is not allowed at this time"); uint256 maxIncrease = marketAssets[market].borrowRate.add(borrowRateMaxIncrease); require (newBorrowRate <= maxIncrease, "Rate should be increased less than max allowed"); } holdefiContract.beforeChangeBorrowRate(market); } emit BorrowRateChanged(market, newBorrowRate, marketAssets[market].borrowRate); marketAssets[market].borrowRate = newBorrowRate; marketAssets[market].borrowRateUpdateTime = currentTime; } /// @notice Set suppliers share rate operation function setSuppliersShareRateInternal (address market, uint256 newSuppliersShareRate) internal { require ( newSuppliersShareRate >= minSuppliersShareRate && newSuppliersShareRate <= rateDecimals, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if (marketAssets[market].suppliersShareRateUpdateTime != 0) { if (newSuppliersShareRate < marketAssets[market].suppliersShareRate) { uint256 deltaTime = currentTime.sub(marketAssets[market].suppliersShareRateUpdateTime); require (deltaTime >= periodBetweenUpdates, "Decreasing rate is not allowed at this time"); uint256 decreasedAllowed = newSuppliersShareRate.add(suppliersShareRateMaxDecrease); require ( marketAssets[market].suppliersShareRate <= decreasedAllowed, "Rate should be decreased less than max allowed" ); } holdefiContract.beforeChangeSupplyRate(market); } emit SuppliersShareRateChanged( market, newSuppliersShareRate, marketAssets[market].suppliersShareRate ); marketAssets[market].suppliersShareRate = newSuppliersShareRate; marketAssets[market].suppliersShareRateUpdateTime = currentTime; } /// @notice Set value to loan rate operation function setValueToLoanRateInternal (address collateral, uint256 newValueToLoanRate) internal { require ( newValueToLoanRate <= maxValueToLoanRate && collateralAssets[collateral].penaltyRate.add(fivePercentLiquidationGap) <= newValueToLoanRate, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if ( collateralAssets[collateral].VTLUpdateTime != 0 && newValueToLoanRate > collateralAssets[collateral].valueToLoanRate ) { uint256 deltaTime = currentTime.sub(collateralAssets[collateral].VTLUpdateTime); require (deltaTime >= periodBetweenUpdates,"Increasing rate is not allowed at this time"); uint256 maxIncrease = collateralAssets[collateral].valueToLoanRate.add( valueToLoanRateMaxIncrease ); require (newValueToLoanRate <= maxIncrease,"Rate should be increased less than max allowed"); } emit ValueToLoanRateChanged( collateral, newValueToLoanRate, collateralAssets[collateral].valueToLoanRate ); collateralAssets[collateral].valueToLoanRate = newValueToLoanRate; collateralAssets[collateral].VTLUpdateTime = currentTime; } /// @notice Set penalty rate operation function setPenaltyRateInternal (address collateral, uint256 newPenaltyRate) internal { require ( newPenaltyRate <= maxPenaltyRate && newPenaltyRate <= collateralAssets[collateral].valueToLoanRate.sub(fivePercentLiquidationGap) && collateralAssets[collateral].bonusRate <= newPenaltyRate, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if ( collateralAssets[collateral].penaltyUpdateTime != 0 && newPenaltyRate > collateralAssets[collateral].penaltyRate ) { uint256 deltaTime = currentTime.sub(collateralAssets[collateral].penaltyUpdateTime); require (deltaTime >= periodBetweenUpdates, "Increasing rate is not allowed at this time"); uint256 maxIncrease = collateralAssets[collateral].penaltyRate.add(penaltyRateMaxIncrease); require (newPenaltyRate <= maxIncrease, "Rate should be increased less than max allowed"); } emit PenaltyRateChanged(collateral, newPenaltyRate, collateralAssets[collateral].penaltyRate); collateralAssets[collateral].penaltyRate = newPenaltyRate; collateralAssets[collateral].penaltyUpdateTime = currentTime; } /// @notice Set Bonus rate operation function setBonusRateInternal (address collateral, uint256 newBonusRate) internal { require ( newBonusRate <= collateralAssets[collateral].penaltyRate && newBonusRate >= rateDecimals, "Rate should be in allowed range" ); emit BonusRateChanged(collateral, newBonusRate, collateralAssets[collateral].bonusRate); collateralAssets[collateral].bonusRate = newBonusRate; } }
21,572
348
// Function a smart contract must implement to be able to consent to a loan. The loan offeringwill be generated off-chain. The "loan owner" address will own the loan-side of the resultingposition. If true is returned, and no errors are thrown by the Margin contract, the loan will haveoccurred. This means that verifyLoanOffering can also be used to update internal contractstate on a loan. addressesArray of addresses:[0] = owedToken [1] = heldToken [2] = loan payer [3] = loan owner [4] = loan taker [5] = loan positionOwner [6] = loan fee recipient [7] = loan lender fee token [8] =
function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external
function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external
17,855
1
// A coefficient used to normalize the token to a value comparable to the debt token. For example, if the underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token.
uint256 conversionFactor;
uint256 conversionFactor;
10,811
221
// Modifier to make a function callable only when the contract is not paused.
modifier whenNotPaused() { require(!paused(), "Contract paused"); _; }
modifier whenNotPaused() { require(!paused(), "Contract paused"); _; }
24,914
3
// tracks owner of a fuelId
mapping(uint256 => address) public loaderOf;
mapping(uint256 => address) public loaderOf;
12,796
63
// Waste can be dumped only at allowed disposal stations
(bool result, uint station_id) = _checkFinalDestiantion(_latitude, _longitude); require(result == true);
(bool result, uint station_id) = _checkFinalDestiantion(_latitude, _longitude); require(result == true);
23,373
231
// Calculate for how long the token has been staked
uint256 stakedDays = (block.timestamp - conquestStart) / 24 / 60 / 60; uint256[3] memory periods = _stakingPeriods; uint256[3] memory rewards = _stakingRewards; if (stakedDays >= periods[2]) { return rewards[2]; } else if (stakedDays >= periods[1]) {
uint256 stakedDays = (block.timestamp - conquestStart) / 24 / 60 / 60; uint256[3] memory periods = _stakingPeriods; uint256[3] memory rewards = _stakingRewards; if (stakedDays >= periods[2]) { return rewards[2]; } else if (stakedDays >= periods[1]) {
40,426
84
// Tokens burned event /
event Burn(address from, uint256 amount);
event Burn(address from, uint256 amount);
28,783
49
// check settlement window
if (exerciseWindow == 0) revert PM_InvalidExerciseWindow(); (, uint8 underlyingId, uint8 strikeId, uint8 collateralId) = productId.parseProductId(); if (tokenType == TokenType.CALL && underlyingId != collateralId && !_isCollateralizable(underlyingId, collateralId)) { revert PM_InvalidCollateral(); }
if (exerciseWindow == 0) revert PM_InvalidExerciseWindow(); (, uint8 underlyingId, uint8 strikeId, uint8 collateralId) = productId.parseProductId(); if (tokenType == TokenType.CALL && underlyingId != collateralId && !_isCollateralizable(underlyingId, collateralId)) { revert PM_InvalidCollateral(); }
31,406
68
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
28,991
79
// attempt rageQuit notification
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
31,436
11
// Burns `_amount` reputation from `_owner`/_user The address that will lose the reputation/_amount The quantity of reputation to burn/ return True if the reputation are burned correctly
function burn(address _user, uint256 _amount) public returns (bool) { //user can burn his own rep other wise we check _canMint if (_user != _msgSender()) _canMint(); _burn(_user, _amount); return true; }
function burn(address _user, uint256 _amount) public returns (bool) { //user can burn his own rep other wise we check _canMint if (_user != _msgSender()) _canMint(); _burn(_user, _amount); return true; }
5,071
22
// emergency function in case a compromised locker is removed
function unlockIfRemovedLocker(uint256 tokenId) external override onlyOwner { if (!locked(tokenId)) { revert NotLockedAsset(); } if (_lockers[_lockedBy[tokenId]]) { revert NotADeactivatedLocker(); } delete _lockedBy[tokenId]; emit ForcefullyUnlocked(tokenId); }
function unlockIfRemovedLocker(uint256 tokenId) external override onlyOwner { if (!locked(tokenId)) { revert NotLockedAsset(); } if (_lockers[_lockedBy[tokenId]]) { revert NotADeactivatedLocker(); } delete _lockedBy[tokenId]; emit ForcefullyUnlocked(tokenId); }
37,845
10
// count all digits preceding least significant figure
numSigfigs++;
numSigfigs++;
16,476
6
// Changes the admin of the proxy. NOTE: Only the admin can call this function. /
function setAdmin(address _newAdmin) external ifAdmin { require(_newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); _setAdmin(_newAdmin); }
function setAdmin(address _newAdmin) external ifAdmin { require(_newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); _setAdmin(_newAdmin); }
17,295
15
// return entire purchased price if key is non-expiring
if (expirationDuration == type(uint).max) { return keyPrice; }
if (expirationDuration == type(uint).max) { return keyPrice; }
2,213
3
// Latest recorded promotion id. Starts at 0 and is incremented by 1 for each new promotion. So the first promotion will have id 1, the second 2, etc. /
uint256 internal _latestPromotionId;
uint256 internal _latestPromotionId;
24,910
112
// Reduce the balance of the account
balanceOf[account] = balanceOf[account] - amount;
balanceOf[account] = balanceOf[account] - amount;
24,318
18
// bytes32 constant MAIL_V2_TYPE_HASH = keccak256('MailV2(PersonV2 from,PersonV2[] to,string contents)PersonV2(string name,address[] wallet)'); bytes32 constant PERSON_V2_TYPE_HASH = keccak256('PersonV2(string name,address[] wallet)');
bytes32 constant Message_TYPE_HASH = keccak256('Message(string[] data)');
bytes32 constant Message_TYPE_HASH = keccak256('Message(string[] data)');
13,665
76
// formula: staker_burn = staker_stake / total_contract_stakecontract_burn reordered for precision loss prevention
_stakerBurnAmount = _currentStake.mul(_totalBurnAmount).div(_stakedOnContract); _newStake = _currentStake.sub(_stakerBurnAmount);
_stakerBurnAmount = _currentStake.mul(_totalBurnAmount).div(_stakedOnContract); _newStake = _currentStake.sub(_stakerBurnAmount);
21,529
129
// Calculate total amount of tokens being unlocked by now
uint totalUnlockedByNow = ((totalTimePassedFromUnlockingDay) / (30 days) + 1) * monthlyTransferAllowance;
uint totalUnlockedByNow = ((totalTimePassedFromUnlockingDay) / (30 days) + 1) * monthlyTransferAllowance;
49,436
79
// Return to user moneyEscrowed that wasn&39;t filled yet
if (_moneyEscrowed > 0) { ICash _denominationToken = _market.getDenominationToken(); require(_denominationToken.transferFrom(_market, _sender, _moneyEscrowed)); }
if (_moneyEscrowed > 0) { ICash _denominationToken = _market.getDenominationToken(); require(_denominationToken.transferFrom(_market, _sender, _moneyEscrowed)); }
52,637
466
// BalanceTrackable An ownable that has a balance tracker property /
contract BalanceTrackable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- BalanceTracker public balanceTracker; bool public balanceTrackerFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker); event FreezeBalanceTrackerEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the balance tracker contract /// @param newBalanceTracker The (address of) BalanceTracker contract instance function setBalanceTracker(BalanceTracker newBalanceTracker) public onlyDeployer notNullAddress(address(newBalanceTracker)) notSameAddresses(address(newBalanceTracker), address(balanceTracker)) { // Require that this contract has not been frozen require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]"); // Update fields BalanceTracker oldBalanceTracker = balanceTracker; balanceTracker = newBalanceTracker; // Emit event emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker); } /// @notice Freeze the balance tracker from further updates /// @dev This operation can not be undone function freezeBalanceTracker() public onlyDeployer { balanceTrackerFrozen = true; // Emit event emit FreezeBalanceTrackerEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier balanceTrackerInitialized() { require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]"); _; } }
contract BalanceTrackable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- BalanceTracker public balanceTracker; bool public balanceTrackerFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker); event FreezeBalanceTrackerEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the balance tracker contract /// @param newBalanceTracker The (address of) BalanceTracker contract instance function setBalanceTracker(BalanceTracker newBalanceTracker) public onlyDeployer notNullAddress(address(newBalanceTracker)) notSameAddresses(address(newBalanceTracker), address(balanceTracker)) { // Require that this contract has not been frozen require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]"); // Update fields BalanceTracker oldBalanceTracker = balanceTracker; balanceTracker = newBalanceTracker; // Emit event emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker); } /// @notice Freeze the balance tracker from further updates /// @dev This operation can not be undone function freezeBalanceTracker() public onlyDeployer { balanceTrackerFrozen = true; // Emit event emit FreezeBalanceTrackerEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier balanceTrackerInitialized() { require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]"); _; } }
21,993
23
// abi hash encode to bytes
require( ITssGroupManager(resolve("Proxy__TSS_GroupManager")).verifySign( keccak256(abi.encode(_batch, _shouldStartAtElement)), _signature), "verify signature failed" );
require( ITssGroupManager(resolve("Proxy__TSS_GroupManager")).verifySign( keccak256(abi.encode(_batch, _shouldStartAtElement)), _signature), "verify signature failed" );
15,519
77
// we can only defund BIT or MNT into the predefined treasury address
ERC20(_tokenAddress).safeTransfer(treasury, _amount); emit ContractDefunded(treasury, _tokenAddress, _amount);
ERC20(_tokenAddress).safeTransfer(treasury, _amount); emit ContractDefunded(treasury, _tokenAddress, _amount);
12,367
31
// Ensures the caller is the StakingAuRa contract address.
modifier onlyStakingContract() { require(msg.sender == address(stakingContract)); _; }
modifier onlyStakingContract() { require(msg.sender == address(stakingContract)); _; }
27,652
15
// the only type of liquidation where we do not need to involve swappa is: - collateral == loan asset - receiveAToken == false example is if someone deposited cUSD and borrowed cUSD
require(collateral == loanAsset, "no swap path defined, collateral must be equal to loan asset");
require(collateral == loanAsset, "no swap path defined, collateral must be equal to loan asset");
29,620
58
// Override exchange rate for daily bonuses
if (now < START_TIME + 3600 * 24 * 1) { exchangeRate = 10800; } else if (now < START_TIME + 3600 * 24 * 2) {
if (now < START_TIME + 3600 * 24 * 1) { exchangeRate = 10800; } else if (now < START_TIME + 3600 * 24 * 2) {
23,580
128
// Create a reusable template, which should be a JSON document./ Placeholders should use gettext() syntax, eg %s./Template data is only stored in the event logs, but its block number is kept in contract storage./content The template content/ return The ID of the newly-created template, which is created sequentially.
function createTemplate(string calldata content) external returns (uint256);
function createTemplate(string calldata content) external returns (uint256);
49,598
5
// Emitted when the fee BPS is changed for a given NFT.tokenId The token ID mapped to the NFT. newFeeBps The new fee BPS mapped to the NFT. /
event FeeBpsChanged(uint256 indexed tokenId, uint16 newFeeBps);
event FeeBpsChanged(uint256 indexed tokenId, uint16 newFeeBps);
39,290
249
// Limit token transfer until the TGE is over./
modifier tokenReleased(address _sender) { require(released); _; }
modifier tokenReleased(address _sender) { require(released); _; }
1,098
0
// Sets the initial storage of the contract. _owners List of Safe owners. _threshold Number of required confirmations for a Safe transaction. /
function setupOwners(address[] memory _owners, uint256 _threshold) internal {
function setupOwners(address[] memory _owners, uint256 _threshold) internal {
24,304
307
// User supplies assets into the market and receives sTokens in exchange Assumes interest has already been accrued up to the current block minter The address of the account which is supplying the assets mintAmount The amount of the underlying asset to supplyreturn (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. /
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The sToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the sToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of sTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of sTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); }
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The sToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the sToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of sTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of sTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); }
56,819
211
// Burn the sold tokens (both front-end and back-end variants).
tokenSupply = tokenSupply.sub(_frontEndTokensToBurn); divTokenSupply = divTokenSupply.sub(_divTokensToBurn);
tokenSupply = tokenSupply.sub(_frontEndTokensToBurn); divTokenSupply = divTokenSupply.sub(_divTokensToBurn);
18,797
39
// Change the current bonus
function setCurrentBonus(uint256 _bonus) private { bonus = _bonus; return; }
function setCurrentBonus(uint256 _bonus) private { bonus = _bonus; return; }
4,570
77
// Divide delta by 1010 to bring it to 4 decimals for strike selection
if (sp >= st) { (d1, d2) = derivatives(t, v, sp, st); delta = Math.ncdf((Math.FIXED_1 * d1) / 1e18).div(10**10); } else {
if (sp >= st) { (d1, d2) = derivatives(t, v, sp, st); delta = Math.ncdf((Math.FIXED_1 * d1) / 1e18).div(10**10); } else {
35,500
288
// handle
punkBids[tokenId] = Bid(false, tokenId, address(0), 0); _safeTransfer(_msgSender(), bid.bidder, tokenId, "");
punkBids[tokenId] = Bid(false, tokenId, address(0), 0); _safeTransfer(_msgSender(), bid.bidder, tokenId, "");
27,085
2
// to set the merkle proof
function updateMerkleRoot(bytes32 newmerkleRoot) external onlyOwner { merkleRoot = newmerkleRoot; emit MerkleRootUpdated(merkleRoot); }
function updateMerkleRoot(bytes32 newmerkleRoot) external onlyOwner { merkleRoot = newmerkleRoot; emit MerkleRootUpdated(merkleRoot); }
29,892
16
// The COMP borrow index for each market for each borrower as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compBorrowerIndex;
mapping(address => mapping(address => uint)) public compBorrowerIndex;
25,712
57
// if the proposal spends 100% of guild bank balance for a token, decrement total guild bank tokens
if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; }
if (userTokenBalances[GUILD][proposal.paymentToken] == 0 && proposal.paymentRequested > 0) { totalGuildBankTokens -= 1; }
18,116
50
// See {recover}. /
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
65,357
284
// manage metadata changes and upgrades to v2 and minting new v2
contract ChildTAMAGManager is Ownable{ address public signerAddress; ITAMAG2 public newTamag; event TamagUpdated(uint256 tamagId, string tokenURI, uint256 traits, uint256 nounce); event TamagEquipAdd(uint256 tamagId, string tokenURI, uint256 equipId, uint256 slot, uint256 nounce); event TamagEquipRemove(uint256 tamagId, string tokenURI, uint256 equipId, uint256 slot, uint256 nounce); event TamagEquipSwap(uint256 tamagId, string tokenURI, uint256 oldEquipId, uint256 equipId, uint256 slot, uint256 nounce); constructor(address _signerAddress, address _newTamag) public Ownable(){ signerAddress = _signerAddress; newTamag = ITAMAG2(_newTamag); } function setNewTamagContract(address a) public onlyOwner{ newTamag = ITAMAG2(a); } function setSignerAddress(address a) public onlyOwner { signerAddress = a; } modifier isTamagOwner(uint256 tamagId) { require(newTamag.ownerOf(tamagId) == _msgSender(), "Caller must be tamag owner"); _; } // assumes hash is always 32 bytes long as it is a keccak output function prefixed(bytes32 myHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", myHash)); } function verify(bytes32 hashInSignature, uint8 v, bytes32 r, bytes32 s) internal { address signer = ecrecover(hashInSignature, v, r, s); require(signer == signerAddress, "Error signer"); } // requires both owner and dev to participate in this; function setMetadataByUser(uint256 tamagId, uint256 newTraits, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId){ uint256 currNounce = newTamag.getAndIncrementNounce(tamagId); bytes32 hashInSignature = prefixed(keccak256(abi.encodePacked(currNounce,"_",newTraits,"_",tamagId,"_",tokenURI))); verify(hashInSignature,v,r,s); newTamag.managerSetTraitAndURI(tamagId, newTraits, tokenURI); emit TamagUpdated(tamagId, tokenURI, newTraits, currNounce); } function switchEquip(uint256 tamagId, uint256 oldEquipId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId) { newTamag.unequipNoChangeGif(_msgSender(), tamagId, oldEquipId, slot); equip(tamagId, equipId, slot, tokenURI, v, r, s); uint256 n = newTamag.idToNounce(tamagId); emit TamagEquipSwap(tamagId, tokenURI, oldEquipId, equipId, slot, n); } function makeURIChange(uint256 tamagId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) internal returns (uint256){ uint256 currNounce = newTamag.getAndIncrementNounce(tamagId); bytes32 hashInSignature = prefixed(keccak256(abi.encodePacked(currNounce,"_",tamagId,"_",equipId,"_",slot,"_",tokenURI))); verify(hashInSignature,v,r,s); newTamag.managerSetTokenURI(tamagId, tokenURI); return currNounce; } function equip(uint256 tamagId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId) { newTamag.equipNoChangeGif(_msgSender(), tamagId, equipId, slot); uint256 n = makeURIChange(tamagId, equipId, slot, tokenURI, v,r,s); emit TamagEquipAdd(tamagId, tokenURI, equipId, slot, n); } function unequip(uint256 tamagId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId) { newTamag.unequipNoChangeGif(_msgSender(), tamagId, equipId, slot); uint256 n = makeURIChange(tamagId, equipId, slot, tokenURI, v,r,s); emit TamagEquipRemove(tamagId, tokenURI, equipId, slot, n); } function close() public onlyOwner { address payable p = payable(owner()); selfdestruct(p); } }
contract ChildTAMAGManager is Ownable{ address public signerAddress; ITAMAG2 public newTamag; event TamagUpdated(uint256 tamagId, string tokenURI, uint256 traits, uint256 nounce); event TamagEquipAdd(uint256 tamagId, string tokenURI, uint256 equipId, uint256 slot, uint256 nounce); event TamagEquipRemove(uint256 tamagId, string tokenURI, uint256 equipId, uint256 slot, uint256 nounce); event TamagEquipSwap(uint256 tamagId, string tokenURI, uint256 oldEquipId, uint256 equipId, uint256 slot, uint256 nounce); constructor(address _signerAddress, address _newTamag) public Ownable(){ signerAddress = _signerAddress; newTamag = ITAMAG2(_newTamag); } function setNewTamagContract(address a) public onlyOwner{ newTamag = ITAMAG2(a); } function setSignerAddress(address a) public onlyOwner { signerAddress = a; } modifier isTamagOwner(uint256 tamagId) { require(newTamag.ownerOf(tamagId) == _msgSender(), "Caller must be tamag owner"); _; } // assumes hash is always 32 bytes long as it is a keccak output function prefixed(bytes32 myHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", myHash)); } function verify(bytes32 hashInSignature, uint8 v, bytes32 r, bytes32 s) internal { address signer = ecrecover(hashInSignature, v, r, s); require(signer == signerAddress, "Error signer"); } // requires both owner and dev to participate in this; function setMetadataByUser(uint256 tamagId, uint256 newTraits, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId){ uint256 currNounce = newTamag.getAndIncrementNounce(tamagId); bytes32 hashInSignature = prefixed(keccak256(abi.encodePacked(currNounce,"_",newTraits,"_",tamagId,"_",tokenURI))); verify(hashInSignature,v,r,s); newTamag.managerSetTraitAndURI(tamagId, newTraits, tokenURI); emit TamagUpdated(tamagId, tokenURI, newTraits, currNounce); } function switchEquip(uint256 tamagId, uint256 oldEquipId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId) { newTamag.unequipNoChangeGif(_msgSender(), tamagId, oldEquipId, slot); equip(tamagId, equipId, slot, tokenURI, v, r, s); uint256 n = newTamag.idToNounce(tamagId); emit TamagEquipSwap(tamagId, tokenURI, oldEquipId, equipId, slot, n); } function makeURIChange(uint256 tamagId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) internal returns (uint256){ uint256 currNounce = newTamag.getAndIncrementNounce(tamagId); bytes32 hashInSignature = prefixed(keccak256(abi.encodePacked(currNounce,"_",tamagId,"_",equipId,"_",slot,"_",tokenURI))); verify(hashInSignature,v,r,s); newTamag.managerSetTokenURI(tamagId, tokenURI); return currNounce; } function equip(uint256 tamagId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId) { newTamag.equipNoChangeGif(_msgSender(), tamagId, equipId, slot); uint256 n = makeURIChange(tamagId, equipId, slot, tokenURI, v,r,s); emit TamagEquipAdd(tamagId, tokenURI, equipId, slot, n); } function unequip(uint256 tamagId, uint256 equipId, uint256 slot, string memory tokenURI, uint8 v, bytes32 r, bytes32 s) public isTamagOwner(tamagId) { newTamag.unequipNoChangeGif(_msgSender(), tamagId, equipId, slot); uint256 n = makeURIChange(tamagId, equipId, slot, tokenURI, v,r,s); emit TamagEquipRemove(tamagId, tokenURI, equipId, slot, n); } function close() public onlyOwner { address payable p = payable(owner()); selfdestruct(p); } }
24,134
137
// File: @airswap/delegate/contracts/DelegateFactory.sol//
contract DelegateFactory is IDelegateFactory, ILocatorWhitelist { // Mapping specifying whether an address was deployed by this factory mapping(address => bool) internal _deployedAddresses; // The swap and indexer contracts to use in the deployment of Delegates ISwap public swapContract; IIndexer public indexerContract; bytes2 public protocol; /** * @notice Create a new Delegate contract * @dev swapContract is unable to be changed after the factory sets it * @param factorySwapContract address Swap contract the delegate will deploy with * @param factoryIndexerContract address Indexer contract the delegate will deploy with * @param factoryProtocol bytes2 Protocol type of the delegates the factory deploys */ constructor( ISwap factorySwapContract, IIndexer factoryIndexerContract, bytes2 factoryProtocol ) public { swapContract = factorySwapContract; indexerContract = factoryIndexerContract; protocol = factoryProtocol; } /** * @param delegateTradeWallet address Wallet the delegate will trade from * @return address delegateContractAddress Address of the delegate contract created */ function createDelegate( address delegateTradeWallet ) external returns (address delegateContractAddress) { delegateContractAddress = address( new Delegate(swapContract, indexerContract, msg.sender, delegateTradeWallet, protocol) ); _deployedAddresses[delegateContractAddress] = true; emit CreateDelegate( delegateContractAddress, address(swapContract), address(indexerContract), msg.sender, delegateTradeWallet ); return delegateContractAddress; } /** * @notice To check whether a locator was deployed * @dev Implements ILocatorWhitelist.has * @param locator bytes32 Locator of the delegate in question * @return bool True if the delegate was deployed by this contract */ function has(bytes32 locator) external view returns (bool) { return _deployedAddresses[address(bytes20(locator))]; } }
contract DelegateFactory is IDelegateFactory, ILocatorWhitelist { // Mapping specifying whether an address was deployed by this factory mapping(address => bool) internal _deployedAddresses; // The swap and indexer contracts to use in the deployment of Delegates ISwap public swapContract; IIndexer public indexerContract; bytes2 public protocol; /** * @notice Create a new Delegate contract * @dev swapContract is unable to be changed after the factory sets it * @param factorySwapContract address Swap contract the delegate will deploy with * @param factoryIndexerContract address Indexer contract the delegate will deploy with * @param factoryProtocol bytes2 Protocol type of the delegates the factory deploys */ constructor( ISwap factorySwapContract, IIndexer factoryIndexerContract, bytes2 factoryProtocol ) public { swapContract = factorySwapContract; indexerContract = factoryIndexerContract; protocol = factoryProtocol; } /** * @param delegateTradeWallet address Wallet the delegate will trade from * @return address delegateContractAddress Address of the delegate contract created */ function createDelegate( address delegateTradeWallet ) external returns (address delegateContractAddress) { delegateContractAddress = address( new Delegate(swapContract, indexerContract, msg.sender, delegateTradeWallet, protocol) ); _deployedAddresses[delegateContractAddress] = true; emit CreateDelegate( delegateContractAddress, address(swapContract), address(indexerContract), msg.sender, delegateTradeWallet ); return delegateContractAddress; } /** * @notice To check whether a locator was deployed * @dev Implements ILocatorWhitelist.has * @param locator bytes32 Locator of the delegate in question * @return bool True if the delegate was deployed by this contract */ function has(bytes32 locator) external view returns (bool) { return _deployedAddresses[address(bytes20(locator))]; } }
10,239
11
// 2 observations are needed to reliably calculate the block starting tick
require(observationCardinality > 1, 'NEO');
require(observationCardinality > 1, 'NEO');
32,194
51
// SafeERC20 Wrappers around ERC20 operations that throw on failure (when the tokencontract returns false). Tokens that return no value (and instead revert orthrow on failure) are also supported, non-reverting calls are assumed to besuccessful.To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,which allows you to call the safe operations as `token.safeTransfer(...)`, etc. /
library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
23,251
114
// Resets the lottery, clears the existing state variable values and the lotterycan be initialized again. Emits {LotteryReset} event indicating that the lottery config and contract state is reset. Requirements: - Only the address set at `adminAddress` can call this function.- The Lottery has closed. /
function resetLottery() private {
function resetLottery() private {
30,201
266
// And may not be set to be shorter than a day.
uint constant MIN_FEE_PERIOD_DURATION_SECONDS = 1 days;
uint constant MIN_FEE_PERIOD_DURATION_SECONDS = 1 days;
81,461
89
// return return true(false) if order specified by `orderHash` is(not) cancelled/
function getCancel( bytes32 orderHash ) public view returns (bool)
function getCancel( bytes32 orderHash ) public view returns (bool)
13,272
45
// See {_burn} and {_approve}. /
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance") ); }
function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance") ); }
926
151
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
24,595
0
// The name of this contract
string public constant NAME = 'Amphora Protocol Governor';
string public constant NAME = 'Amphora Protocol Governor';
29,064
3
// used to decouple insurance price and multiplier from data contract
uint256 amount; uint256 multiplier; bool credited;
uint256 amount; uint256 multiplier; bool credited;
44,398
18
// cancelProposal cancels the proposal if no one managed to vote yet must be sent from the proposal contract
function cancelProposal(uint256 proposalID) nonReentrant external { ProposalState storage prop = proposals[proposalID]; require(prop.params.proposalContract != address(0), "proposal with a given ID doesnt exist"); require(isInitialStatus(prop.status), "proposal isn't active"); require(prop.votes == 0, "voting has already begun"); require(msg.sender == prop.params.proposalContract, "must be sent from the proposal contract"); prop.status = statusCanceled(); emit ProposalCanceled(proposalID); }
function cancelProposal(uint256 proposalID) nonReentrant external { ProposalState storage prop = proposals[proposalID]; require(prop.params.proposalContract != address(0), "proposal with a given ID doesnt exist"); require(isInitialStatus(prop.status), "proposal isn't active"); require(prop.votes == 0, "voting has already begun"); require(msg.sender == prop.params.proposalContract, "must be sent from the proposal contract"); prop.status = statusCanceled(); emit ProposalCanceled(proposalID); }
7,087
275
// If the borrower is a credit account, check the credit limit instead of account liquidity.
if (creditLimit > 0) { (uint256 oErr, , uint256 borrowBalance, ) = CToken(cToken).getAccountSnapshot(borrower); require(oErr == 0, "snapshot error"); require(creditLimit >= add_(borrowBalance, borrowAmount), "insufficient credit limit"); } else {
if (creditLimit > 0) { (uint256 oErr, , uint256 borrowBalance, ) = CToken(cToken).getAccountSnapshot(borrower); require(oErr == 0, "snapshot error"); require(creditLimit >= add_(borrowBalance, borrowAmount), "insufficient credit limit"); } else {
50,954
1,142
// Emits an {CurrencyApproval} event. Requirements: - `currency` cannot be the zero address. 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE will denote to native coin (eth,matic, and etc.) - `spender` cannot be the zero address./
function _approve( address currency, address spender, uint256 amount ) internal { require( currency != address(0), "CurrencyPermit: approve currency of zero address" ); require(
function _approve( address currency, address spender, uint256 amount ) internal { require( currency != address(0), "CurrencyPermit: approve currency of zero address" ); require(
30,787
8
// Get consensus values from request
( uint16 interestRate, uint16 collateralRatio, uint256 maxLoanAmount ) = LibConsensus.processLoanTerms(request); Loan storage loan = LibCreateLoan.initNewLoan( request.request.assetAddress, maxLoanAmount, request.request.duration, interestRate
( uint16 interestRate, uint16 collateralRatio, uint256 maxLoanAmount ) = LibConsensus.processLoanTerms(request); Loan storage loan = LibCreateLoan.initNewLoan( request.request.assetAddress, maxLoanAmount, request.request.duration, interestRate
49,951
2
// confirms that the caller is the guardian account/
modifier onlyGuardian { require(msg.sender == guardian, "invalid caller"); _; }
modifier onlyGuardian { require(msg.sender == guardian, "invalid caller"); _; }
10,984
27
// update length
mstore(stringPtr, add(currentStringLength, len)) mstore(0x40, mload(add(result, 0xa0))) mstore(0x60, mload(add(result, 0xc0))) mstore(0x80, mload(add(result, 0xe0))) mstore(0xa0, mload(add(result, 0x100))) mstore(0xc0, mload(add(result, 0x120))) mstore(0xe0, mload(add(result, 0x140))) mstore(0x100, mload(add(result, 0x160))) mstore(0x120, mload(add(result, 0x180)))
mstore(stringPtr, add(currentStringLength, len)) mstore(0x40, mload(add(result, 0xa0))) mstore(0x60, mload(add(result, 0xc0))) mstore(0x80, mload(add(result, 0xe0))) mstore(0xa0, mload(add(result, 0x100))) mstore(0xc0, mload(add(result, 0x120))) mstore(0xe0, mload(add(result, 0x140))) mstore(0x100, mload(add(result, 0x160))) mstore(0x120, mload(add(result, 0x180)))
43,452
6
// Events that the contract emits /
event StratHarvest(address indexed harvester); event StratRebalance(uint256 _borrowRate, uint256 _borrowDepth); constructor( address _want, address _borrow, address _native, uint256 _borrowRate,
event StratHarvest(address indexed harvester); event StratRebalance(uint256 _borrowRate, uint256 _borrowDepth); constructor( address _want, address _borrow, address _native, uint256 _borrowRate,
29,715
20
// function for applying accounts closing request
function ApplyToCloseAccount (address ClosingAccountAddress) public
function ApplyToCloseAccount (address ClosingAccountAddress) public
7,213
1
// Updates the base URL of tokenReverts if the sender is not owner _newURI New base URL /
function updateBaseTokenURI(string memory _newURI) public onlyOwner noEmergencyFreeze
function updateBaseTokenURI(string memory _newURI) public onlyOwner noEmergencyFreeze
65,719
27
// Add to the staked balance and total supply.
stakedBalanceOf[_holder][_projectId] = stakedBalanceOf[_holder][_projectId] + _amount; stakedTotalSupplyOf[_projectId] = stakedTotalSupplyOf[_projectId] + _amount;
stakedBalanceOf[_holder][_projectId] = stakedBalanceOf[_holder][_projectId] + _amount; stakedTotalSupplyOf[_projectId] = stakedTotalSupplyOf[_projectId] + _amount;
29,460
13
// 发放商品
IStoreOP(goods[goodsId].contractAddress).mint(msg.sender, quantity, goods[goodsId].data); goods[goodsId].quantitySold += uint32(quantity);
IStoreOP(goods[goodsId].contractAddress).mint(msg.sender, quantity, goods[goodsId].data); goods[goodsId].quantitySold += uint32(quantity);
29,708
469
// default to 10%
refundPenaltyBasisPoints = 1000;
refundPenaltyBasisPoints = 1000;
37,906
62
// Next emission point.
eid++;
eid++;
2,756
39
// overwrite _maxRepayLimit memory variable in order to prevent stack too deep error when emitting repay event
_maxRepayLimit = repaymentAmountAfterFees;
_maxRepayLimit = repaymentAmountAfterFees;
25,431
55
// Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address.- `account` must have at least `amount` tokens. /
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount);
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount);
545
95
// We need to swap the current tokens to ETH and send to the MarketingPool wallet
swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketingPool(address(this).balance); }
swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToMarketingPool(address(this).balance); }
4,409
275
// Borrow the max borrowable amount.
borrowAmount = getBorrowableAmount(); if (borrowAmount != 0) { _borrow(borrowAmount); }
borrowAmount = getBorrowableAmount(); if (borrowAmount != 0) { _borrow(borrowAmount); }
4,682
60
// function to allow admin to transfer ETH from this contract
function TransferETH(address payable recipient, uint256 amount) public onlyOwner { recipient.transfer(amount); }
function TransferETH(address payable recipient, uint256 amount) public onlyOwner { recipient.transfer(amount); }
10,620
12
// Change Crowdsale Stage. Available Options: PreICO, ICO
function setCrowdsaleStage(uint value) public onlyOwner { CrowdsaleStage _stage; if (uint(CrowdsaleStage.PreICO) == value) { _stage = CrowdsaleStage.PreICO; } else if (uint(CrowdsaleStage.ICO) == value) { _stage = CrowdsaleStage.ICO; } stage = _stage; if (stage == CrowdsaleStage.PreICO) { setCurrentRate(2); // this is a 100% we will need a 30% bonus } else if (stage == CrowdsaleStage.ICO) { setCurrentRate(1); // no bonus in the public sale } }
function setCrowdsaleStage(uint value) public onlyOwner { CrowdsaleStage _stage; if (uint(CrowdsaleStage.PreICO) == value) { _stage = CrowdsaleStage.PreICO; } else if (uint(CrowdsaleStage.ICO) == value) { _stage = CrowdsaleStage.ICO; } stage = _stage; if (stage == CrowdsaleStage.PreICO) { setCurrentRate(2); // this is a 100% we will need a 30% bonus } else if (stage == CrowdsaleStage.ICO) { setCurrentRate(1); // no bonus in the public sale } }
49,806
20
// Stores token balances of this contract at a given moment.It's used to ensure there're no changes in balances at theend of a transaction. /
store.tokensToCheck = new Snapshot[](10);
store.tokensToCheck = new Snapshot[](10);
40,928
6
// Completes POWO transfers by updating the balances on the current block number_from address to transfer from_to addres to transfer to_amount to transfer/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount > 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked require(allowedToTrade(self, _from, _amount), "Stake amount was not removed from balance"); uint256 previousBalance = balanceOfAt(self, _from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self, _to, block.number); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); }
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public { require(_amount > 0, "Tried to send non-positive amount"); require(_to != address(0), "Receiver is 0 address"); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked require(allowedToTrade(self, _from, _amount), "Stake amount was not removed from balance"); uint256 previousBalance = balanceOfAt(self, _from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self, _to, block.number); require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); }
15,278
5
// break if is an index of an IndexAccess
a[b.c];
a[b.c];
53,837
204
// pool can only be joined when it's unpaused /
modifier joiningNotPaused() { require(!pauseStatus, "TrueFiPool: Joining the pool is paused"); _; }
modifier joiningNotPaused() { require(!pauseStatus, "TrueFiPool: Joining the pool is paused"); _; }
41,089
111
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
25,306
126
// 流动性奖励地址
address public liquidityRewardPoolAddr; uint256 public constant REWARD_POOL_MULTIPLE = 13; uint256 public constant PUBLISHER_MULTIPLE = 3; uint256 public constant DEVELOPER_MULTIPLE = 2;
address public liquidityRewardPoolAddr; uint256 public constant REWARD_POOL_MULTIPLE = 13; uint256 public constant PUBLISHER_MULTIPLE = 3; uint256 public constant DEVELOPER_MULTIPLE = 2;
15,465
20
// todo: 0 out released amount if missing balance from trader
uint256 releasedAmount = uint256(userState.releasedDepositAssetAmount); if (releasedAmount <= _amount) { uint256 redeemAmount = _amount.sub(releasedAmount); userState.pendingAsset = uint256(userState.pendingAsset).sub( redeemAmount ).toUint128(); userState.releasedDepositAssetAmount = 0; _option.totalReleasedDepositAssetAmount = uint256(_option .totalReleasedDepositAssetAmount) .sub(releasedAmount).toUint128();
uint256 releasedAmount = uint256(userState.releasedDepositAssetAmount); if (releasedAmount <= _amount) { uint256 redeemAmount = _amount.sub(releasedAmount); userState.pendingAsset = uint256(userState.pendingAsset).sub( redeemAmount ).toUint128(); userState.releasedDepositAssetAmount = 0; _option.totalReleasedDepositAssetAmount = uint256(_option .totalReleasedDepositAssetAmount) .sub(releasedAmount).toUint128();
14,838
168
// Can be overridden to add finalization logic. The overriding function/should call super.finalization() to ensure the chain of finalization is/executed entirely.
function finalization() internal { }
function finalization() internal { }
53,998
71
// Initialize can only be called once. It saves the block number in which it was initialized.Initializes a kernel instance along with its ACL and sets `_permissionsCreator` as the entity that can create other permissions_baseAcl Address of base ACL app_permissionsCreator Entity that will be given permission over createPermission/
function initialize(address _baseAcl, address _permissionsCreator) onlyInit public { initialized(); IACL acl = IACL(newAppProxy(this, ACL_APP_ID)); _setApp(APP_BASES_NAMESPACE, ACL_APP_ID, _baseAcl); _setApp(APP_ADDR_NAMESPACE, ACL_APP_ID, acl); acl.initialize(_permissionsCreator); }
function initialize(address _baseAcl, address _permissionsCreator) onlyInit public { initialized(); IACL acl = IACL(newAppProxy(this, ACL_APP_ID)); _setApp(APP_BASES_NAMESPACE, ACL_APP_ID, _baseAcl); _setApp(APP_ADDR_NAMESPACE, ACL_APP_ID, acl); acl.initialize(_permissionsCreator); }
51,176
48
// validate pair
lpToken = IDXswapFactory(factory).getPair(tokenA, tokenB); if (lpToken == address(0)) revert InvalidPair(); _approveTokenIfNeeded(lpToken, amount, router);
lpToken = IDXswapFactory(factory).getPair(tokenA, tokenB); if (lpToken == address(0)) revert InvalidPair(); _approveTokenIfNeeded(lpToken, amount, router);
22,076
0
// Partial interface for Oracle contract/Based on PriceOracle from Compound Finance/ (https:github.com/compound-finance/compound-protocol/blob/v2.8.1/contracts/PriceOracle.sol)
interface IOracle { /// @notice Get the underlying price of a market(cToken) asset /// @param market The market to get the underlying price of /// @return The underlying asset price mantissa (scaled by 1e18). /// Zero means the price is unavailable. function getUnderlyingPrice(address market) external view returns (uint256); /// @notice Evaluates input amount according to stored price, accrues interest /// @param cToken Market to evaluate /// @param amount Amount of tokens to evaluate according to 'reverse' order /// @param reverse Order of evaluation /// @return Depending on 'reverse' order: /// false - return USD amount equal to 'amount' of 'cToken' /// true - return cTokens equal to 'amount' of USD function getEvaluation(address cToken, uint256 amount, bool reverse) external returns (uint256); /// @notice Evaluates input amount according to stored price, doesn't accrue interest /// @param cToken Market to evaluate /// @param amount Amount of tokens to evaluate according to 'reverse' order /// @param reverse Order of evaluation /// @return Depending on 'reverse' order: /// false - return USD amount equal to 'amount' of 'cToken' /// true - return cTokens equal to 'amount' of USD function getEvaluationStored( address cToken, uint256 amount, bool reverse ) external view returns (uint256); }
interface IOracle { /// @notice Get the underlying price of a market(cToken) asset /// @param market The market to get the underlying price of /// @return The underlying asset price mantissa (scaled by 1e18). /// Zero means the price is unavailable. function getUnderlyingPrice(address market) external view returns (uint256); /// @notice Evaluates input amount according to stored price, accrues interest /// @param cToken Market to evaluate /// @param amount Amount of tokens to evaluate according to 'reverse' order /// @param reverse Order of evaluation /// @return Depending on 'reverse' order: /// false - return USD amount equal to 'amount' of 'cToken' /// true - return cTokens equal to 'amount' of USD function getEvaluation(address cToken, uint256 amount, bool reverse) external returns (uint256); /// @notice Evaluates input amount according to stored price, doesn't accrue interest /// @param cToken Market to evaluate /// @param amount Amount of tokens to evaluate according to 'reverse' order /// @param reverse Order of evaluation /// @return Depending on 'reverse' order: /// false - return USD amount equal to 'amount' of 'cToken' /// true - return cTokens equal to 'amount' of USD function getEvaluationStored( address cToken, uint256 amount, bool reverse ) external view returns (uint256); }
16,661
155
// set a new reference to the NFT ownership contract/_CStorageAddress - address of a deployed contract implementing EthernautsStorage.
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; }
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; }
63,178