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
|
---|---|---|---|---|
137 | // Returns the information about a position by the position's key/key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper/ return _liquidity The amount of liquidity in the position,/ Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,/ Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,/ Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,/ Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke | function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
| function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
| 14,837 |
167 | // Internal function for updating the length of the reward accounts list._rewardAddressCount new linked list length./ | function _setRewardAddressCount(uint256 _rewardAddressCount) internal {
require(_rewardAddressCount <= MAX_REWARD_ADDRESSES);
uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount;
}
| function _setRewardAddressCount(uint256 _rewardAddressCount) internal {
require(_rewardAddressCount <= MAX_REWARD_ADDRESSES);
uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount;
}
| 2,332 |
16 | // Send Ether to the owner | (bool success, ) = owner.call{value: _payAmount}("");
| (bool success, ) = owner.call{value: _payAmount}("");
| 11,678 |
10 | // For showing number + decimal of tokens (solidity has no decimals so thus, +10 decimals or ten zeros) | function forContractBalance() public view returns (uint256) {
return numberofBUCC;
}
| function forContractBalance() public view returns (uint256) {
return numberofBUCC;
}
| 42,292 |
335 | // Extends the lock of an existing stake | function lockLonger(bytes32 kek_id, uint256 new_ending_ts) nonReentrant updateRewardAndBalanceMdf(msg.sender, true) public {
// Get the stake and its index
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id);
// Check
require(new_ending_ts > block.timestamp, "Must be in the future");
// Calculate some times
uint256 time_left = (thisStake.ending_timestamp > block.timestamp) ? thisStake.ending_timestamp - block.timestamp : 0;
uint256 new_secs = new_ending_ts - block.timestamp;
// Checks
// require(time_left > 0, "Already expired");
require(new_secs > time_left, "Cannot shorten lock time");
require(new_secs >= lock_time_min, "Minimum stake time not met");
require(new_secs <= lock_time_for_max_multiplier, "Trying to lock for too long");
// Update the stake
lockedStakes[msg.sender][theArrayIndex] = LockedStake(
kek_id,
block.timestamp,
thisStake.liquidity,
new_ending_ts,
lockMultiplier(new_secs)
);
// Need to call to update the combined weights
_updateRewardAndBalance(msg.sender, false, true);
emit LockedLonger(msg.sender, kek_id, new_secs, block.timestamp, new_ending_ts);
}
| function lockLonger(bytes32 kek_id, uint256 new_ending_ts) nonReentrant updateRewardAndBalanceMdf(msg.sender, true) public {
// Get the stake and its index
(LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id);
// Check
require(new_ending_ts > block.timestamp, "Must be in the future");
// Calculate some times
uint256 time_left = (thisStake.ending_timestamp > block.timestamp) ? thisStake.ending_timestamp - block.timestamp : 0;
uint256 new_secs = new_ending_ts - block.timestamp;
// Checks
// require(time_left > 0, "Already expired");
require(new_secs > time_left, "Cannot shorten lock time");
require(new_secs >= lock_time_min, "Minimum stake time not met");
require(new_secs <= lock_time_for_max_multiplier, "Trying to lock for too long");
// Update the stake
lockedStakes[msg.sender][theArrayIndex] = LockedStake(
kek_id,
block.timestamp,
thisStake.liquidity,
new_ending_ts,
lockMultiplier(new_secs)
);
// Need to call to update the combined weights
_updateRewardAndBalance(msg.sender, false, true);
emit LockedLonger(msg.sender, kek_id, new_secs, block.timestamp, new_ending_ts);
}
| 17,906 |
17 | // the length of time after the delay has passed that a transaction can be executed | uint256 public constant GRACE_PERIOD = 14 days;
| uint256 public constant GRACE_PERIOD = 14 days;
| 20,710 |
36 | // Pausing is a very serious situation - we revert to sound the alarms | require(!pTokenMintGuardianPaused[pToken], "mint is paused");
| require(!pTokenMintGuardianPaused[pToken], "mint is paused");
| 40,900 |
1 | // Default address to subscribe to for determining blocklisted exchanges | address constant DEFAULT_SUBSCRIPTION =
address(0x511af84166215d528ABf8bA6437ec4BEcF31934B);
address public burnToMintContractAddress =
0x8A04921c61F0f9850A02957530BdbA4aB50312D2;
| address constant DEFAULT_SUBSCRIPTION =
address(0x511af84166215d528ABf8bA6437ec4BEcF31934B);
address public burnToMintContractAddress =
0x8A04921c61F0f9850A02957530BdbA4aB50312D2;
| 16,196 |
20 | // function for users to get their NFT | function makeAnEpicNFT() public {
//get current tokenId
uint256 newItemId = _tokenIds.current();
//require tokenID to be less than 50 (our max mint number)
require(newItemId < 50);
//randomly get one word from each array
string memory first = pickRandomFirstWord(newItemId);
string memory second = pickRandomSecondWord(newItemId);
string memory third = pickRandomThirdWord(newItemId);
string memory combinedWord = string(abi.encodePacked(first, second, third));
//concatenate strings together then close <text> and <svg> tags
string memory finalSvg = string(abi.encodePacked(baseSvg, combinedWord, "</text></svg>"));
console.log("\n----------");
console.log(finalSvg);
console.log("---------\n");
//get all metadata in place and base64 encode it
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',combinedWord,'", "description": "A very cringey and innapropriate collection of words.", "image": "data:image/svg+xml;base64,',Base64.encode(bytes(finalSvg)),'"}'
)
)
)
);
string memory finalTokenUri = string(
abi.encodePacked("data:application/json;base64,", json)
);
console.log("\n--------------------");
console.log(
string(
abi.encodePacked(
"https://nftpreview.0xdev.codes/?code=",
finalTokenUri
)
)
);
console.log("--------------------\n");
//mint the NFT to sender using msg.sender
_safeMint(msg.sender, newItemId);
//set NFT's data
_setTokenURI(newItemId, finalTokenUri);
console.log("An NFT with ID %s has been minted to %s", newItemId, msg.sender);
//increment the counter for next token minted
_tokenIds.increment();
//emit event
emit NewEpicNFTMinted(msg.sender, newItemId);
}
| function makeAnEpicNFT() public {
//get current tokenId
uint256 newItemId = _tokenIds.current();
//require tokenID to be less than 50 (our max mint number)
require(newItemId < 50);
//randomly get one word from each array
string memory first = pickRandomFirstWord(newItemId);
string memory second = pickRandomSecondWord(newItemId);
string memory third = pickRandomThirdWord(newItemId);
string memory combinedWord = string(abi.encodePacked(first, second, third));
//concatenate strings together then close <text> and <svg> tags
string memory finalSvg = string(abi.encodePacked(baseSvg, combinedWord, "</text></svg>"));
console.log("\n----------");
console.log(finalSvg);
console.log("---------\n");
//get all metadata in place and base64 encode it
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',combinedWord,'", "description": "A very cringey and innapropriate collection of words.", "image": "data:image/svg+xml;base64,',Base64.encode(bytes(finalSvg)),'"}'
)
)
)
);
string memory finalTokenUri = string(
abi.encodePacked("data:application/json;base64,", json)
);
console.log("\n--------------------");
console.log(
string(
abi.encodePacked(
"https://nftpreview.0xdev.codes/?code=",
finalTokenUri
)
)
);
console.log("--------------------\n");
//mint the NFT to sender using msg.sender
_safeMint(msg.sender, newItemId);
//set NFT's data
_setTokenURI(newItemId, finalTokenUri);
console.log("An NFT with ID %s has been minted to %s", newItemId, msg.sender);
//increment the counter for next token minted
_tokenIds.increment();
//emit event
emit NewEpicNFTMinted(msg.sender, newItemId);
}
| 24,548 |
161 | // solhint-disable-next-line no-simple-event-func-name | event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
| event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
| 2,603 |
239 | // the average rate is recalculated based on the ratio between the weights of the rates the smaller the weights are, the larger the supported range of each one of the rates is | uint256 private constant EMA_AVERAGE_RATE_WEIGHT = 4;
uint256 private constant EMA_SPOT_RATE_WEIGHT = 1;
| uint256 private constant EMA_AVERAGE_RATE_WEIGHT = 4;
uint256 private constant EMA_SPOT_RATE_WEIGHT = 1;
| 75,523 |
145 | // token addr -> token index | mapping(address => uint256) public rewardTokenAddrToIdx;
| mapping(address => uint256) public rewardTokenAddrToIdx;
| 18,510 |
42 | // Log cancel | emit Cancel(
order.makerAddress,
order.feeRecipientAddress,
order.makerAssetData,
order.takerAssetData,
msg.sender,
orderHash
);
| emit Cancel(
order.makerAddress,
order.feeRecipientAddress,
order.makerAssetData,
order.takerAssetData,
msg.sender,
orderHash
);
| 41,047 |
165 | // Freezes streaming of mAssets / | function freezeStreams() external onlyGovernor whenStreamsNotFrozen {
streamsFrozen = true;
emit StreamsFrozen();
}
| function freezeStreams() external onlyGovernor whenStreamsNotFrozen {
streamsFrozen = true;
emit StreamsFrozen();
}
| 16,954 |
49 | // storing on buy swaping tax amount to swap later on sell | uint public reserveMarketingCollection;
uint public reserveTreseryCollection;
uint public reservePrintingCollection;
| uint public reserveMarketingCollection;
uint public reserveTreseryCollection;
uint public reservePrintingCollection;
| 8,088 |
266 | // ========== EVENTS ==========/ solium-disable / | ) external onlyExchanger {
proxy._emit(
abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
2,
SYNTHEXCHANGE_SIG,
bytes32(account),
0,
0
);
}
| ) external onlyExchanger {
proxy._emit(
abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
2,
SYNTHEXCHANGE_SIG,
bytes32(account),
0,
0
);
}
| 14,448 |
27 | // Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role withconfirmation through the operators contract. _baseOperators BaseOperators contract address. / | function initialize(address _baseOperators) public initializer {
_setOperatorsContract(_baseOperators);
}
| function initialize(address _baseOperators) public initializer {
_setOperatorsContract(_baseOperators);
}
| 11,841 |
158 | // Transfer underlying balance to a specified address. to The address to transfer to. value The amount to be transferred.return True on success, false otherwise. / | function transferUnderlying(address to, uint256 value)
external
validRecipient(to)
returns (bool)
| function transferUnderlying(address to, uint256 value)
external
validRecipient(to)
returns (bool)
| 39,347 |
211 | // Safe ZEUS transfer function, just in case if rounding error causes pool to not have enough ZEUSs. | function safeZEUSTransfer(address _to, uint256 _amount) internal {
uint256 ZEUSBal = zeus.balanceOf(address(this));
if (_amount > ZEUSBal) {
zeus.transfer(_to, ZEUSBal);
} else {
zeus.transfer(_to, _amount);
}
}
| function safeZEUSTransfer(address _to, uint256 _amount) internal {
uint256 ZEUSBal = zeus.balanceOf(address(this));
if (_amount > ZEUSBal) {
zeus.transfer(_to, ZEUSBal);
} else {
zeus.transfer(_to, _amount);
}
}
| 69,578 |
3 | // add exchange in pool (max 10 exchanges by pool) | function updatePoolExchanges(uint8 exchange, uint16 poolId) private {
allPool[poolId-1].exchanges.push(exchange);
}
| function updatePoolExchanges(uint8 exchange, uint16 poolId) private {
allPool[poolId-1].exchanges.push(exchange);
}
| 42,009 |
13 | // Pass all the most important parameters that define the Fundraise All variables cannot be in the constructor because we get "stack too deep" error After deployment setupContract() function needs to be called to set them up. / | constructor(
string memory _label,
address _src20,
address _currencyRegistry,
uint256 _SRC20tokensToMint,
uint256 _startDate,
uint256 _endDate,
uint256 _softCapBCY,
uint256 _hardCapBCY
)
| constructor(
string memory _label,
address _src20,
address _currencyRegistry,
uint256 _SRC20tokensToMint,
uint256 _startDate,
uint256 _endDate,
uint256 _softCapBCY,
uint256 _hardCapBCY
)
| 30,476 |
161 | // Read APIs / | function isMinter(address _minter) external view returns (bool) {
return minters[_minter];
}
| function isMinter(address _minter) external view returns (bool) {
return minters[_minter];
}
| 30,782 |
12 | // add to flips | flips[tokenId] = flips[tokenId].add(1);
| flips[tokenId] = flips[tokenId].add(1);
| 81,598 |
67 | // BLACKLIST | _isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
_blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce));
_isBlackListedBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
_blackListedBots.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345));
_isBlackListedBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
_blackListedBots.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b));
_isBlackListedBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
| _isBlackListedBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
_blackListedBots.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce));
_isBlackListedBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
_blackListedBots.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345));
_isBlackListedBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
_blackListedBots.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b));
_isBlackListedBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
| 18,670 |
0 | // The keyword "public" makes variables accessible from other contracts | address public minter;
mapping (address => uint) public balances;
| address public minter;
mapping (address => uint) public balances;
| 12,621 |
7 | // allow users to call fibonacci library functions | function() public {
// <yes> <report> UNCHECKED_LL_CALLS
require(fibonacciLibrary.delegatecall(msg.data));
}
| function() public {
// <yes> <report> UNCHECKED_LL_CALLS
require(fibonacciLibrary.delegatecall(msg.data));
}
| 16,370 |
25 | // Amount of dividends currently in the Lottery pool | function myDividends() public view returns(uint256) {
return contractCall.myDividends(true);
}
| function myDividends() public view returns(uint256) {
return contractCall.myDividends(true);
}
| 33,595 |
4 | // This is a function of ERC721Enumerable interface / | {
return super.supportsInterface(interfaceId);
}
| {
return super.supportsInterface(interfaceId);
}
| 31,865 |
8 | // initiator reveal pre-image after acceptor commit proof randomID id of this random round iRandom pre-image of initiator / | function initiatorReveal(bytes32 randomID, bytes32 iRandom) public {
Result storage result = resultMap[randomID];
require(result.status == 1, "invalid status");
require(block.number <= result.settleBlock, "reveal block expired");
require(keccak256(abi.encodePacked(iRandom)) == result.iRandomHash, "invalid initiator random");
result.status = 2;
result.random = keccak256(abi.encodePacked(iRandom, result.aRandom));
emit InitiatorReveal(randomID, result.random);
}
| function initiatorReveal(bytes32 randomID, bytes32 iRandom) public {
Result storage result = resultMap[randomID];
require(result.status == 1, "invalid status");
require(block.number <= result.settleBlock, "reveal block expired");
require(keccak256(abi.encodePacked(iRandom)) == result.iRandomHash, "invalid initiator random");
result.status = 2;
result.random = keccak256(abi.encodePacked(iRandom, result.aRandom));
emit InitiatorReveal(randomID, result.random);
}
| 40,467 |
42 | // Repays the full amount for the loan. _poolId The Id of the pool. _ERC20Address The address of the erc20 funds. _bidId The Id of the bid. _lender The lender address. / | function _repayFullAmount(
uint256 _poolId,
address _ERC20Address,
uint256 _bidId,
address _lender
| function _repayFullAmount(
uint256 _poolId,
address _ERC20Address,
uint256 _bidId,
address _lender
| 2,152 |
5 | // accepts batch transfer / | function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
| function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
| 2,018 |
66 | // If compounded deposit is less than a billionth of the initial deposit, return 0. NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less than it's theoretical value. Thus it's unclear whether this line is still really needed./ | if (compoundedStake < initialStake.div(1e9)) {return 0;}
| if (compoundedStake < initialStake.div(1e9)) {return 0;}
| 32,840 |
3 | // verifies that the address is different than this contract address | modifier notThis(address _address) {
require(_address != address(this));
_;
}
| modifier notThis(address _address) {
require(_address != address(this));
_;
}
| 16,497 |
7 | // CORE FUNCTIONS / | function mintToken(address _recipient, uint256 _amount) external;
function changeMintingAddress(address _newAddress) external;
function changeRigoblockAddress(address _newAddress) external;
function balanceOf(address _who) external view returns (uint256);
| function mintToken(address _recipient, uint256 _amount) external;
function changeMintingAddress(address _newAddress) external;
function changeRigoblockAddress(address _newAddress) external;
function balanceOf(address _who) external view returns (uint256);
| 36,869 |
21 | // An event indicating a proposal has been proposedproposer The address that submitted the Proposal proposalAddress The address of the Proposal contract instance that was added / | event Register(address indexed proposer, Proposal indexed proposalAddress);
| event Register(address indexed proposer, Proposal indexed proposalAddress);
| 9,960 |
52 | // Version of signature should be 27 or 28, but 0 and 1 are also possible versions | if (v < 27) {
v += 27;
}
| if (v < 27) {
v += 27;
}
| 44,668 |
81 | // Node registration and management | contract RocketNodeManager is RocketBase, RocketNodeManagerInterface {
// Libraries
using SafeMath for uint256;
// Events
event NodeRegistered(address indexed node, uint256 time);
event NodeTimezoneLocationSet(address indexed node, uint256 time);
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) {
version = 1;
}
// Get the number of nodes in the network
function getNodeCount() override external view returns (uint256) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getCount(keccak256(abi.encodePacked("nodes.index")));
}
// Get a breakdown of the number of nodes per timezone
function getNodeCountPerTimezone(uint256 offset, uint256 limit) override external view returns (TimezoneCount[] memory) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Calculate range
uint256 totalNodes = addressSetStorage.getCount(nodeKey);
uint256 max = offset.add(limit);
if (max > totalNodes || limit == 0) { max = totalNodes; }
// Create an array with as many elements as there are potential values to return
TimezoneCount[] memory counts = new TimezoneCount[](max.sub(offset));
uint256 uniqueTimezoneCount = 0;
// Iterate the minipool range
for (uint256 i = offset; i < max; i++) {
address nodeAddress = addressSetStorage.getItem(nodeKey, i);
string memory timezone = getString(keccak256(abi.encodePacked("node.timezone.location", nodeAddress)));
// Find existing entry in our array
bool existing = false;
for (uint256 j = 0; j < uniqueTimezoneCount; j++) {
if (keccak256(bytes(counts[j].timezone)) == keccak256(bytes(timezone))) {
existing = true;
// Increment the counter
counts[j].count++;
break;
}
}
// Entry was not found, so create a new one
if (!existing) {
counts[uniqueTimezoneCount].timezone = timezone;
counts[uniqueTimezoneCount].count = 1;
uniqueTimezoneCount++;
}
}
// Dirty hack to cut unused elements off end of return value
assembly {
mstore(counts, uniqueTimezoneCount)
}
return counts;
}
// Get a node address by index
function getNodeAt(uint256 _index) override external view returns (address) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getItem(keccak256(abi.encodePacked("nodes.index")), _index);
}
// Check whether a node exists
function getNodeExists(address _nodeAddress) override external view returns (bool) {
return getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress)));
}
// Get a node's current withdrawal address
function getNodeWithdrawalAddress(address _nodeAddress) override external view returns (address) {
return rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
}
// Get a node's pending withdrawal address
function getNodePendingWithdrawalAddress(address _nodeAddress) override external view returns (address) {
return rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress);
}
// Get a node's timezone location
function getNodeTimezoneLocation(address _nodeAddress) override external view returns (string memory) {
return getString(keccak256(abi.encodePacked("node.timezone.location", _nodeAddress)));
}
// Register a new node with Rocket Pool
function registerNode(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) {
// Load contracts
RocketClaimNodeInterface rocketClaimNode = RocketClaimNodeInterface(getContractAddress("rocketClaimNode"));
RocketDAOProtocolSettingsNodeInterface rocketDAOProtocolSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Check node settings
require(rocketDAOProtocolSettingsNode.getRegistrationEnabled(), "Rocket Pool node registrations are currently disabled");
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Initialise node data
setBool(keccak256(abi.encodePacked("node.exists", msg.sender)), true);
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Add node to index
addressSetStorage.addItem(keccak256(abi.encodePacked("nodes.index")), msg.sender);
// Register node for RPL claims
rocketClaimNode.register(msg.sender, true);
// Emit node registered event
emit NodeRegistered(msg.sender, block.timestamp);
}
// Set a node's timezone location
// Only accepts calls from registered nodes
function setTimezoneLocation(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Set timezone location
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Emit node timezone location set event
emit NodeTimezoneLocationSet(msg.sender, block.timestamp);
}
}
| contract RocketNodeManager is RocketBase, RocketNodeManagerInterface {
// Libraries
using SafeMath for uint256;
// Events
event NodeRegistered(address indexed node, uint256 time);
event NodeTimezoneLocationSet(address indexed node, uint256 time);
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) {
version = 1;
}
// Get the number of nodes in the network
function getNodeCount() override external view returns (uint256) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getCount(keccak256(abi.encodePacked("nodes.index")));
}
// Get a breakdown of the number of nodes per timezone
function getNodeCountPerTimezone(uint256 offset, uint256 limit) override external view returns (TimezoneCount[] memory) {
// Get contracts
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Precompute node key
bytes32 nodeKey = keccak256(abi.encodePacked("nodes.index"));
// Calculate range
uint256 totalNodes = addressSetStorage.getCount(nodeKey);
uint256 max = offset.add(limit);
if (max > totalNodes || limit == 0) { max = totalNodes; }
// Create an array with as many elements as there are potential values to return
TimezoneCount[] memory counts = new TimezoneCount[](max.sub(offset));
uint256 uniqueTimezoneCount = 0;
// Iterate the minipool range
for (uint256 i = offset; i < max; i++) {
address nodeAddress = addressSetStorage.getItem(nodeKey, i);
string memory timezone = getString(keccak256(abi.encodePacked("node.timezone.location", nodeAddress)));
// Find existing entry in our array
bool existing = false;
for (uint256 j = 0; j < uniqueTimezoneCount; j++) {
if (keccak256(bytes(counts[j].timezone)) == keccak256(bytes(timezone))) {
existing = true;
// Increment the counter
counts[j].count++;
break;
}
}
// Entry was not found, so create a new one
if (!existing) {
counts[uniqueTimezoneCount].timezone = timezone;
counts[uniqueTimezoneCount].count = 1;
uniqueTimezoneCount++;
}
}
// Dirty hack to cut unused elements off end of return value
assembly {
mstore(counts, uniqueTimezoneCount)
}
return counts;
}
// Get a node address by index
function getNodeAt(uint256 _index) override external view returns (address) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getItem(keccak256(abi.encodePacked("nodes.index")), _index);
}
// Check whether a node exists
function getNodeExists(address _nodeAddress) override external view returns (bool) {
return getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress)));
}
// Get a node's current withdrawal address
function getNodeWithdrawalAddress(address _nodeAddress) override external view returns (address) {
return rocketStorage.getNodeWithdrawalAddress(_nodeAddress);
}
// Get a node's pending withdrawal address
function getNodePendingWithdrawalAddress(address _nodeAddress) override external view returns (address) {
return rocketStorage.getNodePendingWithdrawalAddress(_nodeAddress);
}
// Get a node's timezone location
function getNodeTimezoneLocation(address _nodeAddress) override external view returns (string memory) {
return getString(keccak256(abi.encodePacked("node.timezone.location", _nodeAddress)));
}
// Register a new node with Rocket Pool
function registerNode(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) {
// Load contracts
RocketClaimNodeInterface rocketClaimNode = RocketClaimNodeInterface(getContractAddress("rocketClaimNode"));
RocketDAOProtocolSettingsNodeInterface rocketDAOProtocolSettingsNode = RocketDAOProtocolSettingsNodeInterface(getContractAddress("rocketDAOProtocolSettingsNode"));
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
// Check node settings
require(rocketDAOProtocolSettingsNode.getRegistrationEnabled(), "Rocket Pool node registrations are currently disabled");
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Initialise node data
setBool(keccak256(abi.encodePacked("node.exists", msg.sender)), true);
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Add node to index
addressSetStorage.addItem(keccak256(abi.encodePacked("nodes.index")), msg.sender);
// Register node for RPL claims
rocketClaimNode.register(msg.sender, true);
// Emit node registered event
emit NodeRegistered(msg.sender, block.timestamp);
}
// Set a node's timezone location
// Only accepts calls from registered nodes
function setTimezoneLocation(string calldata _timezoneLocation) override external onlyLatestContract("rocketNodeManager", address(this)) onlyRegisteredNode(msg.sender) {
// Check timezone location
require(bytes(_timezoneLocation).length >= 4, "The timezone location is invalid");
// Set timezone location
setString(keccak256(abi.encodePacked("node.timezone.location", msg.sender)), _timezoneLocation);
// Emit node timezone location set event
emit NodeTimezoneLocationSet(msg.sender, block.timestamp);
}
}
| 30,354 |
34 | // Emitted when cancelWeightUpdates is called./weights Current weights of tokens. | event CancelWeightUpdates(uint256[] weights);
| event CancelWeightUpdates(uint256[] weights);
| 36,688 |
207 | // 4. Collateral >= minimum collateral size. | require(collateral >= minCollateral, "Not enough collateral to open");
| require(collateral >= minCollateral, "Not enough collateral to open");
| 47,808 |
6 | // Overflow is desired, casting never truncates Cumulative price is in (uq112x112 priceseconds) units so we simply wrap it after division by time elapsed | price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
| price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
| 40,075 |
66 | // whitelister "account". This can be done from managers only _investor address address of the investor&39;s wallet / | function whiteListInvestor(address _investor) external onlyManager {
require(_investor != address(0));
isWhitelisted[_investor] = true;
ChangedInvestorWhitelisting(_investor, true);
}
| function whiteListInvestor(address _investor) external onlyManager {
require(_investor != address(0));
isWhitelisted[_investor] = true;
ChangedInvestorWhitelisting(_investor, true);
}
| 33,472 |
185 | // A base contract that may be inherited in order to protect a contract from having its fallback function invoked and to block the receipt of ETH by a contract. Nathan Gang This contract bestows on inheritors the ability to block ETH transfers into the contract ETH may still be forced into the contract - it is impossible to block certain attacks, but this protects from accidental ETH deposits /For more info, see: "https:medium.com/@alexsherbuck/two-ways-to-force-ether-into-a-contract-1543c1311c56" | abstract contract RejectEther {
| abstract contract RejectEther {
| 44,400 |
273 | // Return address of the pooled token at given index. Reverts if tokenIndex is out of range. index the index of the tokenreturn address of the token at given index / | function getToken(uint8 index) public view returns (IERC20) {
require(index < swapStorage.pooledTokens.length, "Out of range");
return swapStorage.pooledTokens[index];
}
| function getToken(uint8 index) public view returns (IERC20) {
require(index < swapStorage.pooledTokens.length, "Out of range");
return swapStorage.pooledTokens[index];
}
| 17,415 |
285 | // The burn fee in bips. | uint16 public burnFee;
| uint16 public burnFee;
| 41,353 |
317 | // Request partnership in the other contract. Open interface on his contract. | PartnershipInterface hisInterface = PartnershipInterface(_hisContract);
bool success = hisInterface._requestPartnership(_ourSymetricKey);
| PartnershipInterface hisInterface = PartnershipInterface(_hisContract);
bool success = hisInterface._requestPartnership(_ourSymetricKey);
| 14,980 |
103 | // @inheritdoc IUniswapV3PoolOwnerActions | function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {
require(
(feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&
(feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))
);
uint8 feeProtocolOld = slot0.feeProtocol;
slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);
emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);
}
| function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {
require(
(feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&
(feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))
);
uint8 feeProtocolOld = slot0.feeProtocol;
slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);
emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);
}
| 50,958 |
21 | // Mint longOptionTokens using the underlyingTokens received from UniswapV2 flash swap to this contract. Send underlyingTokens from this contract to the optionToken contract, then call mintOptions. | (uint256 mintedOptions, uint256 mintedRedeems) =
mintOptionsWithUnderlyingBalance(
IOption(optionAddress),
flashLoanQuantity
);
| (uint256 mintedOptions, uint256 mintedRedeems) =
mintOptionsWithUnderlyingBalance(
IOption(optionAddress),
flashLoanQuantity
);
| 32,037 |
104 | // need to check minimum ether | require(_weiAmount >= minimum_weiAmount);
| require(_weiAmount >= minimum_weiAmount);
| 53,932 |
7 | // Returns the address of the LINK token This is the public implementation for chainlinkTokenAddress, which isan internal method of the ChainlinkClient contract / | function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
| function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
| 18,442 |
269 | // Returns transcoder with most stake in pool / | function getFirstTranscoderInPool() public view returns (address) {
return transcoderPool.getFirst();
}
| function getFirstTranscoderInPool() public view returns (address) {
return transcoderPool.getFirst();
}
| 24,754 |
5 | // if(_ta==0xdAC17F958D2ee523a2206206994597C13D831ec7){ convers=convers/(1012); } | return convers;
| return convers;
| 23,210 |
218 | // uint256 _sushiPerBlock, | uint256 _startBlock
| uint256 _startBlock
| 8,075 |
15 | // See ERC2771 | function _msgSender() internal view virtual override returns (address sender) {
return ERC2771ContextUpgradeable._msgSender();
}
| function _msgSender() internal view virtual override returns (address sender) {
return ERC2771ContextUpgradeable._msgSender();
}
| 10,748 |
11 | // This low-level function should be called from a contract which performs/ important safety checks. | function mint(address to)
external
override
lock
returns (uint256 liquidity)
| function mint(address to)
external
override
lock
returns (uint256 liquidity)
| 4,404 |
82 | // Transfer the token to the specified smart wallet. | _transferToken(token, smartWallet, amount);
| _transferToken(token, smartWallet, amount);
| 41,950 |
190 | // Creates a new NFT. _chosenAmount Amount of tokens to be bougth. / | function mint(
uint256 _chosenAmount
)
external
payable
| function mint(
uint256 _chosenAmount
)
external
payable
| 58,498 |
39 | // Handle asset transfer. | unchecked {
if (locker.token == address(0)) { // Release ETH.
safeTransferETH(locker.depositor, locker.sum - locker.paid);
} else if (locker.bento) { // Release BentoBox shares.
| unchecked {
if (locker.token == address(0)) { // Release ETH.
safeTransferETH(locker.depositor, locker.sum - locker.paid);
} else if (locker.bento) { // Release BentoBox shares.
| 20,639 |
6 | // Without the keyword 'this' it does not compile, once getDouble is an external function | return this.getDouble() + value;
| return this.getDouble() + value;
| 14,734 |
63 | // POOL |
string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0";
string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1";
string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2";
string public constant POOL_INCORRECT_WITHDRAW_FEE = "SP3";
string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4";
|
string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0";
string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1";
string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2";
string public constant POOL_INCORRECT_WITHDRAW_FEE = "SP3";
string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4";
| 6,206 |
20 | // Facade A UX-friendly layer for non-governance protocol interactions@custom:static-call - Use ethers callStatic() in order to get result after update / | contract Facade is IFacade {
using FixLib for uint192;
/// Prompt all traders to run auctions
/// Relatively gas-inefficient, shouldn't be used in production. Use multicall instead
function runAuctionsForAllTraders(IRToken rToken) external {
IMain main = rToken.main();
IBackingManager backingManager = main.backingManager();
IRevenueTrader rsrTrader = main.rsrTrader();
IRevenueTrader rTokenTrader = main.rTokenTrader();
IERC20[] memory erc20s = main.assetRegistry().erc20s();
for (uint256 i = 0; i < erc20s.length; i++) {
// BackingManager
ITrade trade = backingManager.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
backingManager.settleTrade(erc20s[i]);
}
// RSRTrader
trade = rsrTrader.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
rsrTrader.settleTrade(erc20s[i]);
}
// RTokenTrader
trade = rTokenTrader.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
rTokenTrader.settleTrade(erc20s[i]);
}
}
main.backingManager().manageTokens(erc20s);
for (uint256 i = 0; i < erc20s.length; i++) {
rsrTrader.manageToken(erc20s[i]);
rTokenTrader.manageToken(erc20s[i]);
}
}
/// Prompt all traders and the RToken itself to claim rewards and sweep to BackingManager
function claimRewards(IRToken rToken) external {
IMain main = rToken.main();
main.backingManager().claimAndSweepRewards();
main.rsrTrader().claimAndSweepRewards();
main.rTokenTrader().claimAndSweepRewards();
rToken.claimAndSweepRewards();
}
/// @return {qRTok} How many RToken `account` can issue given current holdings
/// @custom:static-call
function maxIssuable(IRToken rToken, address account) external returns (uint256) {
IMain main = rToken.main();
main.poke();
// {BU}
uint192 held = main.basketHandler().basketsHeldBy(account);
uint192 needed = rToken.basketsNeeded();
int8 decimals = int8(rToken.decimals());
// return {qRTok} = {BU} * {(1 RToken) qRTok/BU)}
if (needed.eq(FIX_ZERO)) return held.shiftl_toUint(decimals);
uint192 totalSupply = shiftl_toFix(rToken.totalSupply(), -decimals); // {rTok}
// {qRTok} = {BU} * {rTok} / {BU} * {qRTok/rTok}
return held.mulDiv(totalSupply, needed).shiftl_toUint(decimals);
}
/// @return tokens Array of all known ERC20 asset addreses.
/// @return amounts {qTok} Array of balance that the protocol holds of this current asset
/// @custom:static-call
function currentAssets(IRToken rToken)
external
returns (address[] memory tokens, uint256[] memory amounts)
{
IMain main = rToken.main();
main.poke();
IAssetRegistry reg = main.assetRegistry();
IERC20[] memory erc20s = reg.erc20s();
tokens = new address[](erc20s.length);
amounts = new uint256[](erc20s.length);
for (uint256 i = 0; i < erc20s.length; i++) {
tokens[i] = address(erc20s[i]);
amounts[i] = erc20s[i].balanceOf(address(main.backingManager()));
}
}
/// @return total {UoA} An estimate of the total value of all assets held at BackingManager
/// @custom:static-call
function totalAssetValue(IRToken rToken) external returns (uint192 total) {
IMain main = rToken.main();
main.poke();
IAssetRegistry reg = main.assetRegistry();
address backingManager = address(main.backingManager());
IERC20[] memory erc20s = reg.erc20s();
for (uint256 i = 0; i < erc20s.length; i++) {
IAsset asset = reg.toAsset(erc20s[i]);
// Exclude collateral that has defaulted
if (
asset.isCollateral() &&
ICollateral(address(asset)).status() != CollateralStatus.DISABLED
) {
total = total.plus(asset.bal(backingManager).mul(asset.price()));
}
}
}
/// @custom:static-call
function issue(IRToken rToken, uint256 amount)
external
returns (address[] memory tokens, uint256[] memory deposits)
{
IMain main = rToken.main();
main.poke();
IRToken rTok = rToken;
IBasketHandler bh = main.basketHandler();
// Compute # of baskets to create `amount` qRTok
uint192 baskets = (rTok.totalSupply() > 0) // {BU}
? rTok.basketsNeeded().muluDivu(amount, rTok.totalSupply()) // {BU * qRTok / qRTok}
: shiftl_toFix(amount, -int8(rTok.decimals())); // {qRTok / qRTok}
(tokens, deposits) = bh.quote(baskets, CEIL);
}
/// @return tokens The addresses of the ERC20s backing the RToken
function basketTokens(IRToken rToken) external view returns (address[] memory tokens) {
IMain main = rToken.main();
(tokens, ) = main.basketHandler().quote(FIX_ONE, CEIL);
}
/// @return stTokenAddress The address of the corresponding stToken for the rToken
function stToken(IRToken rToken) external view returns (IStRSR stTokenAddress) {
IMain main = rToken.main();
stTokenAddress = main.stRSR();
}
}
| contract Facade is IFacade {
using FixLib for uint192;
/// Prompt all traders to run auctions
/// Relatively gas-inefficient, shouldn't be used in production. Use multicall instead
function runAuctionsForAllTraders(IRToken rToken) external {
IMain main = rToken.main();
IBackingManager backingManager = main.backingManager();
IRevenueTrader rsrTrader = main.rsrTrader();
IRevenueTrader rTokenTrader = main.rTokenTrader();
IERC20[] memory erc20s = main.assetRegistry().erc20s();
for (uint256 i = 0; i < erc20s.length; i++) {
// BackingManager
ITrade trade = backingManager.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
backingManager.settleTrade(erc20s[i]);
}
// RSRTrader
trade = rsrTrader.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
rsrTrader.settleTrade(erc20s[i]);
}
// RTokenTrader
trade = rTokenTrader.trades(erc20s[i]);
if (address(trade) != address(0) && trade.canSettle()) {
rTokenTrader.settleTrade(erc20s[i]);
}
}
main.backingManager().manageTokens(erc20s);
for (uint256 i = 0; i < erc20s.length; i++) {
rsrTrader.manageToken(erc20s[i]);
rTokenTrader.manageToken(erc20s[i]);
}
}
/// Prompt all traders and the RToken itself to claim rewards and sweep to BackingManager
function claimRewards(IRToken rToken) external {
IMain main = rToken.main();
main.backingManager().claimAndSweepRewards();
main.rsrTrader().claimAndSweepRewards();
main.rTokenTrader().claimAndSweepRewards();
rToken.claimAndSweepRewards();
}
/// @return {qRTok} How many RToken `account` can issue given current holdings
/// @custom:static-call
function maxIssuable(IRToken rToken, address account) external returns (uint256) {
IMain main = rToken.main();
main.poke();
// {BU}
uint192 held = main.basketHandler().basketsHeldBy(account);
uint192 needed = rToken.basketsNeeded();
int8 decimals = int8(rToken.decimals());
// return {qRTok} = {BU} * {(1 RToken) qRTok/BU)}
if (needed.eq(FIX_ZERO)) return held.shiftl_toUint(decimals);
uint192 totalSupply = shiftl_toFix(rToken.totalSupply(), -decimals); // {rTok}
// {qRTok} = {BU} * {rTok} / {BU} * {qRTok/rTok}
return held.mulDiv(totalSupply, needed).shiftl_toUint(decimals);
}
/// @return tokens Array of all known ERC20 asset addreses.
/// @return amounts {qTok} Array of balance that the protocol holds of this current asset
/// @custom:static-call
function currentAssets(IRToken rToken)
external
returns (address[] memory tokens, uint256[] memory amounts)
{
IMain main = rToken.main();
main.poke();
IAssetRegistry reg = main.assetRegistry();
IERC20[] memory erc20s = reg.erc20s();
tokens = new address[](erc20s.length);
amounts = new uint256[](erc20s.length);
for (uint256 i = 0; i < erc20s.length; i++) {
tokens[i] = address(erc20s[i]);
amounts[i] = erc20s[i].balanceOf(address(main.backingManager()));
}
}
/// @return total {UoA} An estimate of the total value of all assets held at BackingManager
/// @custom:static-call
function totalAssetValue(IRToken rToken) external returns (uint192 total) {
IMain main = rToken.main();
main.poke();
IAssetRegistry reg = main.assetRegistry();
address backingManager = address(main.backingManager());
IERC20[] memory erc20s = reg.erc20s();
for (uint256 i = 0; i < erc20s.length; i++) {
IAsset asset = reg.toAsset(erc20s[i]);
// Exclude collateral that has defaulted
if (
asset.isCollateral() &&
ICollateral(address(asset)).status() != CollateralStatus.DISABLED
) {
total = total.plus(asset.bal(backingManager).mul(asset.price()));
}
}
}
/// @custom:static-call
function issue(IRToken rToken, uint256 amount)
external
returns (address[] memory tokens, uint256[] memory deposits)
{
IMain main = rToken.main();
main.poke();
IRToken rTok = rToken;
IBasketHandler bh = main.basketHandler();
// Compute # of baskets to create `amount` qRTok
uint192 baskets = (rTok.totalSupply() > 0) // {BU}
? rTok.basketsNeeded().muluDivu(amount, rTok.totalSupply()) // {BU * qRTok / qRTok}
: shiftl_toFix(amount, -int8(rTok.decimals())); // {qRTok / qRTok}
(tokens, deposits) = bh.quote(baskets, CEIL);
}
/// @return tokens The addresses of the ERC20s backing the RToken
function basketTokens(IRToken rToken) external view returns (address[] memory tokens) {
IMain main = rToken.main();
(tokens, ) = main.basketHandler().quote(FIX_ONE, CEIL);
}
/// @return stTokenAddress The address of the corresponding stToken for the rToken
function stToken(IRToken rToken) external view returns (IStRSR stTokenAddress) {
IMain main = rToken.main();
stTokenAddress = main.stRSR();
}
}
| 9,078 |
145 | // Community commission contract. Collects `_communitySwapFee`, `_communityJoinFee`, `_communityExitFee` for voting in underlying protocols, receiving rewards. | address private _communityFeeReceiver;
| address private _communityFeeReceiver;
| 16,477 |
31 | // this is safe from underflow because `upper` ceiling is provided | uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTimestamp == timestamp) {
return cp.votes;
} else if (cp.fromTimestamp < timestamp) {
| uint256 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromTimestamp == timestamp) {
return cp.votes;
} else if (cp.fromTimestamp < timestamp) {
| 49,777 |
120 | // ERC20Wrapper Set Protocol This library contains functions for interacting wtih ERC20 tokens, even those not fully compliant.For all functions we will only accept tokens that return a null or true value, any other values willcause the operation to revert. / | library ERC20Wrapper {
// ============ Internal Functions ============
/**
* Check balance owner's balance of ERC20 token
*
* @param _token The address of the ERC20 token
* @param _owner The owner who's balance is being checked
* @return uint256 The _owner's amount of tokens
*/
function balanceOf(
address _token,
address _owner
)
external
view
returns (uint256)
{
return IERC20(_token).balanceOf(_owner);
}
/**
* Checks spender's allowance to use token's on owner's behalf.
*
* @param _token The address of the ERC20 token
* @param _owner The token owner address
* @param _spender The address the allowance is being checked on
* @return uint256 The spender's allowance on behalf of owner
*/
function allowance(
address _token,
address _owner,
address _spender
)
internal
view
returns (uint256)
{
return IERC20(_token).allowance(_owner, _spender);
}
/**
* Transfers tokens from an address. Handle's tokens that return true or null.
* If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _to The address to transfer to
* @param _quantity The amount of tokens to transfer
*/
function transfer(
address _token,
address _to,
uint256 _quantity
)
external
{
IERC20(_token).transfer(_to, _quantity);
// Check that transfer returns true or null
require(
checkSuccess(),
"ERC20Wrapper.transfer: Bad return value"
);
}
/**
* Transfers tokens from an address (that has set allowance on the proxy).
* Handle's tokens that return true or null. If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(
address _token,
address _from,
address _to,
uint256 _quantity
)
external
{
IERC20(_token).transferFrom(_from, _to, _quantity);
// Check that transferFrom returns true or null
require(
checkSuccess(),
"ERC20Wrapper.transferFrom: Bad return value"
);
}
/**
* Grants spender ability to spend on owner's behalf.
* Handle's tokens that return true or null. If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _spender The address to approve for transfer
* @param _quantity The amount of tokens to approve spender for
*/
function approve(
address _token,
address _spender,
uint256 _quantity
)
internal
{
IERC20(_token).approve(_spender, _quantity);
// Check that approve returns true or null
require(
checkSuccess(),
"ERC20Wrapper.approve: Bad return value"
);
}
/**
* Ensure's the owner has granted enough allowance for system to
* transfer tokens.
*
* @param _token The address of the ERC20 token
* @param _owner The address of the token owner
* @param _spender The address to grant/check allowance for
* @param _quantity The amount to see if allowed for
*/
function ensureAllowance(
address _token,
address _owner,
address _spender,
uint256 _quantity
)
internal
{
uint256 currentAllowance = allowance(_token, _owner, _spender);
if (currentAllowance < _quantity) {
approve(
_token,
_spender,
CommonMath.maxUInt256()
);
}
}
// ============ Private Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 1.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
// default to failure
uint256 returnValue = 0;
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
// check if returned value is one or nothing
return returnValue == 1;
}
}
| library ERC20Wrapper {
// ============ Internal Functions ============
/**
* Check balance owner's balance of ERC20 token
*
* @param _token The address of the ERC20 token
* @param _owner The owner who's balance is being checked
* @return uint256 The _owner's amount of tokens
*/
function balanceOf(
address _token,
address _owner
)
external
view
returns (uint256)
{
return IERC20(_token).balanceOf(_owner);
}
/**
* Checks spender's allowance to use token's on owner's behalf.
*
* @param _token The address of the ERC20 token
* @param _owner The token owner address
* @param _spender The address the allowance is being checked on
* @return uint256 The spender's allowance on behalf of owner
*/
function allowance(
address _token,
address _owner,
address _spender
)
internal
view
returns (uint256)
{
return IERC20(_token).allowance(_owner, _spender);
}
/**
* Transfers tokens from an address. Handle's tokens that return true or null.
* If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _to The address to transfer to
* @param _quantity The amount of tokens to transfer
*/
function transfer(
address _token,
address _to,
uint256 _quantity
)
external
{
IERC20(_token).transfer(_to, _quantity);
// Check that transfer returns true or null
require(
checkSuccess(),
"ERC20Wrapper.transfer: Bad return value"
);
}
/**
* Transfers tokens from an address (that has set allowance on the proxy).
* Handle's tokens that return true or null. If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(
address _token,
address _from,
address _to,
uint256 _quantity
)
external
{
IERC20(_token).transferFrom(_from, _to, _quantity);
// Check that transferFrom returns true or null
require(
checkSuccess(),
"ERC20Wrapper.transferFrom: Bad return value"
);
}
/**
* Grants spender ability to spend on owner's behalf.
* Handle's tokens that return true or null. If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _spender The address to approve for transfer
* @param _quantity The amount of tokens to approve spender for
*/
function approve(
address _token,
address _spender,
uint256 _quantity
)
internal
{
IERC20(_token).approve(_spender, _quantity);
// Check that approve returns true or null
require(
checkSuccess(),
"ERC20Wrapper.approve: Bad return value"
);
}
/**
* Ensure's the owner has granted enough allowance for system to
* transfer tokens.
*
* @param _token The address of the ERC20 token
* @param _owner The address of the token owner
* @param _spender The address to grant/check allowance for
* @param _quantity The amount to see if allowed for
*/
function ensureAllowance(
address _token,
address _owner,
address _spender,
uint256 _quantity
)
internal
{
uint256 currentAllowance = allowance(_token, _owner, _spender);
if (currentAllowance < _quantity) {
approve(
_token,
_spender,
CommonMath.maxUInt256()
);
}
}
// ============ Private Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 1.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
// default to failure
uint256 returnValue = 0;
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
// check if returned value is one or nothing
return returnValue == 1;
}
}
| 52,597 |
15 | // Send any referral fee | uint256 total = domain.price;
if (domain.referralFeePPM * domain.price > 0 && referrer != address(0x0) && referrer != domain.owner) {
uint256 referralFee = (domain.price * domain.referralFeePPM) / 1000000;
referrer.transfer(referralFee);
total -= referralFee;
}
| uint256 total = domain.price;
if (domain.referralFeePPM * domain.price > 0 && referrer != address(0x0) && referrer != domain.owner) {
uint256 referralFee = (domain.price * domain.referralFeePPM) / 1000000;
referrer.transfer(referralFee);
total -= referralFee;
}
| 46,597 |
105 | // Constructor for initializing the VestingEscrow contract._admin - address of the contract admin._token - address of the token._recipient - address of the recipient of the tokens._beneficiary - address of the tokens beneficiary._totalAmount - amount of tokens to vest._startTime - start timestamp of the vesting in seconds._endTime - end timestamp of the vesting in seconds._cliffLength - cliff length in seconds./ | function initialize(
address _admin,
address _token,
address _recipient,
address _beneficiary,
uint256 _totalAmount,
| function initialize(
address _admin,
address _token,
address _recipient,
address _beneficiary,
uint256 _totalAmount,
| 32,717 |
14 | // 80% sent here at end of crowdsale | address public beneficiary;
| address public beneficiary;
| 34,946 |
131 | // Predict the deployed clone address with the given parameters | function predictedRoyaltiesHandler(
address _handler,
address[] calldata _recipients,
uint256[] calldata _splits
) external view returns (address predictedHandler);
| function predictedRoyaltiesHandler(
address _handler,
address[] calldata _recipients,
uint256[] calldata _splits
) external view returns (address predictedHandler);
| 33,443 |
348 | // The WPC borrow index for each market for each borrower as of the last time they accrued WPC | mapping(address => mapping(address => uint)) public wpcBorrowerIndex;
| mapping(address => mapping(address => uint)) public wpcBorrowerIndex;
| 9,522 |
35 | // create tickets in ticket recipient (based on how many have already been sold) | for (uint i = 0; i < winners; i++){
address giveawayAddress = winnerAddress[i];
| for (uint i = 0; i < winners; i++){
address giveawayAddress = winnerAddress[i];
| 15,890 |
26 | // Get the current contract address | address contractAddress =
_getAddress(
keccak256(abi.encodePacked("contract.address", _contractName))
);
| address contractAddress =
_getAddress(
keccak256(abi.encodePacked("contract.address", _contractName))
);
| 28,771 |
137 | // public functions ============================================================ | function updateOracles() public {
for (uint i = 0; i < collateralArray.length; i++) {
if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).update();
}
}
| function updateOracles() public {
for (uint i = 0; i < collateralArray.length; i++) {
if (acceptedCollateral[collateralArray[i]]) TwapOracle(collateralOracle[collateralArray[i]]).update();
}
}
| 43,604 |
31 | // Burn taxed token | startToken.transfer(BURN_ADDRESS, tax);
| startToken.transfer(BURN_ADDRESS, tax);
| 38,500 |
46 | // Returns true if `account` is a contract. This test is non-exhaustive, and there may be false-negatives: during theexecution of a contract's constructor, its address will be reported asnot containing a contract. IMPORTANT: It is unsafe to assume that an address for which thisfunction returns false is an externally-owned account (EOA) and not acontract. / | function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
| function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
| 1,392 |
167 | // Change offering mining fee ratio | function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
| function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
| 24,881 |
1 | // The expected values of the variables | uint expectedNumberOfColumns = 2;
bool expectedDoorsStatus = true;
bool expectedBrakeStatus = true;
bool expectedCableStatus = true;
bool expectedBatteryStatus = true;
bool expectedhasColumnCertificateOfConformity = true;
bool expectedProductState = false;
bool isDoorsTestPass = true;
bool isBrakesTestPass = true;
bool isCableTestPass = true;
| uint expectedNumberOfColumns = 2;
bool expectedDoorsStatus = true;
bool expectedBrakeStatus = true;
bool expectedCableStatus = true;
bool expectedBatteryStatus = true;
bool expectedhasColumnCertificateOfConformity = true;
bool expectedProductState = false;
bool isDoorsTestPass = true;
bool isBrakesTestPass = true;
bool isCableTestPass = true;
| 15,954 |
246 | // 2. They sent some value > 0 | require(amount > 0, "Deposit must be greater than 0");
| require(amount > 0, "Deposit must be greater than 0");
| 28,989 |
400 | // Burn state for a pricefeed operator/user Address of pricefeed operator to burn the stake from | function burnStake(address user)
external
auth
{
uint totalToBurn = add(stakedAmounts[user], stakeToWithdraw[user]);
stakedAmounts[user] = 0;
stakeToWithdraw[user] = 0;
updateStakerRanking(user);
emit StakeBurned(user, totalToBurn, "");
}
| function burnStake(address user)
external
auth
{
uint totalToBurn = add(stakedAmounts[user], stakeToWithdraw[user]);
stakedAmounts[user] = 0;
stakeToWithdraw[user] = 0;
updateStakerRanking(user);
emit StakeBurned(user, totalToBurn, "");
}
| 35,389 |
4 | // The client must not be a client already | require(isClientInsured[msg.sender]==false);
require(msg.value == calculatePremium(msg.sender));
InsuranceClient storage customer = insuranceMapping[msg.sender];
customer.receivedPremiums += msg.value;
| require(isClientInsured[msg.sender]==false);
require(msg.value == calculatePremium(msg.sender));
InsuranceClient storage customer = insuranceMapping[msg.sender];
customer.receivedPremiums += msg.value;
| 14,363 |
189 | // TheSampleNft contract / | contract TestGenies5 is ERC721Enumerable, Ownable {
string public PROVENANCE_HASH = "";
uint256 public MAX_ITEMS;
uint256 public MAX_PRESALE_ITEMS;
uint256 public PUBLIC_ITEMS;
uint256 public COMMUNITY_ITEMS;
string public baseUri;
bool public isSaleActive;
bool public isPresaleActive;
uint256 public saleStartBlock;
uint256 public presaleStartBlock;
uint256 public mintPrice;
uint256 public maxPerMint;
uint256 public maxPerPresaleMint;
uint256 public communityMinted;
uint256 public presaleMinted;
mapping(address => bool) public presaleWhitelist;
mapping(address => uint) public presaleClaimed;
event SetBaseUri(string indexed baseUri);
modifier whenSaleActive {
require(isSaleActive || (block.number >= 0 && block.number >= saleStartBlock), "TheSampleNft: Sale is not active");
_;
}
modifier whenPresaleActive {
require(isPresaleActive || (block.number >= 0 && block.number >= presaleStartBlock), "TheSampleNft: Presale is not active");
require(presaleMinted < MAX_PRESALE_ITEMS, "TheSampleNft: Presale sold out");
_;
}
constructor() ERC721("Test Genies 5", "TGEN5") {
presaleStartBlock = 0;
saleStartBlock = 0;
MAX_ITEMS = 10000;
MAX_PRESALE_ITEMS = 2000;
COMMUNITY_ITEMS = 50;
PUBLIC_ITEMS = MAX_ITEMS - COMMUNITY_ITEMS;
mintPrice = 0.005 ether;
maxPerMint = 20;
maxPerPresaleMint = 3;
baseUri = "ipfs://QmR64gQpHHrjrkCQVGKjBeR443sE3QfkApqW5S1vM3z7Ey/";
}
// ------------------
// Utility view functions
// ------------------
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
function mint(uint256 amount) external payable whenSaleActive {
uint256 publicMinted = totalSupply() - communityMinted;
require(amount <= maxPerMint, "TheSampleNft: Amount exceeds max per mint");
require(publicMinted + amount <= PUBLIC_ITEMS, "TheSampleNft: Purchase would exceed cap");
require(mintPrice * amount <= msg.value, "TheSampleNft: Ether value sent is not correct");
for(uint256 i = 0; i < amount; i++) {
uint256 mintIndex = totalSupply() + 1;
if (publicMinted< PUBLIC_ITEMS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function presaleMint(uint256 amount) external payable whenPresaleActive {
require(amount <= maxPerPresaleMint, "TheSampleNft: Amount exceeds max per presale mint");
require(presaleMinted + amount <= MAX_PRESALE_ITEMS, "TheSampleNft: Purchase would exceed presale supply cap");
require(presaleClaimed[msg.sender] + amount <= maxPerPresaleMint, 'Purchase exceeds max allowed presale address cap');
require(mintPrice * amount <= msg.value, "TheSampleNft: Ether value sent is not correct");
for(uint256 i = 0; i < amount; i++) {
uint256 mintIndex = totalSupply() + 1;
if (presaleMinted < MAX_PRESALE_ITEMS) {
presaleClaimed[msg.sender] += 1;
presaleMinted += 1;
_safeMint(msg.sender, mintIndex);
}
}
}
// ------------------
// Functions for the owner
// ------------------
function updateWhitelist(address[] memory addresses, bool remove) external onlyOwner {
for (uint i=0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add the null address");
presaleWhitelist[addresses[i]] = remove ? false : true;
presaleClaimed[addresses[i]] > 0 ? presaleClaimed[addresses[i]] : 0;
}
}
function setMaxPerMint(uint256 _maxPerMint) external onlyOwner {
maxPerMint = _maxPerMint;
}
function setMaxPerPresaleMint(uint256 _maxPerPresaleMint) external onlyOwner {
maxPerPresaleMint = _maxPerPresaleMint;
}
function setMintPrice(uint256 _mintPrice) external onlyOwner {
mintPrice = _mintPrice;
}
function setBaseUri(string memory _baseUri) external onlyOwner {
baseUri = _baseUri;
emit SetBaseUri(baseUri);
}
function setPresaleStartBlock(uint256 blockNumber) external onlyOwner {
presaleStartBlock = blockNumber;
}
function setSaleStartBlock(uint256 blockNumber) external onlyOwner {
saleStartBlock = blockNumber;
}
function mintForCommunity(address _to, uint256 _numberOfTokens) external onlyOwner {
require(_to != address(0), "TheSampleNft: Cannot mint to zero address.");
require(totalSupply() + _numberOfTokens <= MAX_ITEMS, "TheSampleNft: Minting would exceed cap");
require(communityMinted + _numberOfTokens <= COMMUNITY_ITEMS, "TheSampleNft: Minting would exceed community cap");
for(uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply() + 1;
if (totalSupply() < MAX_ITEMS && communityMinted < COMMUNITY_ITEMS) {
_safeMint(_to, mintIndex);
communityMinted = communityMinted + 1;
}
}
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
PROVENANCE_HASH = _provenanceHash;
}
function toggleSaleState() external onlyOwner {
isSaleActive = !isSaleActive;
}
function togglePresaleState() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
}
| contract TestGenies5 is ERC721Enumerable, Ownable {
string public PROVENANCE_HASH = "";
uint256 public MAX_ITEMS;
uint256 public MAX_PRESALE_ITEMS;
uint256 public PUBLIC_ITEMS;
uint256 public COMMUNITY_ITEMS;
string public baseUri;
bool public isSaleActive;
bool public isPresaleActive;
uint256 public saleStartBlock;
uint256 public presaleStartBlock;
uint256 public mintPrice;
uint256 public maxPerMint;
uint256 public maxPerPresaleMint;
uint256 public communityMinted;
uint256 public presaleMinted;
mapping(address => bool) public presaleWhitelist;
mapping(address => uint) public presaleClaimed;
event SetBaseUri(string indexed baseUri);
modifier whenSaleActive {
require(isSaleActive || (block.number >= 0 && block.number >= saleStartBlock), "TheSampleNft: Sale is not active");
_;
}
modifier whenPresaleActive {
require(isPresaleActive || (block.number >= 0 && block.number >= presaleStartBlock), "TheSampleNft: Presale is not active");
require(presaleMinted < MAX_PRESALE_ITEMS, "TheSampleNft: Presale sold out");
_;
}
constructor() ERC721("Test Genies 5", "TGEN5") {
presaleStartBlock = 0;
saleStartBlock = 0;
MAX_ITEMS = 10000;
MAX_PRESALE_ITEMS = 2000;
COMMUNITY_ITEMS = 50;
PUBLIC_ITEMS = MAX_ITEMS - COMMUNITY_ITEMS;
mintPrice = 0.005 ether;
maxPerMint = 20;
maxPerPresaleMint = 3;
baseUri = "ipfs://QmR64gQpHHrjrkCQVGKjBeR443sE3QfkApqW5S1vM3z7Ey/";
}
// ------------------
// Utility view functions
// ------------------
function exists(uint256 _tokenId) public view returns (bool) {
return _exists(_tokenId);
}
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
function mint(uint256 amount) external payable whenSaleActive {
uint256 publicMinted = totalSupply() - communityMinted;
require(amount <= maxPerMint, "TheSampleNft: Amount exceeds max per mint");
require(publicMinted + amount <= PUBLIC_ITEMS, "TheSampleNft: Purchase would exceed cap");
require(mintPrice * amount <= msg.value, "TheSampleNft: Ether value sent is not correct");
for(uint256 i = 0; i < amount; i++) {
uint256 mintIndex = totalSupply() + 1;
if (publicMinted< PUBLIC_ITEMS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function presaleMint(uint256 amount) external payable whenPresaleActive {
require(amount <= maxPerPresaleMint, "TheSampleNft: Amount exceeds max per presale mint");
require(presaleMinted + amount <= MAX_PRESALE_ITEMS, "TheSampleNft: Purchase would exceed presale supply cap");
require(presaleClaimed[msg.sender] + amount <= maxPerPresaleMint, 'Purchase exceeds max allowed presale address cap');
require(mintPrice * amount <= msg.value, "TheSampleNft: Ether value sent is not correct");
for(uint256 i = 0; i < amount; i++) {
uint256 mintIndex = totalSupply() + 1;
if (presaleMinted < MAX_PRESALE_ITEMS) {
presaleClaimed[msg.sender] += 1;
presaleMinted += 1;
_safeMint(msg.sender, mintIndex);
}
}
}
// ------------------
// Functions for the owner
// ------------------
function updateWhitelist(address[] memory addresses, bool remove) external onlyOwner {
for (uint i=0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add the null address");
presaleWhitelist[addresses[i]] = remove ? false : true;
presaleClaimed[addresses[i]] > 0 ? presaleClaimed[addresses[i]] : 0;
}
}
function setMaxPerMint(uint256 _maxPerMint) external onlyOwner {
maxPerMint = _maxPerMint;
}
function setMaxPerPresaleMint(uint256 _maxPerPresaleMint) external onlyOwner {
maxPerPresaleMint = _maxPerPresaleMint;
}
function setMintPrice(uint256 _mintPrice) external onlyOwner {
mintPrice = _mintPrice;
}
function setBaseUri(string memory _baseUri) external onlyOwner {
baseUri = _baseUri;
emit SetBaseUri(baseUri);
}
function setPresaleStartBlock(uint256 blockNumber) external onlyOwner {
presaleStartBlock = blockNumber;
}
function setSaleStartBlock(uint256 blockNumber) external onlyOwner {
saleStartBlock = blockNumber;
}
function mintForCommunity(address _to, uint256 _numberOfTokens) external onlyOwner {
require(_to != address(0), "TheSampleNft: Cannot mint to zero address.");
require(totalSupply() + _numberOfTokens <= MAX_ITEMS, "TheSampleNft: Minting would exceed cap");
require(communityMinted + _numberOfTokens <= COMMUNITY_ITEMS, "TheSampleNft: Minting would exceed community cap");
for(uint256 i = 0; i < _numberOfTokens; i++) {
uint256 mintIndex = totalSupply() + 1;
if (totalSupply() < MAX_ITEMS && communityMinted < COMMUNITY_ITEMS) {
_safeMint(_to, mintIndex);
communityMinted = communityMinted + 1;
}
}
}
function setProvenanceHash(string memory _provenanceHash) external onlyOwner {
PROVENANCE_HASH = _provenanceHash;
}
function toggleSaleState() external onlyOwner {
isSaleActive = !isSaleActive;
}
function togglePresaleState() external onlyOwner {
isPresaleActive = !isPresaleActive;
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 index; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
}
| 31,610 |
10 | // Set the swap fee percentage. This is a permissioned function, and disabled if the pool is paused. The swap fee must be within thebounds set by MIN_SWAP_FEE_PERCENTAGE/MAX_SWAP_FEE_PERCENTAGE. Emits the SwapFeePercentageChanged event. / | function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
| function setSwapFeePercentage(uint256 swapFeePercentage) public virtual authenticate whenNotPaused {
_setSwapFeePercentage(swapFeePercentage);
}
| 15,381 |
10 | // This contract Identity information. | IdentityInformation public identityInformation;
| IdentityInformation public identityInformation;
| 37,210 |
57 | // -- Liquidation is completed | return true;
| return true;
| 12,972 |
167 | // Safe sheesha transfer function, just in case if rounding error causes pool to not have enough SHEESHAs | function safeSheeshaTransfer(address _to, uint256 _amount) internal {
uint256 sheeshaBal = sheesha.balanceOf(address(this));
if (_amount > sheeshaBal) {
sheesha.transfer(_to, sheeshaBal);
} else {
sheesha.transfer(_to, _amount);
}
}
| function safeSheeshaTransfer(address _to, uint256 _amount) internal {
uint256 sheeshaBal = sheesha.balanceOf(address(this));
if (_amount > sheeshaBal) {
sheesha.transfer(_to, sheeshaBal);
} else {
sheesha.transfer(_to, _amount);
}
}
| 9,132 |
5 | // Set up the various roles with the authority address | _setupRole(PAUSER_ROLE, _authority);
_setupRole(MINTER_ROLE, _authority);
_setupRole(ACCESS_ROLE, _authority);
_setupRole(MOVER_ROLE, _authority);
_setupRole(BURNER_ROLE, _authority);
_setupRole(FREEZER_ROLE, _authority);
| _setupRole(PAUSER_ROLE, _authority);
_setupRole(MINTER_ROLE, _authority);
_setupRole(ACCESS_ROLE, _authority);
_setupRole(MOVER_ROLE, _authority);
_setupRole(BURNER_ROLE, _authority);
_setupRole(FREEZER_ROLE, _authority);
| 236 |
35 | // Emitted when the contract is unpaused. | event Unpaused(address account);
| event Unpaused(address account);
| 31,677 |
11 | // gameInit event: player 0 set up the game | event gameInit(uint256 indexed GameId, address indexed Creator, uint256 indexed ExpirationBlock);
| event gameInit(uint256 indexed GameId, address indexed Creator, uint256 indexed ExpirationBlock);
| 49,756 |
29 | // Validates that the managers are initialized. / | modifier managersInitialized() {
require(v1DigitalMediaStore != address(0));
require(currentDigitalMediaStore != address(0));
_;
}
| modifier managersInitialized() {
require(v1DigitalMediaStore != address(0));
require(currentDigitalMediaStore != address(0));
_;
}
| 6,559 |
4 | // Bonus data | mapping( uint16 => mapping(address => uint256)) userLongTermStakeInPeriod;
mapping(address => uint256) userLastLongTermBonusPaid;
mapping( uint16 => uint256) longTermPoolSupply;
mapping( uint16 => uint256) longTermPoolTokenSupply;
mapping( uint16 => uint256) longTermPoolReward;
mapping( uint16 => uint256) periodStarts;
mapping( uint16 => uint256) periodEnds;
mapping( uint16 => mapping(address => uint256)) userLastBalanceInPeriod;
uint16 currentPeriod;
| mapping( uint16 => mapping(address => uint256)) userLongTermStakeInPeriod;
mapping(address => uint256) userLastLongTermBonusPaid;
mapping( uint16 => uint256) longTermPoolSupply;
mapping( uint16 => uint256) longTermPoolTokenSupply;
mapping( uint16 => uint256) longTermPoolReward;
mapping( uint16 => uint256) periodStarts;
mapping( uint16 => uint256) periodEnds;
mapping( uint16 => mapping(address => uint256)) userLastBalanceInPeriod;
uint16 currentPeriod;
| 30,282 |
166 | // EIP-2612 Provide internal implementation for gas-abstracted approvals / | abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32
public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) private _permitNonces;
/**
* @notice Nonces for permit
* @param owner Token owner's address (Authorizer)
* @return Next nonce
*/
function nonces(address owner) external view returns (uint256) {
return _permitNonces[owner];
}
/**
* @notice Verify a signed approval permit and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(deadline >= now, "FiatTokenV2: permit is expired");
bytes memory data = abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
_permitNonces[owner]++,
deadline
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"EIP2612: invalid signature"
);
_approve(owner, spender, value);
}
}
| abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
bytes32
public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) private _permitNonces;
/**
* @notice Nonces for permit
* @param owner Token owner's address (Authorizer)
* @return Next nonce
*/
function nonces(address owner) external view returns (uint256) {
return _permitNonces[owner];
}
/**
* @notice Verify a signed approval permit and execute if valid
* @param owner Token owner's address (Authorizer)
* @param spender Spender's address
* @param value Amount of allowance
* @param deadline The time at which this expires (unix time)
* @param v v of the signature
* @param r r of the signature
* @param s s of the signature
*/
function _permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
require(deadline >= now, "FiatTokenV2: permit is expired");
bytes memory data = abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
_permitNonces[owner]++,
deadline
);
require(
EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner,
"EIP2612: invalid signature"
);
_approve(owner, spender, value);
}
}
| 16,848 |
31 | // See {IERC165-supportsInterface}. Docs: https:docs.openzeppelin.com/contracts/4.x/api/utilsIERC165 | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IBridge).interfaceId ||
interfaceId == type(IBridgeReceiver).interfaceId ||
super.supportsInterface(interfaceId);
}
| function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IBridge).interfaceId ||
interfaceId == type(IBridgeReceiver).interfaceId ||
super.supportsInterface(interfaceId);
}
| 16,543 |
134 | // Perform binary search to find out user's epoch from the given timestamp/_user The user address/_timestamp The timestamp that you wish to find out epoch/_maxUserEpoch Max epoch to find out the timestamp | function _findTimestampUserEpoch(
address _user,
uint256 _timestamp,
uint256 _maxUserEpoch
| function _findTimestampUserEpoch(
address _user,
uint256 _timestamp,
uint256 _maxUserEpoch
| 28,320 |
119 | // console.log("get reward rate"); console.log(uint(_data.rewardWeight)); console.log(uint(_ctx.totalRewardWeight)); console.log(uint(_ctx.rewardRate)); | return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight);
| return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight);
| 32,187 |
11 | // admin is publish contract | address private admin = msg.sender;
| address private admin = msg.sender;
| 68,538 |
22 | // Total number of underlying shares that can beredeemed from the Vault by `owner`, where `owner` correspondsto the input parameter of a `redeem` call. / | function maxRedeem(address owner) external view virtual override returns (uint256) {
return maxWithdraw(owner);
}
| function maxRedeem(address owner) external view virtual override returns (uint256) {
return maxWithdraw(owner);
}
| 21,556 |
13 | // gb 0x90842eb834cfd2a1db0b1512b254a18e4d396215 cra 0xa32608e873f9ddef944b24798db69d80bbb4d1edaddress of the uniswap v2 router | address private constant UNISWAP_V2_ROUTER = 0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106;
| address private constant UNISWAP_V2_ROUTER = 0xE54Ca86531e17Ef3616d22Ca28b0D458b6C89106;
| 35,247 |
17 | // The easiest way to bubble the revert reason is using memory via assembly |
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
|
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
| 2,846 |
77 | // Initializes the contract by setting a `name` and a `symbol` to the token collection. / | constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
| constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
| 1,663 |
73 | // Allow only from zones/ | modifier onlyZone() {
require(zones[msg.sender]);
_;
}
| modifier onlyZone() {
require(zones[msg.sender]);
_;
}
| 7,609 |
5 | // Returns the first id in the tree that is higher than or equal to the given id.It will return 0 if there is no such id. tree The tree id The idreturn The first id in the tree that is higher than or equal to the given id / | function findFirstLeft(TreeUint24 storage tree, uint24 id) internal view returns (uint24) {
bytes32 leaves;
bytes32 key2 = bytes32(uint256(id) >> 8);
uint8 bit = uint8(id & type(uint8).max);
if (bit != type(uint8).max) {
leaves = tree.level2[key2];
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) return uint24(uint256(key2) << 8 | closestBit);
}
bytes32 key1 = key2 >> 8;
bit = uint8(uint256(key2) & type(uint8).max);
if (bit != type(uint8).max) {
leaves = tree.level1[key1];
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) {
key2 = bytes32(uint256(key1) << 8 | closestBit);
leaves = tree.level2[key2];
return uint24(uint256(key2) << 8 | uint256(leaves).leastSignificantBit());
}
}
bit = uint8(uint256(key1) & type(uint8).max);
if (bit != type(uint8).max) {
leaves = tree.level0;
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) {
key1 = bytes32(closestBit);
leaves = tree.level1[key1];
key2 = bytes32(uint256(key1) << 8 | uint256(leaves).leastSignificantBit());
leaves = tree.level2[key2];
return uint24(uint256(key2) << 8 | uint256(leaves).leastSignificantBit());
}
}
return 0;
}
| function findFirstLeft(TreeUint24 storage tree, uint24 id) internal view returns (uint24) {
bytes32 leaves;
bytes32 key2 = bytes32(uint256(id) >> 8);
uint8 bit = uint8(id & type(uint8).max);
if (bit != type(uint8).max) {
leaves = tree.level2[key2];
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) return uint24(uint256(key2) << 8 | closestBit);
}
bytes32 key1 = key2 >> 8;
bit = uint8(uint256(key2) & type(uint8).max);
if (bit != type(uint8).max) {
leaves = tree.level1[key1];
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) {
key2 = bytes32(uint256(key1) << 8 | closestBit);
leaves = tree.level2[key2];
return uint24(uint256(key2) << 8 | uint256(leaves).leastSignificantBit());
}
}
bit = uint8(uint256(key1) & type(uint8).max);
if (bit != type(uint8).max) {
leaves = tree.level0;
uint256 closestBit = _closestBitLeft(leaves, bit);
if (closestBit != type(uint256).max) {
key1 = bytes32(closestBit);
leaves = tree.level1[key1];
key2 = bytes32(uint256(key1) << 8 | uint256(leaves).leastSignificantBit());
leaves = tree.level2[key2];
return uint24(uint256(key2) << 8 | uint256(leaves).leastSignificantBit());
}
}
return 0;
}
| 28,721 |
71 | // Get X node of required Matrix. matrix Matrix "3" or "6". level Matrix level. id Tree node id.return Parameters of Tree structure: user address, parent node, parent address, child nodes, child addresses. / | function getTreeNode(uint32 matrix, uint32 level, uint64 id) public view returns (address, uint64, address, uint64[] memory, address[] memory){
address[] memory childAddresses = new address[](tree[matrix][level][id].childs.length);
for(uint64 i = 0; i < tree[matrix][level][id].childs.length; i++){
childAddresses[i] = tree[matrix][level][ tree[matrix][level][id].childs[i] ].userAddress;
}
return (
tree[matrix][level][id].userAddress,
tree[matrix][level][id].parent,
tree[matrix][level][ tree[matrix][level][id].parent ].userAddress,
tree[matrix][level][id].childs,
childAddresses
);
}
| function getTreeNode(uint32 matrix, uint32 level, uint64 id) public view returns (address, uint64, address, uint64[] memory, address[] memory){
address[] memory childAddresses = new address[](tree[matrix][level][id].childs.length);
for(uint64 i = 0; i < tree[matrix][level][id].childs.length; i++){
childAddresses[i] = tree[matrix][level][ tree[matrix][level][id].childs[i] ].userAddress;
}
return (
tree[matrix][level][id].userAddress,
tree[matrix][level][id].parent,
tree[matrix][level][ tree[matrix][level][id].parent ].userAddress,
tree[matrix][level][id].childs,
childAddresses
);
}
| 41,118 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.