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
27
// Returns the downcasted uint104 from uint256, reverting onoverflow (when the input is greater than largest uint104). Counterpart to Solidity's `uint104` operator. Requirements: - input must fit into 104 bits _Available since v4.7._ /
function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); }
function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); }
16,223
54
// Returns the last vesting schedule for a given holder address./
function getLastVestingScheduleForHolder(address holder) public view
function getLastVestingScheduleForHolder(address holder) public view
27,156
161
// If it is a normal user and not smart contract, then the requirement will pass If it is a smart contract, then make sure that it is not on our greyList.
if (rewardPayout) { IERC20(rt).safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, rt, reward); } else {
if (rewardPayout) { IERC20(rt).safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, rt, reward); } else {
24,945
81
// Starts the change for waitPeriod/_id Id of contract/_newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); }
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); }
24,549
18
// 10. Update the total debt /
_currentTotalDebt += _interest;
_currentTotalDebt += _interest;
16,365
28
// The minimum goal to reach. If the goal is not reached, finishing/ the sale will enable refunds.
uint256 public goal;
uint256 public goal;
38,425
8
// Gift tokens for contract owner to distribute, verify with whitelist.
function giftMint(address[] calldata receivers) external onlyOwner { require(totalSupply() + receivers.length <= giftNFT, "MAX_GIFTS"); require(numGifted + receivers.length <= giftNFT, "GIFTS_EMPTY"); for (uint256 i = 0; i < receivers.length; i++) { numGifted++; _safeMint(receivers[i], totalSupply() + 1); } }
function giftMint(address[] calldata receivers) external onlyOwner { require(totalSupply() + receivers.length <= giftNFT, "MAX_GIFTS"); require(numGifted + receivers.length <= giftNFT, "GIFTS_EMPTY"); for (uint256 i = 0; i < receivers.length; i++) { numGifted++; _safeMint(receivers[i], totalSupply() + 1); } }
20,454
45
// (0- Activity, 6- Parallel Multi-Instance)
uint cInst = IFlow(cFlow).getInstanceCount(eInd); while(cInst-- > 0) createInstance(eInd, pCase); pState[1] |= (1 << eInd);
uint cInst = IFlow(cFlow).getInstanceCount(eInd); while(cInst-- > 0) createInstance(eInd, pCase); pState[1] |= (1 << eInd);
22,753
76
// register interfaces
ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
13,231
4
// Given the index of a marketplace listing, calculates the difference between the listed price and the token's fair value.The returned value is scaled by 10000 to represent a percentage with 2 decimal places.Fair value is defined as [oracle price + (remaining rewards / number of tokens in position)]._index Index of the marketplace listing. return (bool, uint256) Whether the price is above fair value, and the % difference between listed price and fair value./
function calculatePriceDifference(uint256 _index) external view returns (bool, uint256);
function calculatePriceDifference(uint256 _index) external view returns (bool, uint256);
51,306
1
// Emit an event whenever an order is successfully fulfilled.orderHash The hash of the fulfilled order. offerer The offerer of the fulfilled order. zoneThe zone of the fulfilled order. recipient The recipient of each spent item on the fulfilled order, or the null address if there is no specific fulfiller (i.e. the order is part of a group of orders). Defaults to the caller unless explicitly specified otherwise by the fulfiller. offer The offer items spent as part of the order. consideration The consideration items received as part of the order along with the recipients of each item. /
event OrderFulfilled( bytes32 orderHash, address indexed offerer, address indexed zone, address recipient, SpentItem[] offer, ReceivedItem[] consideration );
event OrderFulfilled( bytes32 orderHash, address indexed offerer, address indexed zone, address recipient, SpentItem[] offer, ReceivedItem[] consideration );
32,619
27
// claim any pending rewards from this pool, from msg.sender
function claimReward(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : user.amount, rewardDebt : user.amount.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); }
function claimReward(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; IFateRewardController.UserInfo memory user = _getUserInfo(_pid, msg.sender); updatePool(_pid); uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt); _safeFateTransfer(msg.sender, pending); emit ClaimRewards(msg.sender, _pid, pending); _userInfo[_pid][msg.sender] = UserInfoV2({ amount : user.amount, rewardDebt : user.amount.mul(pool.accumulatedFatePerShare).div(1e12), isUpdated : true }); }
37,531
321
// Safe hbt transfer function, just in case if rounding error causes pool to not have enough HBTs.
function safeHbtTransfer(address _to, uint256 _amount) internal { uint256 hbtBal = hbt.balanceOf(address(this)); if (_amount > hbtBal) { hbt.transfer(_to, hbtBal); } else { hbt.transfer(_to, _amount); } // hbt.transfer(_to, _amount); }
function safeHbtTransfer(address _to, uint256 _amount) internal { uint256 hbtBal = hbt.balanceOf(address(this)); if (_amount > hbtBal) { hbt.transfer(_to, hbtBal); } else { hbt.transfer(_to, _amount); } // hbt.transfer(_to, _amount); }
44,069
18
// Executes before swap hook. Requirements:- Contract is not stopped.- Swapping has started.- Swapping hasn't ended.- Gas price doesn't exceed the limit (if set). /
function _beforeSwap() internal view { require(!_stopped, 'Exchange: swapping is stopped'); require(block.timestamp >= _xfiToken.vestingStart(), 'Exchange: swapping has not started'); require(block.timestamp <= _xfiToken.vestingEnd(), 'Exchange: swapping has ended'); if (_maxGasPrice > 0) { require(tx.gasprice <= _maxGasPrice, 'Exchange: gas price exceeds the limit'); } }
function _beforeSwap() internal view { require(!_stopped, 'Exchange: swapping is stopped'); require(block.timestamp >= _xfiToken.vestingStart(), 'Exchange: swapping has not started'); require(block.timestamp <= _xfiToken.vestingEnd(), 'Exchange: swapping has ended'); if (_maxGasPrice > 0) { require(tx.gasprice <= _maxGasPrice, 'Exchange: gas price exceeds the limit'); } }
47,157
23
// Filling in the flight initial data
flights[key] = Flight ({ flightNumber: flight, isRegistered: true, landed: false, statusCode: 0, updatedTimestamp: timestamp, airline: msg.sender });
flights[key] = Flight ({ flightNumber: flight, isRegistered: true, landed: false, statusCode: 0, updatedTimestamp: timestamp, airline: msg.sender });
51,338
40
// Nonce is the same thing as a &39;check number&39; EIP 712
function getLavaTypedDataHash( address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce) public constant returns (bytes32)
function getLavaTypedDataHash( address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce) public constant returns (bytes32)
46,477
0
// pragma solidity ^0.4.23; /
contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); }
contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); }
20,226
9
// ======= External Functions ======= //Executes the OTC deal. Sends the USDC from the beneficiary to Index Governance, andlocks the INDEX in the vesting contract. Can only be called once. /
function swap() external onlyOnce { require(IERC20(index).balanceOf(address(this)) >= indexAmount, "insufficient INDEX"); // Transfer expected USDC from beneficiary IERC20(usdc).safeTransferFrom(beneficiary, address(this), usdcAmount); // Create Vesting contract Vesting vesting = new Vesting(index, beneficiary, indexAmount, vestingStart, vestingCliff, vestingEnd); // Transfer index to vesting contract IERC20(index).safeTransfer(address(vesting), indexAmount); // Transfer USDC to index governance IERC20(usdc).safeTransfer(indexGov, usdcAmount); emit VestingDeployed(address(vesting)); }
function swap() external onlyOnce { require(IERC20(index).balanceOf(address(this)) >= indexAmount, "insufficient INDEX"); // Transfer expected USDC from beneficiary IERC20(usdc).safeTransferFrom(beneficiary, address(this), usdcAmount); // Create Vesting contract Vesting vesting = new Vesting(index, beneficiary, indexAmount, vestingStart, vestingCliff, vestingEnd); // Transfer index to vesting contract IERC20(index).safeTransfer(address(vesting), indexAmount); // Transfer USDC to index governance IERC20(usdc).safeTransfer(indexGov, usdcAmount); emit VestingDeployed(address(vesting)); }
40,582
11
// Triggered whenever tokens are destroyed
event Burn(address indexed from, uint256 value);
event Burn(address indexed from, uint256 value);
39,054
36
// returns the effective reserve tokens weights return reserve1 weight return reserve2 weight/
function effectiveReserveWeights() public view returns (uint256, uint256) { Fraction memory rate = _effectiveTokensRate(); (uint32 primaryReserveWeight, uint32 secondaryReserveWeight) = effectiveReserveWeights(rate); if (primaryReserveToken == reserveTokens[0]) { return (primaryReserveWeight, secondaryReserveWeight); } return (secondaryReserveWeight, primaryReserveWeight); }
function effectiveReserveWeights() public view returns (uint256, uint256) { Fraction memory rate = _effectiveTokensRate(); (uint32 primaryReserveWeight, uint32 secondaryReserveWeight) = effectiveReserveWeights(rate); if (primaryReserveToken == reserveTokens[0]) { return (primaryReserveWeight, secondaryReserveWeight); } return (secondaryReserveWeight, primaryReserveWeight); }
49,972
36
// Are the tokens non-transferrable?
bool public locked = true;
bool public locked = true;
11,657
132
// underlying token decimals return : decimals of underlying token /
function tokenDecimals() external view returns (uint256 decimals);
function tokenDecimals() external view returns (uint256 decimals);
35,838
74
// DAIPoints token contractLiorRabin/
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
contract DAIPointsToken is ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, Ownable { using SafeMath for uint256; uint256 public DAI_TO_DAIPOINTS_CONVERSION_RATE = 100; IERC20 public DAI; constructor (address _dai) public ERC20Detailed('DAIPoints', 'DAIp', 18) { setDAI(_dai); } /** * @dev Function to be called by owner only to set the DAI token address * @param _address DAI token address */ function setDAI(address _address) public onlyOwner { require(_address != address(0) && Address.isContract(_address)); DAI = IERC20(_address); } /** * @dev Function to be called by owner only to set the DAI to DAIPoints conversion rate * @param _rate amount of DAIPoints equal to 1 DAI */ function setConversionRate(uint256 _rate) public onlyOwner { require(_rate > 0); DAI_TO_DAIPOINTS_CONVERSION_RATE = _rate; } /** * @dev Get DAIPoints (minted) in exchange for DAI, according to the conversion rate * @param _amount amount (in wei) of DAI to be transferred from msg.sender balance to this contract's balance */ function getDAIPoints(uint256 _amount) public { require(DAI.transferFrom(msg.sender, address(this), _amount)); _mint(msg.sender, _amount.mul(DAI_TO_DAIPOINTS_CONVERSION_RATE)); } /** * @dev Get DAI in exchange for DAIPoints (burned), according to the conversion rate * @param _amount amount (in wei) of DAIPoints to be deducted from msg.sender balance */ function getDAI(uint256 _amount) public { _burn(msg.sender, _amount); require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), msg.sender, _amount.div(DAI_TO_DAIPOINTS_CONVERSION_RATE))); } /** * @dev Function to be called by owner only to transfer DAI (without exchange to DAIPoints) * @param _to address to transfer DAI from this contract * @param _amount amount (in wei) of DAI to be transferred from this contract */ function moveDAI(address _to, uint256 _amount) public onlyOwner { require(DAI.approve(address(this), _amount)); require(DAI.transferFrom(address(this), _to, _amount)); } }
22,651
3
// Function to deposit funds into the donation pool/One address can deposit in batch for multiple grantIds
function depositFunds( uint256[] calldata _grantIds, uint256[] calldata _depositFunds, uint256 _cumulativeTotal, address _token
function depositFunds( uint256[] calldata _grantIds, uint256[] calldata _depositFunds, uint256 _cumulativeTotal, address _token
24,180
406
// swap protocol funds on AMM, only for authorized
function authorizedSwapT4ExactT( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens
function authorizedSwapT4ExactT( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens
47,624
108
// get item
Item storage item = items[_user][_id];
Item storage item = items[_user][_id];
6,221
272
// Similar to the rawCollateral in PositionData, this value should not be used directly. _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
FixedPoint.Unsigned public rawTotalPositionCollateral;
5,386
13
// Function to announce Announcements. Announcements can be for instance for dividend sharing, voting, orjust for general announcements. Instead of storing the announcement details, we just broadcast them as anevent, and store only the address.announcement Address of the Announcement /
function announce(Announcement announcement) external onlyRole(ROLE_ANNOUNCE) { announcements.push(announcement); announcementsByAddress[address(announcement)] = announcements.length; Announced(address(announcement), announcement.announcementType(), announcement.announcementName(), announcement.announcementURI(), announcement.announcementHash()); }
function announce(Announcement announcement) external onlyRole(ROLE_ANNOUNCE) { announcements.push(announcement); announcementsByAddress[address(announcement)] = announcements.length; Announced(address(announcement), announcement.announcementType(), announcement.announcementName(), announcement.announcementURI(), announcement.announcementHash()); }
1,344
30
// first 32 bytes, after the length prefix.
r := mload(add(sig, 32))
r := mload(add(sig, 32))
10,239
12
// SEND MESSAGE
function sendMessage(address friend_key, string calldata _msg) external { require(checkUserExists(msg.sender), "Create an account first"); require(checkUserExists(friend_key), "User is not registered"); require(checkAlreadyFriends(msg.sender, friend_key), "You are not friend with the given user"); bytes32 chatCode = _getChatCode(msg.sender, friend_key); message memory newMsg = message(msg.sender, block.timestamp, _msg); allMessages[chatCode].push(newMsg); }
function sendMessage(address friend_key, string calldata _msg) external { require(checkUserExists(msg.sender), "Create an account first"); require(checkUserExists(friend_key), "User is not registered"); require(checkAlreadyFriends(msg.sender, friend_key), "You are not friend with the given user"); bytes32 chatCode = _getChatCode(msg.sender, friend_key); message memory newMsg = message(msg.sender, block.timestamp, _msg); allMessages[chatCode].push(newMsg); }
4,178
143
// TLSNotary proof for URLs
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); uint256 call_price = oraclize_getPrice("URL", config_gas_limit) * 2; //2 calls oraclize_setProof(proofType_Ledger); call_price = call_price.add(oraclize_getPrice("Random", config_random_gas_limit)); //1 call oraclize_setProof(proofType_NONE); return call_price.add(oraclize_getPrice("URL", config_rolling_gas_limit)); //1 call
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); uint256 call_price = oraclize_getPrice("URL", config_gas_limit) * 2; //2 calls oraclize_setProof(proofType_Ledger); call_price = call_price.add(oraclize_getPrice("Random", config_random_gas_limit)); //1 call oraclize_setProof(proofType_NONE); return call_price.add(oraclize_getPrice("URL", config_rolling_gas_limit)); //1 call
19,075
47
// for Emergency stop of the sale
function emergencyStop() external onlyOwner _contractUp { require(!ifEmergencyStop); ifEmergencyStop = true; emit SaleStopped(msg.sender, now); }
function emergencyStop() external onlyOwner _contractUp { require(!ifEmergencyStop); ifEmergencyStop = true; emit SaleStopped(msg.sender, now); }
630
42
// can only withdraw the receivable of the msg.sender
function withdrawNative(uint8 _type, address _owner, address payable _to, uint _amount) external; function withdrawZRO(address _to, uint _amount) external;
function withdrawNative(uint8 _type, address _owner, address payable _to, uint _amount) external; function withdrawZRO(address _to, uint _amount) external;
74,443
12
// solhint-disable-next-line
if (block.timestamp < tokenRequests[msg.sender] + minPeriod) {
if (block.timestamp < tokenRequests[msg.sender] + minPeriod) {
19,763
124
// Creates clone of TokensFarm smart contract
address clone = Clones.clone(farmImplementation);
address clone = Clones.clone(farmImplementation);
50,492
44
// tokenOut should match the "swap to" token
require(pool.getToken(params.tokenIndexTo) == IERC20(tokenOut), "!tokenOut");
require(pool.getToken(params.tokenIndexTo) == IERC20(tokenOut), "!tokenOut");
16,595
16
// Verify leaf using openzeppelin library
return MerkleProof.verify(merkleProof, PresaleMerkleRoot, leafHash);
return MerkleProof.verify(merkleProof, PresaleMerkleRoot, leafHash);
67,270
198
// Add blacklist for robot
function banUser(uint256 _pid, address _user) public onlyOwner{ UserInfo storage user = userInfo[_pid][_user]; user.isBaned = true; }
function banUser(uint256 _pid, address _user) public onlyOwner{ UserInfo storage user = userInfo[_pid][_user]; user.isBaned = true; }
40,897
503
// if we reached this point, we can transfer
core.transferToUser(_reserve, msg.sender, _amount); emit Borrow( _reserve, msg.sender, _amount, _interestRateMode, vars.finalUserBorrowRate, vars.borrowFee, vars.borrowBalanceIncrease,
core.transferToUser(_reserve, msg.sender, _amount); emit Borrow( _reserve, msg.sender, _amount, _interestRateMode, vars.finalUserBorrowRate, vars.borrowFee, vars.borrowBalanceIncrease,
56,112
457
// Creating new votes
function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId);
function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId);
50,177
156
// Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
37,819
3
// Estimates the price of a VRF request with a specific gas limit and gas price.This is a convenience function that can be called in simulation to better understand pricing._callbackGasLimit is the gas limit used to estimate the price. _requestGasPriceWei is the gas price in wei used for the estimation. /
function estimateRequestPrice(uint32 _callbackGasLimit, uint256 _requestGasPriceWei) external view returns (uint256);
function estimateRequestPrice(uint32 _callbackGasLimit, uint256 _requestGasPriceWei) external view returns (uint256);
24,732
52
// Store dispute
disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0, // no related dispute, DisputeType.QueryDispute ); emit QueryDisputeCreated( disputeID,
disputes[disputeID] = Dispute( indexer, _fisherman, _deposit, 0, // no related dispute, DisputeType.QueryDispute ); emit QueryDisputeCreated( disputeID,
42,761
41
// send the amount to the target account
safetyWallet.transfer(_amount);
safetyWallet.transfer(_amount);
29,934
138
// price is increasing
IUtilizationFarm(getModule("UFB")).stake(_user, _newPrice.sub(originalPrice));
IUtilizationFarm(getModule("UFB")).stake(_user, _newPrice.sub(originalPrice));
4,807
105
// See {IERC721-approve}. /
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId);
function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId);
76,319
60
// emitted if this contract successfully posts a capped-to-max price to the money market/
event CappedPricePosted(address asset, uint requestedPriceMantissa, uint anchorPriceMantissa, uint cappedPriceMantissa);
event CappedPricePosted(address asset, uint requestedPriceMantissa, uint anchorPriceMantissa, uint cappedPriceMantissa);
19,393
34
// how many USD cents for 110^18 token /
uint public price = 210;
uint public price = 210;
80,168
4
// Transfers counter
mapping(address => uint256) public nonces;
mapping(address => uint256) public nonces;
59,816
154
// returns picked assets from potential assets and final seed/_potentialAssets array of all potential assets encoded in bytes32/_randomHashIds selected random hash ids from our contract/_timestamp timestamp of image creation/_iterations number of iterations to get to final seed
function getPickedAssetsAndFinalSeed(bytes32[] _potentialAssets, uint[] _randomHashIds, uint _timestamp, uint _iterations) internal view returns(uint[], uint) { uint finalSeed = uint(functions.getFinalSeed(functions.calculateSeed(_randomHashIds, _timestamp), _iterations)); require(!seedExists[finalSeed]); return (functions.pickRandomAssets(finalSeed, _potentialAssets), finalSeed); }
function getPickedAssetsAndFinalSeed(bytes32[] _potentialAssets, uint[] _randomHashIds, uint _timestamp, uint _iterations) internal view returns(uint[], uint) { uint finalSeed = uint(functions.getFinalSeed(functions.calculateSeed(_randomHashIds, _timestamp), _iterations)); require(!seedExists[finalSeed]); return (functions.pickRandomAssets(finalSeed, _potentialAssets), finalSeed); }
74,129
25
// The bitwords address, where all the 30% cut is received ETH
address public bitwordsWithdrawlAddress;
address public bitwordsWithdrawlAddress;
50,585
41
// function signature of "postProcess()"
bytes4 public constant POSTPROCESS_SIG = 0xc2722916;
bytes4 public constant POSTPROCESS_SIG = 0xc2722916;
15,347
61
// save space, limits us to 2^24 tokens per user (~17m)
uint24[] indices; uint public burnCount;
uint24[] indices; uint public burnCount;
79,885
264
// Last node key was larger than the key remainder. We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
uint8 branchKey = uint8(lastNodeKey[0]);
71,652
10
// A record of vote checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) checkpoints;
mapping (address => mapping (uint32 => Checkpoint)) checkpoints;
46,694
6
// Because last_price expressed in wei we dont need mul(1e18)but still need div(1e4) - see comment above near A and B declarationuint256 _price = last_price.mul(A_bagsCount).div(10(4_bagsCount));
return bagPrice;
return bagPrice;
48,985
52
// Restore consideration data pointer at the consideration head ptr.
mstore(considerationHeadPtr, considerationDataPtr)
mstore(considerationHeadPtr, considerationDataPtr)
20,227
114
// return The total supply in shares /
function totalShares() external view returns (uint256) { return _totalShares; }
function totalShares() external view returns (uint256) { return _totalShares; }
8,574
34
// I_minter. /
contract I_minter { event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventBankrupt(); function Leverage() constant returns (uint128) {} function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) {} function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) {} function PriceReturn(uint _TransID,uint128 _Price) {} function NewStatic() external payable returns (uint _TransID) {} function NewStaticAdr(address _Risk) external payable returns (uint _TransID) {} function NewRisk() external payable returns (uint _TransID) {} function NewRiskAdr(address _Risk) external payable returns (uint _TransID) {} function RetRisk(uint128 _Quantity) external payable returns (uint _TransID) {} function RetStatic(uint128 _Quantity) external payable returns (uint _TransID) {} function Strike() constant returns (uint128) {} }
contract I_minter { event EventCreateStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemStatic(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventCreateRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventRedeemRisk(address indexed _from, uint128 _value, uint _transactionID, uint _Price); event EventBankrupt(); function Leverage() constant returns (uint128) {} function RiskPrice(uint128 _currentPrice,uint128 _StaticTotal,uint128 _RiskTotal, uint128 _ETHTotal) constant returns (uint128 price) {} function RiskPrice(uint128 _currentPrice) constant returns (uint128 price) {} function PriceReturn(uint _TransID,uint128 _Price) {} function NewStatic() external payable returns (uint _TransID) {} function NewStaticAdr(address _Risk) external payable returns (uint _TransID) {} function NewRisk() external payable returns (uint _TransID) {} function NewRiskAdr(address _Risk) external payable returns (uint _TransID) {} function RetRisk(uint128 _Quantity) external payable returns (uint _TransID) {} function RetStatic(uint128 _Quantity) external payable returns (uint _TransID) {} function Strike() constant returns (uint128) {} }
50,285
80
// Option must have Matured, which means it's filled, unexercised, and has passed its Maturation time.
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Matured); bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation); address seller = optionData[optionHash].seller;
require(getOptionState(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation) == optionStates.Matured); bytes32 optionHash = getOptionHash(assetLocked_assetTraded_firstMaker, amountLocked_amountTraded_maturation); address seller = optionData[optionHash].seller;
12,482
3
// /
function transferTo(address _to) public onlyOwner returns (bool) { require(_to != address(0)); owner = _to; return true; }
function transferTo(address _to) public onlyOwner returns (bool) { require(_to != address(0)); owner = _to; return true; }
940
1
// get current contract
function getContract() public view returns (address){ return CONTRACT; }
function getContract() public view returns (address){ return CONTRACT; }
9,048
19
// Returns the beneficiary to receive a portion interest rate for the protocol.
function reserveBeneficiary() external view returns (address);
function reserveBeneficiary() external view returns (address);
38,908
176
// Returns the multiplication of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow. /
function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; }
2,306
229
// https:docs.peri.finance/contracts/source/contracts/exchangerates
contract ExchangeRates is Owned, MixinSystemSettings, IExchangeRates { using SafeMath for uint; using SafeDecimalMath for uint; // Exchange rates and update times stored by currency code, e.g. 'PERI', or 'pUSD' mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; address public externalRateAggregator; mapping(bytes32 => bool) public currencyByExternal; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorV2V3Interface) public aggregators; mapping(bytes32 => uint8) public currencyKeyDecimals; // List of aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint private constant ORACLE_FUTURE_LIMIT = 10 minutes; mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; mapping(bytes32 => uint) public currentRoundForRate; mapping(bytes32 => uint) public roundFrozen; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; // // ========== CONSTRUCTOR ========== constructor( address _owner, address _oracle, address _resolver, bytes32[] memory _currencyKeys, uint[] memory _newRates ) public Owned(_owner) MixinSystemSettings(_resolver) { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The pUSD rate is always 1 and is never stale. _setRate("pUSD", SafeDecimalMath.unit(), now); internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setExternalRateAggregator(address _aggregator) external onlyOwner { externalRateAggregator = _aggregator; } function setCurrencyToExternalAggregator(bytes32 _currencyKey, bool _set) external onlyOwner { currencyByExternal[_currencyKey] = _set; } /* ========== MUTATIVE FUNCTIONS ========== */ function updateRates( bytes32[] calldata currencyKeys, uint[] calldata newRates, uint timeSent ) external onlyOracle returns (bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function deleteRate(bytes32 currencyKey) external onlyOracle { require(_getRate(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey][currentRoundForRate[currencyKey]]; currentRoundForRate[currencyKey]--; emit RateDeleted(currencyKey); } function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { // 0 < lowerLimit < entryPoint => 0 < entryPoint require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); } else { // unfreeze if need be inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; // remove any tracking roundFrozen[currencyKey] = 0; } // SIP-78 uint rate = _getRate(currencyKey); if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); delete inversePricing[currencyKey]; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress); // This check tries to make sure that a valid aggregator is being added. // It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function. require(aggregator.latestRound() >= 0, "Given Aggregator is invalid"); uint8 decimals = aggregator.decimals(); require(decimals <= 18, "Aggregator decimals should be lower or equal to 18"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; currencyKeyDecimals[currencyKey] = decimals; emit AggregatorAdded(currencyKey, address(aggregator)); } function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = address(aggregators[currencyKey]); require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; delete currencyKeyDecimals[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } // SIP-75 Public keeper function to freeze a pynth that is out of bounds function freezeRate(bytes32 currencyKey) external { InversePricing storage inverse = inversePricing[currencyKey]; require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate"); require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen"); uint rate = _getRate(currencyKey); if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) { inverse.frozenAtUpperLimit = (rate == inverse.upperLimit); inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit); uint currentRoundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = currentRoundId; emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender); } else { revert("Rate within bounds"); } } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_EXCHANGER; addresses = combineArrays(existingAddresses, newAddresses); } // SIP-75 View to determine if freezeRate can be called safely function canFreezeRate(bytes32 currencyKey) external view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) { return false; } else { uint rate = _getRate(currencyKey); return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)); } } function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) { uint count = 0; currencies = new bytes32[](aggregatorKeys.length); for (uint i = 0; i < aggregatorKeys.length; i++) { bytes32 currencyKey = aggregatorKeys[i]; if (address(aggregators[currencyKey]) == aggregator) { currencies[count++] = currencyKey; } } } function rateStalePeriod() external view returns (uint) { return getRateStalePeriod(); } function aggregatorWarningFlags() external view returns (address) { return getAggregatorWarningFlags(); } function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); return (rateAndTime.rate, rateAndTime.time); } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1); // if there's no new round, then the previous roundId was the latest if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) { return _getCurrentRoundId(currencyKey); } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); if (destRate == 0) { // prevent divide-by 0 error (this can happen when roundIDs jump epochs due // to aggregator upgrades) return 0; } // Calculate the effective value by going from source -> USD -> destination value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate); } function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) { return _getRateAndTimestampAtRound(currencyKey, roundId); } function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) { return _getUpdatedTime(currencyKey); } function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]); } return lastUpdateTimes; } function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value) { (value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ) { return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function rateForCurrency(bytes32 currencyKey) external view returns (uint) { return _getRateAndUpdatedTime(currencyKey).rate; } function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times) { rates = new uint[](numRounds); times = new uint[](numRounds); uint roundId = _getCurrentRoundId(currencyKey); for (uint i = 0; i < numRounds; i++) { // fetch the rate and treat is as current, so inverse limits if frozen will always be applied // regardless of current rate (rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) { // if we hit the last round, then return what we have return (rates, times); } else { roundId--; } } } function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = _getRate(currencyKeys[i]); } return _localRates; } function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); if (currencyKey == "pUSD") { return (rateAndTime.rate, false); } return ( rateAndTime.rate, _rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())) ); } function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid) { rates = new uint[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); // fetch all flags at once bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { // do one lookup of the rate & time to minimize gas RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "pUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } } function rateIsStale(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()); } function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return _rateIsFrozen(currencyKey); } function rateIsInvalid(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function rateIsFlagged(bytes32 currencyKey) external view returns (bool) { return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) { return true; } } return false; } /* ========== INTERNAL FUNCTIONS ========== */ function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) { FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags()); // fetch all flags at once if (_flags != FlagsInterface(0)) { address[] memory _aggregators = new address[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _aggregators[i] = address(aggregators[currencyKeys[i]]); } flagList = _flags.getFlags(_aggregators); } else { flagList = new bool[](currencyKeys.length); } } function _setRate( bytes32 currencyKey, uint256 rate, uint256 time ) internal { // Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } function internalUpdateRates( bytes32[] memory currencyKeys, uint[] memory newRates, uint timeSent ) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "pUSD", "Rate of pUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < _getUpdatedTime(currencyKey)) { continue; } // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { // if an inverse mapping exists, adjust the price accordingly InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { // when no inverse is set or when given a 0 rate, return the rate, regardless of the inverse status // (the latter is so when a new inverse is set but the underlying has no rate, it will return 0 as // the rate, not the lowerLimit) return rate; } newRate = rate; // Determine when round was frozen (if any) uint roundWhenRateFrozen = roundFrozen[currencyKey]; // And if we're looking at a rate after frozen, and it's currently frozen, then apply the bounds limit even // if the current price is back within bounds if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; } else if (roundId >= roundWhenRateFrozen && inverse.frozenAtLowerLimit) { newRate = inverse.lowerLimit; } else { // this ensures any rate outside the limit will never be returned uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newRate = 0; } else { newRate = doubleEntryPoint.sub(rate); } // now ensure the rate is between the bounds if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; } else if (newRate <= inverse.lowerLimit) { newRate = inverse.lowerLimit; } } } function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) { require(rate >= 0, "Negative rate not supported"); if (currencyKeyDecimals[currencyKey] > 0) { uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey])); return uint(uint(rate).mul(multiplier)); } return uint(rate); } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); return RateAndUpdatedTime({rate: uint216(rate), time: uint40(time)}); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { // this view from the aggregator is the most gas efficient but it can throw when there's no data, // so let's call it low-level to suppress any reverts bytes memory payload = abi.encodeWithSignature("latestRoundData()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } } else { uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate, roundId)), time: entry.time}); } } function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { return aggregator.latestRound(); } else { return currentRoundForRate[currencyKey]; } } function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { // this view from the aggregator is the most gas efficient but it can throw when there's no data, // so let's call it low-level to suppress any reverts bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt); } } else { RateAndUpdatedTime memory update = _rates[currencyKey][roundId]; return (_rateOrInverted(currencyKey, update.rate, roundId), update.time); } } function _getRate(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).rate; } function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).time; } function _effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view returns ( uint value, uint sourceRate, uint destinationRate ) { sourceRate = _getRate(sourceCurrencyKey); // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) { destinationRate = sourceRate; value = sourceAmount; } else { // Calculate the effective value by going from source -> USD -> destination destinationRate = _getRate(destinationCurrencyKey); // prevent divide-by 0 error (this happens if the dest is not a valid rate) if (destinationRate > 0) { value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate); } } } function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) { // pUSD is a special case and is never stale (check before an SLOAD of getRateAndUpdatedTime) if (currencyKey == "pUSD") return false; return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey)); } function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) { return _time.add(_rateStalePeriod) < now; } function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit; } function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) { // pUSD is a special case and is never invalid if (currencyKey == "pUSD") return false; address aggregator = address(aggregators[currencyKey]); // when no aggregator or when the flags haven't been setup if (aggregator == address(0) || flags == FlagsInterface(0)) { return false; } return flags.getFlag(aggregator); } /* ========== MODIFIERS ========== */ modifier onlyOracle { _onlyOracle(); _; } function _onlyOracle() internal view { require(msg.sender == oracle, "Only the oracle can perform this action"); } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey, uint rate, uint roundId, address initiator); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
contract ExchangeRates is Owned, MixinSystemSettings, IExchangeRates { using SafeMath for uint; using SafeDecimalMath for uint; // Exchange rates and update times stored by currency code, e.g. 'PERI', or 'pUSD' mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; address public externalRateAggregator; mapping(bytes32 => bool) public currencyByExternal; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorV2V3Interface) public aggregators; mapping(bytes32 => uint8) public currencyKeyDecimals; // List of aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint private constant ORACLE_FUTURE_LIMIT = 10 minutes; mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; mapping(bytes32 => uint) public currentRoundForRate; mapping(bytes32 => uint) public roundFrozen; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; // // ========== CONSTRUCTOR ========== constructor( address _owner, address _oracle, address _resolver, bytes32[] memory _currencyKeys, uint[] memory _newRates ) public Owned(_owner) MixinSystemSettings(_resolver) { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The pUSD rate is always 1 and is never stale. _setRate("pUSD", SafeDecimalMath.unit(), now); internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setExternalRateAggregator(address _aggregator) external onlyOwner { externalRateAggregator = _aggregator; } function setCurrencyToExternalAggregator(bytes32 _currencyKey, bool _set) external onlyOwner { currencyByExternal[_currencyKey] = _set; } /* ========== MUTATIVE FUNCTIONS ========== */ function updateRates( bytes32[] calldata currencyKeys, uint[] calldata newRates, uint timeSent ) external onlyOracle returns (bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function deleteRate(bytes32 currencyKey) external onlyOracle { require(_getRate(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey][currentRoundForRate[currencyKey]]; currentRoundForRate[currencyKey]--; emit RateDeleted(currencyKey); } function setInversePricing( bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freezeAtUpperLimit, bool freezeAtLowerLimit ) external onlyOwner { // 0 < lowerLimit < entryPoint => 0 < entryPoint require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits"); InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inverse.entryPoint = entryPoint; inverse.upperLimit = upperLimit; inverse.lowerLimit = lowerLimit; if (freezeAtUpperLimit || freezeAtLowerLimit) { // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade inverse.frozenAtUpperLimit = freezeAtUpperLimit; inverse.frozenAtLowerLimit = freezeAtLowerLimit; uint roundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = roundId; emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender); } else { // unfreeze if need be inverse.frozenAtUpperLimit = false; inverse.frozenAtLowerLimit = false; // remove any tracking roundFrozen[currencyKey] = 0; } // SIP-78 uint rate = _getRate(currencyKey); if (rate > 0) { exchanger().setLastExchangeRateForPynth(currencyKey, rate); } emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); delete inversePricing[currencyKey]; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress); // This check tries to make sure that a valid aggregator is being added. // It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function. require(aggregator.latestRound() >= 0, "Given Aggregator is invalid"); uint8 decimals = aggregator.decimals(); require(decimals <= 18, "Aggregator decimals should be lower or equal to 18"); if (address(aggregators[currencyKey]) == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; currencyKeyDecimals[currencyKey] = decimals; emit AggregatorAdded(currencyKey, address(aggregator)); } function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = address(aggregators[currencyKey]); require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; delete currencyKeyDecimals[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } // SIP-75 Public keeper function to freeze a pynth that is out of bounds function freezeRate(bytes32 currencyKey) external { InversePricing storage inverse = inversePricing[currencyKey]; require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate"); require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen"); uint rate = _getRate(currencyKey); if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) { inverse.frozenAtUpperLimit = (rate == inverse.upperLimit); inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit); uint currentRoundId = _getCurrentRoundId(currencyKey); roundFrozen[currencyKey] = currentRoundId; emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender); } else { revert("Rate within bounds"); } } /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_EXCHANGER; addresses = combineArrays(existingAddresses, newAddresses); } // SIP-75 View to determine if freezeRate can be called safely function canFreezeRate(bytes32 currencyKey) external view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) { return false; } else { uint rate = _getRate(currencyKey); return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)); } } function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) { uint count = 0; currencies = new bytes32[](aggregatorKeys.length); for (uint i = 0; i < aggregatorKeys.length; i++) { bytes32 currencyKey = aggregatorKeys[i]; if (address(aggregators[currencyKey]) == aggregator) { currencies[count++] = currencyKey; } } } function rateStalePeriod() external view returns (uint) { return getRateStalePeriod(); } function aggregatorWarningFlags() external view returns (address) { return getAggregatorWarningFlags(); } function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); return (rateAndTime.rate, rateAndTime.time); } function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint) { uint roundId = startingRoundId; uint nextTimestamp = 0; while (true) { (, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1); // if there's no new round, then the previous roundId was the latest if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) { return roundId; } roundId++; } return roundId; } function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) { return _getCurrentRoundId(currencyKey); } function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; (uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc); (uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest); if (destRate == 0) { // prevent divide-by 0 error (this can happen when roundIDs jump epochs due // to aggregator upgrades) return 0; } // Calculate the effective value by going from source -> USD -> destination value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate); } function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) { return _getRateAndTimestampAtRound(currencyKey, roundId); } function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) { return _getUpdatedTime(currencyKey); } function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]); } return lastUpdateTimes; } function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value) { (value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ) { return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function rateForCurrency(bytes32 currencyKey) external view returns (uint) { return _getRateAndUpdatedTime(currencyKey).rate; } function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times) { rates = new uint[](numRounds); times = new uint[](numRounds); uint roundId = _getCurrentRoundId(currencyKey); for (uint i = 0; i < numRounds; i++) { // fetch the rate and treat is as current, so inverse limits if frozen will always be applied // regardless of current rate (rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) { // if we hit the last round, then return what we have return (rates, times); } else { roundId--; } } } function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = _getRate(currencyKeys[i]); } return _localRates; } function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) { RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey); if (currencyKey == "pUSD") { return (rateAndTime.rate, false); } return ( rateAndTime.rate, _rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())) ); } function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid) { rates = new uint[](currencyKeys.length); uint256 _rateStalePeriod = getRateStalePeriod(); // fetch all flags at once bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { // do one lookup of the rate & time to minimize gas RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]); rates[i] = rateEntry.rate; if (!anyRateInvalid && currencyKeys[i] != "pUSD") { anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time); } } } function rateIsStale(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()); } function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return _rateIsFrozen(currencyKey); } function rateIsInvalid(bytes32 currencyKey) external view returns (bool) { return _rateIsStale(currencyKey, getRateStalePeriod()) || _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function rateIsFlagged(bytes32 currencyKey) external view returns (bool) { return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags())); } function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 _rateStalePeriod = getRateStalePeriod(); bool[] memory flagList = getFlagsForRates(currencyKeys); for (uint i = 0; i < currencyKeys.length; i++) { if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) { return true; } } return false; } /* ========== INTERNAL FUNCTIONS ========== */ function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) { FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags()); // fetch all flags at once if (_flags != FlagsInterface(0)) { address[] memory _aggregators = new address[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _aggregators[i] = address(aggregators[currencyKeys[i]]); } flagList = _flags.getFlags(_aggregators); } else { flagList = new bool[](currencyKeys.length); } } function _setRate( bytes32 currencyKey, uint256 rate, uint256 time ) internal { // Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators currentRoundForRate[currencyKey]++; _rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } function internalUpdateRates( bytes32[] memory currencyKeys, uint[] memory newRates, uint timeSent ) internal returns (bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "pUSD", "Rate of pUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < _getUpdatedTime(currencyKey)) { continue; } // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } function _rateOrInverted( bytes32 currencyKey, uint rate, uint roundId ) internal view returns (uint newRate) { // if an inverse mapping exists, adjust the price accordingly InversePricing memory inverse = inversePricing[currencyKey]; if (inverse.entryPoint == 0 || rate == 0) { // when no inverse is set or when given a 0 rate, return the rate, regardless of the inverse status // (the latter is so when a new inverse is set but the underlying has no rate, it will return 0 as // the rate, not the lowerLimit) return rate; } newRate = rate; // Determine when round was frozen (if any) uint roundWhenRateFrozen = roundFrozen[currencyKey]; // And if we're looking at a rate after frozen, and it's currently frozen, then apply the bounds limit even // if the current price is back within bounds if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) { newRate = inverse.upperLimit; } else if (roundId >= roundWhenRateFrozen && inverse.frozenAtLowerLimit) { newRate = inverse.lowerLimit; } else { // this ensures any rate outside the limit will never be returned uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newRate = 0; } else { newRate = doubleEntryPoint.sub(rate); } // now ensure the rate is between the bounds if (newRate >= inverse.upperLimit) { newRate = inverse.upperLimit; } else if (newRate <= inverse.lowerLimit) { newRate = inverse.lowerLimit; } } } function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) { require(rate >= 0, "Negative rate not supported"); if (currencyKeyDecimals[currencyKey] > 0) { uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey])); return uint(uint(rate).mul(multiplier)); } return uint(rate); } function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) { if (currencyByExternal[currencyKey]) { require(externalRateAggregator != address(0), "External price aggregator is not set yet"); IExternalRateAggregator _externalRateAggregator = IExternalRateAggregator(externalRateAggregator); (uint rate, uint time) = _externalRateAggregator.getRateAndUpdatedTime(currencyKey); return RateAndUpdatedTime({rate: uint216(rate), time: uint40(time)}); } AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { // this view from the aggregator is the most gas efficient but it can throw when there's no data, // so let's call it low-level to suppress any reverts bytes memory payload = abi.encodeWithSignature("latestRoundData()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return RateAndUpdatedTime({ rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)), time: uint40(updatedAt) }); } } else { uint roundId = currentRoundForRate[currencyKey]; RateAndUpdatedTime memory entry = _rates[currencyKey][roundId]; return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate, roundId)), time: entry.time}); } } function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { return aggregator.latestRound(); } else { return currentRoundForRate[currencyKey]; } } function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) { AggregatorV2V3Interface aggregator = aggregators[currencyKey]; if (aggregator != AggregatorV2V3Interface(0)) { // this view from the aggregator is the most gas efficient but it can throw when there's no data, // so let's call it low-level to suppress any reverts bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(aggregator).staticcall(payload); if (success) { (, int256 answer, , uint256 updatedAt, ) = abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt); } } else { RateAndUpdatedTime memory update = _rates[currencyKey][roundId]; return (_rateOrInverted(currencyKey, update.rate, roundId), update.time); } } function _getRate(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).rate; } function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) { return _getRateAndUpdatedTime(currencyKey).time; } function _effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) internal view returns ( uint value, uint sourceRate, uint destinationRate ) { sourceRate = _getRate(sourceCurrencyKey); // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) { destinationRate = sourceRate; value = sourceAmount; } else { // Calculate the effective value by going from source -> USD -> destination destinationRate = _getRate(destinationCurrencyKey); // prevent divide-by 0 error (this happens if the dest is not a valid rate) if (destinationRate > 0) { value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate); } } } function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) { // pUSD is a special case and is never stale (check before an SLOAD of getRateAndUpdatedTime) if (currencyKey == "pUSD") return false; return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey)); } function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) { return _time.add(_rateStalePeriod) < now; } function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) { InversePricing memory inverse = inversePricing[currencyKey]; return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit; } function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) { // pUSD is a special case and is never invalid if (currencyKey == "pUSD") return false; address aggregator = address(aggregators[currencyKey]); // when no aggregator or when the flags haven't been setup if (aggregator == address(0) || flags == FlagsInterface(0)) { return false; } return flags.getFlag(aggregator); } /* ========== MODIFIERS ========== */ modifier onlyOracle { _onlyOracle(); _; } function _onlyOracle() internal view { require(msg.sender == oracle, "Only the oracle can perform this action"); } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey, uint rate, uint roundId, address initiator); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
75,855
100
// The addresses in this array are added by the oracle and these contracts are able to mint frax
address[] public frax_pools_array;
address[] public frax_pools_array;
12,182
172
// Helper to update harvest data
function __updateHarvest( address _rewardToken, address[2] memory _accounts, uint256 _supply
function __updateHarvest( address _rewardToken, address[2] memory _accounts, uint256 _supply
60,757
3
// Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements:- Subtraction cannot underflow. /
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; }
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; }
22,351
114
// This interface defines the ProxyAdmin methods
interface IProxyAdmin { /// @dev Upgrades a proxy to the newest implementation of a contract /// @param proxy Proxy to be upgraded /// @param implementation the address of the Implementation function upgrade(address proxy, address implementation) external; /// @dev Transfers ownership of the contract to a new account (`newOwner`) /// Can only be called by the current owner /// @param newOwner The address of new owner function transferOwnership(address newOwner) external; }
interface IProxyAdmin { /// @dev Upgrades a proxy to the newest implementation of a contract /// @param proxy Proxy to be upgraded /// @param implementation the address of the Implementation function upgrade(address proxy, address implementation) external; /// @dev Transfers ownership of the contract to a new account (`newOwner`) /// Can only be called by the current owner /// @param newOwner The address of new owner function transferOwnership(address newOwner) external; }
14,421
257
// Changes lock CA days - number of days for which tokensare locked while submitting a vote. /
function _changelockCADays(uint _val) internal { lockCADays = _val; }
function _changelockCADays(uint _val) internal { lockCADays = _val; }
28,708
47
// set up address
address _addr = msg.sender;
address _addr = msg.sender;
14,881
129
// give the option to change the router
IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH());
IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH());
39,645
2
// (uint256 batchId, ) = _getBatchId(_tokenId); string memory batchUri = _getBaseURI(_tokenId); if (isEncryptedBatch(batchId)) { return string(abi.encodePacked(batchUri, "0")); } else { return string(abi.encodePacked(batchUri, _tokenId.toString())); } return "hello";
string memory cid = "bafybeiblzu7xvvcepkarrblpduffm54cncr33ndyabcd5vf7ccwhlsrufq"; string memory fancyId = Strings.toString(_tokenId + 1); string memory redeemed = " [REDEEMED]"; string memory nameFancyIdAndRedeemedMaybe; string memory redeemable; bytes memory animationurl; if (isRedeemable(_tokenId)) { redeemable = "true";
string memory cid = "bafybeiblzu7xvvcepkarrblpduffm54cncr33ndyabcd5vf7ccwhlsrufq"; string memory fancyId = Strings.toString(_tokenId + 1); string memory redeemed = " [REDEEMED]"; string memory nameFancyIdAndRedeemedMaybe; string memory redeemable; bytes memory animationurl; if (isRedeemable(_tokenId)) { redeemable = "true";
33,567
6
// require(msg.value == 0, "Don't Send Eth use USDT");
require(_referrer != msg.sender,"You Cannot Refer Yourself"); uint256 tokenToBuy = msg.value / tokenPrice; require(tokenToBuy > 0, "You Must purchase at least one token"); uint256 salePhase = getSalePhase(); SalePhase memory phase = salePhases[salePhase]; uint256 tokenAllocated = tokenToBuy * (100 + phase.vestingPeriod) / 100; uint256 totalPrice = tokenToBuy * phase.price; require(totalTokenSold + tokenToBuy <= totalTokensAllocated, "All tokens have been sold "); require(USDT.balanceOf(msg.sender) >= totalPrice, "Insufficient USDT balance");
require(_referrer != msg.sender,"You Cannot Refer Yourself"); uint256 tokenToBuy = msg.value / tokenPrice; require(tokenToBuy > 0, "You Must purchase at least one token"); uint256 salePhase = getSalePhase(); SalePhase memory phase = salePhases[salePhase]; uint256 tokenAllocated = tokenToBuy * (100 + phase.vestingPeriod) / 100; uint256 totalPrice = tokenToBuy * phase.price; require(totalTokenSold + tokenToBuy <= totalTokensAllocated, "All tokens have been sold "); require(USDT.balanceOf(msg.sender) >= totalPrice, "Insufficient USDT balance");
35,597
148
// Add bettor to bettor list if they are not on it
if (bettorInfo[msg.sender].amountsBet[0] == 0 && bettorInfo[msg.sender].amountsBet[1] == 0) bettors.push(msg.sender);
if (bettorInfo[msg.sender].amountsBet[0] == 0 && bettorInfo[msg.sender].amountsBet[1] == 0) bettors.push(msg.sender);
76,387
413
// Returns the total junior capital depositedreturn The total USDC amount deposited into all junior tranches /
function totalJuniorDeposits() external view override returns (uint256) { uint256 total; for (uint256 i = 0; i < poolSlices.length; i++) { total = total.add(poolSlices[i].juniorTranche.principalDeposited); } return total; }
function totalJuniorDeposits() external view override returns (uint256) { uint256 total; for (uint256 i = 0; i < poolSlices.length; i++) { total = total.add(poolSlices[i].juniorTranche.principalDeposited); } return total; }
83,968
24
// notice that certain conditions must be met with settle_timeout.
modifier settleTimeoutValid(uint64 timeout) { require(timeout >= 6 && timeout <= 2700000); _; }
modifier settleTimeoutValid(uint64 timeout) { require(timeout >= 6 && timeout <= 2700000); _; }
45,134
19
// 获取 ETH/USD 交易对的价格,单位是 1e8
int256 basePrice = chainlinkContract.latestAnswer();
int256 basePrice = chainlinkContract.latestAnswer();
39,504
7
// Mapping for saving all challenges
mapping(uint => challengeInfo) allChallenges;
mapping(uint => challengeInfo) allChallenges;
20,668
18
// [ERC20]Allows _spender to withdraw from your account multiple times, up to the _value amount.If this function is called again it overwrites the current allowance with _value. NOTE: To prevent attack vectors like the one described here and discussed here,clients SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender.THOUGH The contract itself shouldn't enforce it, to allow backwards compatibility with contracts deployed before/
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
5,254
212
// allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults can only be updated by the vault owner _operator operator that the sender wants to give privileges to or revoke them from _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator /
function setOperator(address _operator, bool _isOperator) external { require(operators[msg.sender][_operator] != _isOperator, "C9"); operators[msg.sender][_operator] = _isOperator; emit AccountOperatorUpdated(msg.sender, _operator, _isOperator); }
function setOperator(address _operator, bool _isOperator) external { require(operators[msg.sender][_operator] != _isOperator, "C9"); operators[msg.sender][_operator] = _isOperator; emit AccountOperatorUpdated(msg.sender, _operator, _isOperator); }
34,509
38
// In collateral
function collateralBalance() public view returns (uint256) { if (borrowed_collat_historical >= returned_collat_historical) return borrowed_collat_historical.sub(returned_collat_historical); else return 0; }
function collateralBalance() public view returns (uint256) { if (borrowed_collat_historical >= returned_collat_historical) return borrowed_collat_historical.sub(returned_collat_historical); else return 0; }
36,174
9
// Adds a new admin to the marketplace./newAdmin Address of the new admin to add.
function MEWaddAdmin(address newAdmin) public isAdmin { MEWadmins[newAdmin] = true; }
function MEWaddAdmin(address newAdmin) public isAdmin { MEWadmins[newAdmin] = true; }
22,967
52
// V1 mapping
mapping(address => mapping(uint256 => ERC721ForLend)) public lentERC721List;
mapping(address => mapping(uint256 => ERC721ForLend)) public lentERC721List;
44,853
219
// An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
662
10
// Updates entropy value hash
function _updateEntropy() internal { entropyBase = keccak256( abi.encodePacked( msg.sender, block.timestamp, block.coinbase, block.difficulty, gasleft(), tx.gasprice, metadataBase ) ); }
function _updateEntropy() internal { entropyBase = keccak256( abi.encodePacked( msg.sender, block.timestamp, block.coinbase, block.difficulty, gasleft(), tx.gasprice, metadataBase ) ); }
21,033
94
// Changes the admin of `proxy` to `newAdmin`.Requirements:- This contract must be the current admin of `proxy`. /
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); }
function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); }
7,317
61
// duration after voting, since a proposal has passed during which the proposed action may be executed
uint public constant RESULT_EXECUTION_ALLOWANCE_PERIOD = 3 days;
uint public constant RESULT_EXECUTION_ALLOWANCE_PERIOD = 3 days;
38,455
2
// The SOV token contract.
IERC20_ public SOV;
IERC20_ public SOV;
7,531
5
// Verify Merkle proof (that the leaf belongs to the tree)_proof Merkle proof (the leaf's sibling, and each non-leaf hash that could not otherwise be calculated without additional leaf nodes)_feeDistributorInstance feeDistributor instance address_amountInGwei total CL rewards earned by all validators in GWei (see _validatorCount)/
function verify( bytes32[] calldata _proof, address _feeDistributorInstance, uint256 _amountInGwei ) external view;
function verify( bytes32[] calldata _proof, address _feeDistributorInstance, uint256 _amountInGwei ) external view;
12,261
91
// emit whitelisted event
Whitelisted(participant);
Whitelisted(participant);
83,734
13
// We set the title of our NFT as the generated word.
combinedWord, '", "description": "A highly acclaimed collection of squares.", "image": "data:image/svg+xml;base64,',
combinedWord, '", "description": "A highly acclaimed collection of squares.", "image": "data:image/svg+xml;base64,',
20,760
19
// Checks that the current message sender or caller is the governance address.//
modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; }
modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; }
6,749
37
// update player data in current mini game
if (p.currentMiniGameId == miniGameId) { p.totalJoin = p.totalJoin + 1; } else {
if (p.currentMiniGameId == miniGameId) { p.totalJoin = p.totalJoin + 1; } else {
26,647
4
// Each asset stored in an array of AssetInfo structs, contains all relevant data for an asset
struct AssetInfo { address vaultImplementation; bytes depositVaultInitData; address intermediary; address stakingStrategy; address erc1155Receipt; bytes erc1155ReceiptInitData; address maturedHoldingVault; address depositToken; uint256 maxDuration;
struct AssetInfo { address vaultImplementation; bytes depositVaultInitData; address intermediary; address stakingStrategy; address erc1155Receipt; bytes erc1155ReceiptInitData; address maturedHoldingVault; address depositToken; uint256 maxDuration;
21,605
11
// Unwrap token
function unwrap(uint256 _tokenId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_wrapped[_tokenId], "Token must be wrapped"); _wrapped[_tokenId] = false; }
function unwrap(uint256 _tokenId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_wrapped[_tokenId], "Token must be wrapped"); _wrapped[_tokenId] = false; }
16,197
4
// Defining state variable --dynamic in nature
uint256 public minStake; // minimum value can be stake uint256 public maxStake; // maximum value can be stake uint256 public APY ; // Annual percentage yield of 12% uint public bonus ; // Bonus percentage uint public Claim_Tenure_Time ; address public owner;
uint256 public minStake; // minimum value can be stake uint256 public maxStake; // maximum value can be stake uint256 public APY ; // Annual percentage yield of 12% uint public bonus ; // Bonus percentage uint public Claim_Tenure_Time ; address public owner;
35,445
113
// The configuration from the constructor was moved to the configurationGenericCrowdsale function.team_multisig Address of the multisignature wallet of the team that will receive all the funds contributed in the crowdsale. start Timestamp where the crowdsale will be officially started. It should be greater than the timestamp in which the contract is deployed. end Timestamp where the crowdsale finishes. No tokens can be sold through this contract after this timestamp. configurationGenericCrowdsale can only be called when in State.PendingConfiguration because of the inState modifier. /
function configurationGenericCrowdsale(address team_multisig, uint start, uint end) internal inState(State.PendingConfiguration) { setMultisig(team_multisig);
function configurationGenericCrowdsale(address team_multisig, uint start, uint end) internal inState(State.PendingConfiguration) { setMultisig(team_multisig);
35,319
260
// Sets or upgrades the RariFundController of the RariFundManager. newContract The address of the new RariFundController contract. /
function setFundController(address payable newContract) external onlyOwner { _rariFundControllerContract = newContract; rariFundController = RariFundController(_rariFundControllerContract); emit FundControllerSet(newContract); }
function setFundController(address payable newContract) external onlyOwner { _rariFundControllerContract = newContract; rariFundController = RariFundController(_rariFundControllerContract); emit FundControllerSet(newContract); }
35,773
9
// burn after calculating liquidity because _getLiquidityAmount uses lgeToken.totalSupply to calculate liquidity
ILGEToken(_lgeToken).burn(msg.sender, _amountLGEToken);
ILGEToken(_lgeToken).burn(msg.sender, _amountLGEToken);
38,388