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 |
|---|---|---|---|---|
13 | // Receives json from constructTokenURI / prettier-ignore | function tokenURI(uint256 _id)
public
view
override
returns (string memory)
| function tokenURI(uint256 _id)
public
view
override
returns (string memory)
| 10,975 |
293 | // Similar to EIP20 transfer, except it handles a False result from `transferFrom` reverts in that case. If caller has not called `checkTransferIn`, this may revert due to insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, and it returned Error.NO_ERROR, this should not revert in normal conditions. This function returns the actual amount received, with may be less than `amount` if there is a fee attached with the transfer.Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. / | function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
| function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
| 15,022 |
94 | // Returns whether an add operation causes an overflow/a First addend/b Second addend/ return Did no overflow occur? | function safeToAdd(uint a, uint b)
public
constant
returns (bool)
| function safeToAdd(uint a, uint b)
public
constant
returns (bool)
| 78,821 |
41 | // Retrieves the current ring buffer context. _self Buffer to access.return Current ring buffer context. / | function getContext(
RingBuffer storage _self
)
internal
view
returns (
RingBufferContext memory
)
| function getContext(
RingBuffer storage _self
)
internal
view
returns (
RingBufferContext memory
)
| 10,955 |
12 | // The minimalist design of a container's smart contract. Storage:Contract stores all possible items (pallet, box, item) in its own storage.Items are stored in simple tree structure container->pallets->boxs->items. The structure allows passing all nodes in both directions.It is possible to retrieve all items from a container as well as retrieve all parent for specific item up to the root element(container).The structure is append-only. Events:The contract contains a number of events which allows tracing of contract's changing without doing any calls to the contract.Log memory is cheap, it allows optimize gas usage as well. | contract Container is Ownable {
struct Node {
uint256 parentId;
uint256[] childs;
}
struct Leaf {
uint256 id;
uint256 parentId;
}
event LogPallet(uint256 indexed _index);
event LogBox(uint256 indexed _palletIndex, uint256 indexed _index);
event LogItem(uint256 indexed _boxIndex, uint256 indexed _index, uint256 indexed _id);
event LogTrace(address indexed _from, string _msg);
uint256 private palletIndex = 0;
Node[] private pallets;
mapping(uint256 => address) palletOwners;
uint256 private boxIndex = 0;
Node[] private boxes;
uint256 private itemIndex = 0;
Leaf[] private items;
/**
@notice Adds pallet to the container
@dev MUST emit LogPallet event on success
@param _owner Pallet's owner, the field cannot be empty
@return Index of created pallet
*/
function addPallet(address _owner) external onlyOwner returns(uint256 index) {
require(_owner != address(0x0), "_owner must be non-zero.");
pallets.push(Node({
parentId: 0,
childs: new uint256[](0)
}));
index = palletIndex;
palletOwners[index] = _owner;
palletIndex++;
emit LogPallet(index);
}
/**
@notice Adds box linked to specified pallet
@dev MUST emit LogBox event on success
@param _palletIndex Pallet's index, pallet should exists
@return Index of created box
*/
function addBox(uint256 _palletIndex) external onlyOwner returns(uint256 index) {
require(_palletIndex < palletIndex);
boxes.push(Node({
parentId: _palletIndex,
childs: new uint256[](0)
}));
pallets[_palletIndex].childs.push(boxIndex);
index = boxIndex;
boxIndex++;
emit LogBox(_palletIndex, index);
}
/**
@notice Adds item linked to specified box
@dev MUST emit LogItem event on success
@param _boxIndex Box's index, box should exists
@param _id Item's identifier
@return Index of created item
*/
function addItem(uint256 _boxIndex, uint256 _id) external onlyOwner returns(uint256 index) {
require(_boxIndex < boxIndex);
items.push(Leaf({
id: _id,
parentId: _boxIndex
}));
boxes[_boxIndex].childs.push(itemIndex);
index = itemIndex;
itemIndex++;
emit LogItem(_boxIndex, index, _id);
}
/**
@notice Adds data to the log. It allows store dynamic data.
*/
function trace(string memory _msg) public {
emit LogTrace(msg.sender, _msg);
}
function getPalletsCount() public view returns(uint256) {
return palletIndex;
}
function getBoxesCount() public view returns(uint256) {
return boxIndex;
}
function getItemsCount() public view returns(uint256) {
return itemIndex;
}
function getPallet(uint256 _index) public view returns(uint256, uint256[] memory, address) {
require(_index < palletIndex);
return (pallets[_index].parentId, pallets[_index].childs, palletOwners[_index]);
}
function getBox(uint256 _index) public view returns(uint256, uint256[] memory) {
require(_index < boxIndex);
return (boxes[_index].parentId, boxes[_index].childs);
}
function getItem(uint256 _index) public view returns(uint256, uint256) {
require(_index < boxIndex);
return (items[_index].id, items[_index].parentId);
}
} | contract Container is Ownable {
struct Node {
uint256 parentId;
uint256[] childs;
}
struct Leaf {
uint256 id;
uint256 parentId;
}
event LogPallet(uint256 indexed _index);
event LogBox(uint256 indexed _palletIndex, uint256 indexed _index);
event LogItem(uint256 indexed _boxIndex, uint256 indexed _index, uint256 indexed _id);
event LogTrace(address indexed _from, string _msg);
uint256 private palletIndex = 0;
Node[] private pallets;
mapping(uint256 => address) palletOwners;
uint256 private boxIndex = 0;
Node[] private boxes;
uint256 private itemIndex = 0;
Leaf[] private items;
/**
@notice Adds pallet to the container
@dev MUST emit LogPallet event on success
@param _owner Pallet's owner, the field cannot be empty
@return Index of created pallet
*/
function addPallet(address _owner) external onlyOwner returns(uint256 index) {
require(_owner != address(0x0), "_owner must be non-zero.");
pallets.push(Node({
parentId: 0,
childs: new uint256[](0)
}));
index = palletIndex;
palletOwners[index] = _owner;
palletIndex++;
emit LogPallet(index);
}
/**
@notice Adds box linked to specified pallet
@dev MUST emit LogBox event on success
@param _palletIndex Pallet's index, pallet should exists
@return Index of created box
*/
function addBox(uint256 _palletIndex) external onlyOwner returns(uint256 index) {
require(_palletIndex < palletIndex);
boxes.push(Node({
parentId: _palletIndex,
childs: new uint256[](0)
}));
pallets[_palletIndex].childs.push(boxIndex);
index = boxIndex;
boxIndex++;
emit LogBox(_palletIndex, index);
}
/**
@notice Adds item linked to specified box
@dev MUST emit LogItem event on success
@param _boxIndex Box's index, box should exists
@param _id Item's identifier
@return Index of created item
*/
function addItem(uint256 _boxIndex, uint256 _id) external onlyOwner returns(uint256 index) {
require(_boxIndex < boxIndex);
items.push(Leaf({
id: _id,
parentId: _boxIndex
}));
boxes[_boxIndex].childs.push(itemIndex);
index = itemIndex;
itemIndex++;
emit LogItem(_boxIndex, index, _id);
}
/**
@notice Adds data to the log. It allows store dynamic data.
*/
function trace(string memory _msg) public {
emit LogTrace(msg.sender, _msg);
}
function getPalletsCount() public view returns(uint256) {
return palletIndex;
}
function getBoxesCount() public view returns(uint256) {
return boxIndex;
}
function getItemsCount() public view returns(uint256) {
return itemIndex;
}
function getPallet(uint256 _index) public view returns(uint256, uint256[] memory, address) {
require(_index < palletIndex);
return (pallets[_index].parentId, pallets[_index].childs, palletOwners[_index]);
}
function getBox(uint256 _index) public view returns(uint256, uint256[] memory) {
require(_index < boxIndex);
return (boxes[_index].parentId, boxes[_index].childs);
}
function getItem(uint256 _index) public view returns(uint256, uint256) {
require(_index < boxIndex);
return (items[_index].id, items[_index].parentId);
}
} | 24,163 |
113 | // Now we have our lowest priced token ID that we will sell into, calculate price difference | bool profitable = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 _price = tokenList[i].price;
if(_price > targetPrice){
if(_price.sub(targetPrice) >= minDifference){ // Difference is greater than 0.001 cents
| bool profitable = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 _price = tokenList[i].price;
if(_price > targetPrice){
if(_price.sub(targetPrice) >= minDifference){ // Difference is greater than 0.001 cents
| 6,498 |
90 | // This is an internal function which should be called from user-implemented externalburn function. Its purpose is to show and properly initialize data structures when using thisimplementation. Also, note that this burn implementation allows the minter to re-mint a burnedNFT. Burns a NFT. _tokenId ID of the NFT to be burned. / | function _burn(uint256 _tokenId) internal virtual override {
super._burn(_tokenId);
uint256 tokenIndex = idToIndex[_tokenId];
uint256 lastTokenIndex = tokens.length - 1;
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.pop();
// This wastes gas if you are burning the last token but saves a little gas if you are not.
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
}
| function _burn(uint256 _tokenId) internal virtual override {
super._burn(_tokenId);
uint256 tokenIndex = idToIndex[_tokenId];
uint256 lastTokenIndex = tokens.length - 1;
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.pop();
// This wastes gas if you are burning the last token but saves a little gas if you are not.
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
}
| 10,050 |
73 | // now we handled all tail/head situation, we have to connect prev and next | infos[info.prev].next = info.next;
infos[info.next].prev = info.prev;
| infos[info.prev].next = info.next;
infos[info.next].prev = info.prev;
| 10,248 |
48 | // split the contract balance into halves | uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
| uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
| 41,047 |
41 | // If the amount being transfered is more than the balance of theaccount the transfer returns false | uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
| uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
| 70,398 |
31 | // Zap Getters LibraryThis is the getter library for all variables in the Zap Tokens system. ZapGetters references thislibary for the getters logic/ | library ZapGettersLibrary{
using SafeMathM for uint256;
event NewZapAddress(address _newZap); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Zap to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the zap system
*/
function changeDeity(ZapStorage.ZapStorageStruct storage self, address _newDeity) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("_deity")] =_newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Zap System
* @param _zapContract address of new updated ZapCore contract
*/
function changeZapContract(ZapStorage.ZapStorageStruct storage self,address _zapContract) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("zapContract")]= _zapContract;
emit NewZapAddress(_zapContract);
}
/*Zap Getters*/
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(ZapStorage.ZapStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){
return self.minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a dispute
* @param _disputeId to look up
* @param _address of voting party to look up
* @return bool of whether or not party voted
*/
function didVote(ZapStorage.ZapStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){
return self.disputesById[_disputeId].voted[_address];
}
/**
* @dev allows Zap to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("zapContract")]
*/
function getAddressVars(ZapStorage.ZapStorageStruct storage self, bytes32 _data) view internal returns(address){
return self.addressVars[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return bool isPropFork true if the dispute is a proposed fork
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(ZapStorage.ZapStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){
ZapStorage.Dispute storage disp = self.disputesById[_disputeId];
return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally);
}
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables(ZapStorage.ZapStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){
return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(ZapStorage.ZapStorageStruct storage self,bytes32 _hash) internal view returns(uint){
return self.disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(ZapStorage.ZapStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){
return self.disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue(ZapStorage.ZapStorageStruct storage self) internal view returns(uint,bool){
return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true);
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(ZapStorage.ZapStorageStruct storage self,uint _requestId) internal view returns(uint,bool){
ZapStorage.Request storage _request = self.requestDetails[_requestId];
if(_request.requestTimestamps.length > 0){
return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true);
}
else{
return (0,false);
}
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(ZapStorage.ZapStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){
return self.requestDetails[_requestId].minedBlockNum[_timestamp];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){
return self.requestDetails[_requestId].minersByValue[_timestamp];
}
/**
* @dev Get the name of the token
* @return string of the token name
*/
function getName(ZapStorage.ZapStorageStruct storage self) internal pure returns(string memory){
return "Zap Tokens";
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(ZapStorage.ZapStorageStruct storage self, uint _requestId) internal view returns(uint){
return self.requestDetails[_requestId].requestTimestamps.length;
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(ZapStorage.ZapStorageStruct storage self, uint _index) internal view returns(uint){
require(_index <= 50);
return self.requestIdByRequestQIndex[_index];
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(ZapStorage.ZapStorageStruct storage self, uint _timestamp) internal view returns(uint){
return self.requestIdByTimestamp[_timestamp];
}
/**
* @dev Getter function for requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(ZapStorage.ZapStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){
return self.requestIdByQueryHash[_queryHash];
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ(ZapStorage.ZapStorageStruct storage self) view internal returns(uint[51] memory){
return self.requestQ;
}
/**
* @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(ZapStorage.ZapStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){
return self.requestDetails[_requestId].apiUintVars[_data];
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(ZapStorage.ZapStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) {
ZapStorage.Request storage _request = self.requestDetails[_requestId];
return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(ZapStorage.ZapStorageStruct storage self,address _staker) internal view returns(uint,uint){
return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){
return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Get the symbol of the token
* @return string of the token symbol
*/
function getSymbol(ZapStorage.ZapStorageStruct storage self) internal pure returns(string memory){
return "TT";
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(ZapStorage.ZapStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){
return self.requestDetails[_requestID].requestTimestamps[_index];
}
/**
* @dev Getter for the variables saved under the ZapStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the ZapStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(ZapStorage.ZapStorageStruct storage self,bytes32 _data) view internal returns(uint){
return self.uintVars[_data];
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck(ZapStorage.ZapStorageStruct storage self) internal view returns(uint, uint,string memory){
uint newRequestId = getTopRequestID(self);
return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString);
}
/**
* @dev Getter function for the request with highest payout. This function is used withing the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(ZapStorage.ZapStorageStruct storage self) internal view returns(uint _requestId){
uint _max;
uint _index;
(_max,_index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) {
return self.requestDetails[_requestId].finalValues[_timestamp];
}
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply(ZapStorage.ZapStorageStruct storage self) internal view returns (uint) {
return self.uintVars[keccak256("total_supply")];
}
}
| library ZapGettersLibrary{
using SafeMathM for uint256;
event NewZapAddress(address _newZap); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Zap to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the zap system
*/
function changeDeity(ZapStorage.ZapStorageStruct storage self, address _newDeity) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("_deity")] =_newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Zap System
* @param _zapContract address of new updated ZapCore contract
*/
function changeZapContract(ZapStorage.ZapStorageStruct storage self,address _zapContract) internal{
require(self.addressVars[keccak256("_deity")] == msg.sender);
self.addressVars[keccak256("zapContract")]= _zapContract;
emit NewZapAddress(_zapContract);
}
/*Zap Getters*/
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(ZapStorage.ZapStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){
return self.minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a dispute
* @param _disputeId to look up
* @param _address of voting party to look up
* @return bool of whether or not party voted
*/
function didVote(ZapStorage.ZapStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){
return self.disputesById[_disputeId].voted[_address];
}
/**
* @dev allows Zap to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("zapContract")]
*/
function getAddressVars(ZapStorage.ZapStorageStruct storage self, bytes32 _data) view internal returns(address){
return self.addressVars[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return bool isPropFork true if the dispute is a proposed fork
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(ZapStorage.ZapStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){
ZapStorage.Dispute storage disp = self.disputesById[_disputeId];
return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally);
}
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables(ZapStorage.ZapStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){
return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(ZapStorage.ZapStorageStruct storage self,bytes32 _hash) internal view returns(uint){
return self.disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(ZapStorage.ZapStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){
return self.disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue(ZapStorage.ZapStorageStruct storage self) internal view returns(uint,bool){
return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true);
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(ZapStorage.ZapStorageStruct storage self,uint _requestId) internal view returns(uint,bool){
ZapStorage.Request storage _request = self.requestDetails[_requestId];
if(_request.requestTimestamps.length > 0){
return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true);
}
else{
return (0,false);
}
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(ZapStorage.ZapStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){
return self.requestDetails[_requestId].minedBlockNum[_timestamp];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){
return self.requestDetails[_requestId].minersByValue[_timestamp];
}
/**
* @dev Get the name of the token
* @return string of the token name
*/
function getName(ZapStorage.ZapStorageStruct storage self) internal pure returns(string memory){
return "Zap Tokens";
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(ZapStorage.ZapStorageStruct storage self, uint _requestId) internal view returns(uint){
return self.requestDetails[_requestId].requestTimestamps.length;
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(ZapStorage.ZapStorageStruct storage self, uint _index) internal view returns(uint){
require(_index <= 50);
return self.requestIdByRequestQIndex[_index];
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(ZapStorage.ZapStorageStruct storage self, uint _timestamp) internal view returns(uint){
return self.requestIdByTimestamp[_timestamp];
}
/**
* @dev Getter function for requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(ZapStorage.ZapStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){
return self.requestIdByQueryHash[_queryHash];
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ(ZapStorage.ZapStorageStruct storage self) view internal returns(uint[51] memory){
return self.requestQ;
}
/**
* @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(ZapStorage.ZapStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){
return self.requestDetails[_requestId].apiUintVars[_data];
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(ZapStorage.ZapStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) {
ZapStorage.Request storage _request = self.requestDetails[_requestId];
return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(ZapStorage.ZapStorageStruct storage self,address _staker) internal view returns(uint,uint){
return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){
return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Get the symbol of the token
* @return string of the token symbol
*/
function getSymbol(ZapStorage.ZapStorageStruct storage self) internal pure returns(string memory){
return "TT";
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(ZapStorage.ZapStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){
return self.requestDetails[_requestID].requestTimestamps[_index];
}
/**
* @dev Getter for the variables saved under the ZapStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the ZapStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(ZapStorage.ZapStorageStruct storage self,bytes32 _data) view internal returns(uint){
return self.uintVars[_data];
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck(ZapStorage.ZapStorageStruct storage self) internal view returns(uint, uint,string memory){
uint newRequestId = getTopRequestID(self);
return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString);
}
/**
* @dev Getter function for the request with highest payout. This function is used withing the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(ZapStorage.ZapStorageStruct storage self) internal view returns(uint _requestId){
uint _max;
uint _index;
(_max,_index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(ZapStorage.ZapStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) {
return self.requestDetails[_requestId].finalValues[_timestamp];
}
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply(ZapStorage.ZapStorageStruct storage self) internal view returns (uint) {
return self.uintVars[keccak256("total_supply")];
}
}
| 7,560 |
30 | // --- Init --- | constructor (address _oracle) public {
// core
dai = IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa);
dao = 0x89188bE35B16AF852dC0A4a9e47e0cA871fadf9a;
// default dao controlled parameters
oracle = _oracle;
cap = 1000000000000000000000000;
fee = 400; // 0.25%
unifa = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30;
unisl = 40; // uniswap slippage - 2.5%
unidl = 900 * 60; // uniswap deadline - 15 minutes
// DSR - DAI Savings Rate
daiJoin = DaiJoin(0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c);
vat = Vat(0xbA987bDB501d131f766fEe8180Da5d81b34b69d9);
pot = Pot(0xEA190DBDC7adF265260ec4dA6e9675Fd4f5A78bb);
vat.hope(address(daiJoin));
vat.hope(address(pot));
// Uniswap
uniswapFactory = UniswapFactoryInterface(unifa);
daiExchange = UniswapExchangeInterface(uniswapFactory.getExchange(address(dai)));
dai.approve(address(daiJoin), uint256(-1));
// first drip
_drip();
}
| constructor (address _oracle) public {
// core
dai = IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa);
dao = 0x89188bE35B16AF852dC0A4a9e47e0cA871fadf9a;
// default dao controlled parameters
oracle = _oracle;
cap = 1000000000000000000000000;
fee = 400; // 0.25%
unifa = 0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30;
unisl = 40; // uniswap slippage - 2.5%
unidl = 900 * 60; // uniswap deadline - 15 minutes
// DSR - DAI Savings Rate
daiJoin = DaiJoin(0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c);
vat = Vat(0xbA987bDB501d131f766fEe8180Da5d81b34b69d9);
pot = Pot(0xEA190DBDC7adF265260ec4dA6e9675Fd4f5A78bb);
vat.hope(address(daiJoin));
vat.hope(address(pot));
// Uniswap
uniswapFactory = UniswapFactoryInterface(unifa);
daiExchange = UniswapExchangeInterface(uniswapFactory.getExchange(address(dai)));
dai.approve(address(daiJoin), uint256(-1));
// first drip
_drip();
}
| 4,750 |
23 | // marketShare is an inverse weighting for the market maker's desired portfolio: 100 = ETH weight. 200 = half the weight of ETH 50 = twice the weight of ETH | function upsertAsset(ERC20 token, AggregatorV3Interface oracle, uint256 rawMarketShare) external onlyOwner {
require(rawMarketShare > 0, "Clipper: Market share must be positive");
// Oracle returns a response that is in base oracle.decimals()
// corresponding to one "unit" of input, in base token.decimals()
// We want to return an adjustment figure with DEFAULT_DECIMALS
// When both of these are 18 (DEFAULT_DECIMALS), we let the marketShare go straight through
// We need to adjust the oracle's response so that it corresponds to
uint256 sumDecimals = token.decimals()+oracle.decimals();
uint256 marketShareDecimalsAdjusted = rawMarketShare*WEI_PER_ETH;
if(sumDecimals < 2*DEFAULT_DECIMALS){
// Make it larger
marketShareDecimalsAdjusted = marketShareDecimalsAdjusted*(10**(2*DEFAULT_DECIMALS-sumDecimals));
} else if(sumDecimals > 2*DEFAULT_DECIMALS){
// Make it smaller
marketShareDecimalsAdjusted = marketShareDecimalsAdjusted/(10**(sumDecimals-2*DEFAULT_DECIMALS));
}
assetSet.add(address(token));
assets[token] = Asset(oracle, rawMarketShare, marketShareDecimalsAdjusted, token.balanceOf(address(this)), 0);
emit TokenModified(address(token), rawMarketShare, address(oracle));
}
| function upsertAsset(ERC20 token, AggregatorV3Interface oracle, uint256 rawMarketShare) external onlyOwner {
require(rawMarketShare > 0, "Clipper: Market share must be positive");
// Oracle returns a response that is in base oracle.decimals()
// corresponding to one "unit" of input, in base token.decimals()
// We want to return an adjustment figure with DEFAULT_DECIMALS
// When both of these are 18 (DEFAULT_DECIMALS), we let the marketShare go straight through
// We need to adjust the oracle's response so that it corresponds to
uint256 sumDecimals = token.decimals()+oracle.decimals();
uint256 marketShareDecimalsAdjusted = rawMarketShare*WEI_PER_ETH;
if(sumDecimals < 2*DEFAULT_DECIMALS){
// Make it larger
marketShareDecimalsAdjusted = marketShareDecimalsAdjusted*(10**(2*DEFAULT_DECIMALS-sumDecimals));
} else if(sumDecimals > 2*DEFAULT_DECIMALS){
// Make it smaller
marketShareDecimalsAdjusted = marketShareDecimalsAdjusted/(10**(sumDecimals-2*DEFAULT_DECIMALS));
}
assetSet.add(address(token));
assets[token] = Asset(oracle, rawMarketShare, marketShareDecimalsAdjusted, token.balanceOf(address(this)), 0);
emit TokenModified(address(token), rawMarketShare, address(oracle));
}
| 52,616 |
44 | // ------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` accountThe calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------ | function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool) {
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
| function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool) {
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
| 49,346 |
204 | // Computes the final oracle fees that a contract should pay at settlement. currency token used to pay the final fee.return finalFee amount due. / | function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
| function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
| 7,761 |
18 | // OWNABLE FUNCTIONS/ | function setTotalLockFloor(uint256 _totalLockFloor) external onlyOwner {
// BT_TLEM: totalLockFloor exceed maximum
require(_totalLockFloor <= MAX_TOTAL_LOCK_FLOOR, "BT_TLEM");
totalLockFloor = _totalLockFloor;
}
| function setTotalLockFloor(uint256 _totalLockFloor) external onlyOwner {
// BT_TLEM: totalLockFloor exceed maximum
require(_totalLockFloor <= MAX_TOTAL_LOCK_FLOOR, "BT_TLEM");
totalLockFloor = _totalLockFloor;
}
| 20,958 |
11 | // V2 买入 | function V2Buy(uint256 amountIn, uint amountOutMin, address[] memory path) external onlyExecutor returns (uint[] memory){
| function V2Buy(uint256 amountIn, uint amountOutMin, address[] memory path) external onlyExecutor returns (uint[] memory){
| 31,501 |
83 | // `balanceOf` would give the amount staked.As this is 1 to 1, this is also the holder's share | function balanceOf(address holder) external view returns (uint256);
| function balanceOf(address holder) external view returns (uint256);
| 25,941 |
168 | // See {IERC1155MetadataURI-uri}. This implementation returns the same URI for all token types. It relieson the token type ID substitution mechanism Clients calling this function must replace the `\{id\}` substring with theactual token type ID. / | function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
| function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
| 171 |
263 | // SafeMath Math operations with safety checks that throw on errorchange notes:original SafeMath library from OpenZeppelin modified by Inventor- added sqrt- added sq- added pwr - changed asserts to requires with error log outputs / | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | 14,853 |
51 | // when ico finishes we can perform other actions | modifier whenICOFinished {
uint8 _round = _getCurrentRound(now);
require(_round < 0 || _round > 4); // if we do not get current valid round number ICO finished
_;
}
| modifier whenICOFinished {
uint8 _round = _getCurrentRound(now);
require(_round < 0 || _round > 4); // if we do not get current valid round number ICO finished
_;
}
| 39,149 |
2 | // Transfer the ETH payment to the specified address | address payable paymentReceiver = payable(
0xc28D0C12eF4a55b5B72044736540E3f45509d7f9
);
paymentReceiver.transfer(msg.value);
| address payable paymentReceiver = payable(
0xc28D0C12eF4a55b5B72044736540E3f45509d7f9
);
paymentReceiver.transfer(msg.value);
| 18,753 |
22 | // 90 days for version 0.1 | lendingDays = _lendingDays;
state = LendingState.AcceptingContributions;
StateChange(uint(state));
| lendingDays = _lendingDays;
state = LendingState.AcceptingContributions;
StateChange(uint(state));
| 44,334 |
31 | // Listing created/updated against address. | whitelist[_tokenId] = Whitelist(_address, block.timestamp, true);
emit Whitelisted(_tokenId, _address, block.timestamp);
| whitelist[_tokenId] = Whitelist(_address, block.timestamp, true);
emit Whitelisted(_tokenId, _address, block.timestamp);
| 26,218 |
1 | // |/ A distinct Uniform Resource Identifier (URI) for a given token. URIs are defined in RFC 3986. URIs are assumed to be deterministically generated based on token ID Token IDs are assumed to be represented in their hex format in URIsreturn URI string / | function uri(uint256 _id) public view returns (string memory) {
return
string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json"));
}
| function uri(uint256 _id) public view returns (string memory) {
return
string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json"));
}
| 20,403 |
27 | // Returns the total number of editions / | function totalEditions() external view returns (uint256 total) {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
total = state._editionCounter - 1;
}
| function totalEditions() external view returns (uint256 total) {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
total = state._editionCounter - 1;
}
| 40,215 |
47 | // Create a new withdraw minimize trading strategy instance./_router The Uniswap router smart contract. | constructor(IUniswapV2Router02 _router) public {
factory = IUniswapV2Factory(_router.factory());
router = _router;
weth = _router.WETH();
}
| constructor(IUniswapV2Router02 _router) public {
factory = IUniswapV2Factory(_router.factory());
router = _router;
weth = _router.WETH();
}
| 40,151 |
194 | // _payoutDistributionHash the payout distribution hash being checkedreturn uint256 indicating the REP stake in a single outcome for a particular payout hash / | function getStakeInOutcome(bytes32 _payoutDistributionHash) public view returns (uint256) {
uint256 _sum;
// Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21
for (uint256 i = 0; i < participants.length; ++i) {
IReportingParticipant _reportingParticipant = participants[i];
if (_reportingParticipant.getPayoutDistributionHash() != _payoutDistributionHash) {
continue;
}
_sum = _sum.add(_reportingParticipant.getStake());
}
return _sum;
}
| function getStakeInOutcome(bytes32 _payoutDistributionHash) public view returns (uint256) {
uint256 _sum;
// Participants is implicitly bounded by the floor of the initial report REP cost to be no more than 21
for (uint256 i = 0; i < participants.length; ++i) {
IReportingParticipant _reportingParticipant = participants[i];
if (_reportingParticipant.getPayoutDistributionHash() != _payoutDistributionHash) {
continue;
}
_sum = _sum.add(_reportingParticipant.getStake());
}
return _sum;
}
| 31,636 |
63 | // Convert reeth decimals to ETH | totalREETH = totalREETH.mul(10**uint256(IERC20(WETH_ADDRESS).decimals())).div(10**uint256(IERC20(reethAddress).decimals()));
totalETH += totalREETH.mul(reethPrice).div(1e18);
return totalETH.mul(_bal).div(totalZS); // This will be the user's equivalent balance in eth worth
| totalREETH = totalREETH.mul(10**uint256(IERC20(WETH_ADDRESS).decimals())).div(10**uint256(IERC20(reethAddress).decimals()));
totalETH += totalREETH.mul(reethPrice).div(1e18);
return totalETH.mul(_bal).div(totalZS); // This will be the user's equivalent balance in eth worth
| 11,472 |
74 | // update myown info | if (serialAddr[msg.sender]==0){
serialAddr[msg.sender]=counter;
counter = counter.add(1);
}
| if (serialAddr[msg.sender]==0){
serialAddr[msg.sender]=counter;
counter = counter.add(1);
}
| 9,711 |
9 | // Helper function to allow batching of BentoBox master contract approvals so the first trade can happen in one transaction. | function approveMasterContract(
uint8 v,
bytes32 r,
bytes32 s
| function approveMasterContract(
uint8 v,
bytes32 r,
bytes32 s
| 55,927 |
297 | // Admin can set start and min price through this function. _startPrice Auction start price. _minimumPrice Auction minimum price. / | function setAuctionPrice(uint256 _startPrice, uint256 _minimumPrice) external {
require(hasAdminRole(msg.sender));
require(_startPrice > _minimumPrice, "DutchAuction: start price must be higher than minimum price");
require(_minimumPrice > 0, "DutchAuction: minimum price must be greater than 0");
require(marketStatus.commitmentsTotal == 0, "DutchAuction: auction cannot have already started");
marketPrice.startPrice = BoringMath.to128(_startPrice);
marketPrice.minimumPrice = BoringMath.to128(_minimumPrice);
emit AuctionPriceUpdated(_startPrice,_minimumPrice);
}
| function setAuctionPrice(uint256 _startPrice, uint256 _minimumPrice) external {
require(hasAdminRole(msg.sender));
require(_startPrice > _minimumPrice, "DutchAuction: start price must be higher than minimum price");
require(_minimumPrice > 0, "DutchAuction: minimum price must be greater than 0");
require(marketStatus.commitmentsTotal == 0, "DutchAuction: auction cannot have already started");
marketPrice.startPrice = BoringMath.to128(_startPrice);
marketPrice.minimumPrice = BoringMath.to128(_minimumPrice);
emit AuctionPriceUpdated(_startPrice,_minimumPrice);
}
| 56,306 |
63 | // Cannot set bots after 20 minutes of launch time to ensure contract is SAFU without renounce as well | if (block.timestamp < _launchTime + (20 minutes)) {
for (uint i = 0; i < bots_.length; i++) {
if (bots_[i] != uniswapV2Pair && bots_[i] != address(uniswapV2Router)) {
_bots[bots_[i]] = true;
}
| if (block.timestamp < _launchTime + (20 minutes)) {
for (uint i = 0; i < bots_.length; i++) {
if (bots_[i] != uniswapV2Pair && bots_[i] != address(uniswapV2Router)) {
_bots[bots_[i]] = true;
}
| 32,219 |
150 | // The Token contract does this and that... / | contract Folia is ERC721Full, Ownable {
using Roles for Roles.Role;
Roles.Role private _admins;
uint8 admins;
address public metadata;
address public controller;
modifier onlyAdminOrController() {
require((_admins.has(msg.sender) || msg.sender == controller), "DOES_NOT_HAVE_ADMIN_OR_CONTROLLER_ROLE");
_;
}
modifier onlyAdmin() {
require(_admins.has(msg.sender), "DOES_NOT_HAVE_ADMIN_ROLE");
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, operator or controller
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(_isApprovedOrOwner(msg.sender, _tokenId) || msg.sender == controller);
_;
}
constructor(string memory name, string memory symbol, address _metadata) public ERC721Full(name, symbol) {
metadata = _metadata;
_admins.add(msg.sender);
admins += 1;
}
function mint(address recepient, uint256 tokenId) public onlyAdminOrController {
_mint(recepient, tokenId);
}
function burn(uint256 tokenId) public onlyAdminOrController {
_burn(ownerOf(tokenId), tokenId);
}
function updateMetadata(address _metadata) public onlyAdminOrController {
metadata = _metadata;
}
function updateController(address _controller) public onlyAdminOrController {
controller = _controller;
}
function addAdmin(address _admin) public onlyOwner {
_admins.add(_admin);
admins += 1;
}
function removeAdmin(address _admin) public onlyOwner {
require(admins > 1, "CANT_REMOVE_LAST_ADMIN");
_admins.remove(_admin);
admins -= 1;
}
function tokenURI(uint _tokenId) external view returns (string memory _infoUrl) {
return Metadata(metadata).tokenURI(_tokenId);
}
/**
* @dev Moves Eth to a certain address for use in the CloversController
* @param _to The address to receive the Eth.
* @param _amount The amount of Eth to be transferred.
*/
function moveEth(address payable _to, uint256 _amount) public onlyAdminOrController {
require(_amount <= address(this).balance);
_to.transfer(_amount);
}
/**
* @dev Moves Token to a certain address for use in the CloversController
* @param _to The address to receive the Token.
* @param _amount The amount of Token to be transferred.
* @param _token The address of the Token to be transferred.
*/
function moveToken(address _to, uint256 _amount, address _token) public onlyAdminOrController returns (bool) {
require(_amount <= IERC20(_token).balanceOf(address(this)));
return IERC20(_token).transfer(_to, _amount);
}
}
| contract Folia is ERC721Full, Ownable {
using Roles for Roles.Role;
Roles.Role private _admins;
uint8 admins;
address public metadata;
address public controller;
modifier onlyAdminOrController() {
require((_admins.has(msg.sender) || msg.sender == controller), "DOES_NOT_HAVE_ADMIN_OR_CONTROLLER_ROLE");
_;
}
modifier onlyAdmin() {
require(_admins.has(msg.sender), "DOES_NOT_HAVE_ADMIN_ROLE");
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, operator or controller
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(_isApprovedOrOwner(msg.sender, _tokenId) || msg.sender == controller);
_;
}
constructor(string memory name, string memory symbol, address _metadata) public ERC721Full(name, symbol) {
metadata = _metadata;
_admins.add(msg.sender);
admins += 1;
}
function mint(address recepient, uint256 tokenId) public onlyAdminOrController {
_mint(recepient, tokenId);
}
function burn(uint256 tokenId) public onlyAdminOrController {
_burn(ownerOf(tokenId), tokenId);
}
function updateMetadata(address _metadata) public onlyAdminOrController {
metadata = _metadata;
}
function updateController(address _controller) public onlyAdminOrController {
controller = _controller;
}
function addAdmin(address _admin) public onlyOwner {
_admins.add(_admin);
admins += 1;
}
function removeAdmin(address _admin) public onlyOwner {
require(admins > 1, "CANT_REMOVE_LAST_ADMIN");
_admins.remove(_admin);
admins -= 1;
}
function tokenURI(uint _tokenId) external view returns (string memory _infoUrl) {
return Metadata(metadata).tokenURI(_tokenId);
}
/**
* @dev Moves Eth to a certain address for use in the CloversController
* @param _to The address to receive the Eth.
* @param _amount The amount of Eth to be transferred.
*/
function moveEth(address payable _to, uint256 _amount) public onlyAdminOrController {
require(_amount <= address(this).balance);
_to.transfer(_amount);
}
/**
* @dev Moves Token to a certain address for use in the CloversController
* @param _to The address to receive the Token.
* @param _amount The amount of Token to be transferred.
* @param _token The address of the Token to be transferred.
*/
function moveToken(address _to, uint256 _amount, address _token) public onlyAdminOrController returns (bool) {
require(_amount <= IERC20(_token).balanceOf(address(this)));
return IERC20(_token).transfer(_to, _amount);
}
}
| 13,000 |
16 | // Secondary listing business logic need to add additional checks | function listItem(
address nftAddress,
uint256 tokenId,
uint256 amount,
uint256 price
)
external
isNftTokenOwner(nftAddress, tokenId, msg.sender)
| function listItem(
address nftAddress,
uint256 tokenId,
uint256 amount,
uint256 price
)
external
isNftTokenOwner(nftAddress, tokenId, msg.sender)
| 11,396 |
18 | // data is organized in blocks of 10x10. There are 100x100 blocks. Base is 0 and counting goes left to right, then top to bottom. | Block[10000] public blk;
uint256[] public updates;
constructor() public payable {
| Block[10000] public blk;
uint256[] public updates;
constructor() public payable {
| 8,993 |
0 | // ========== CONSTANT VARIABLES ========== / | enum ProposalStatus {Inactive, Active, Passed, Executed, Cancelled}
struct Proposal {
ProposalStatus _status;
uint200 _yesVotes; // bitmap, 200 maximum votes
uint8 _yesVotesTotal;
uint40 _proposedBlock; // 1099511627775 maximum block
}
| enum ProposalStatus {Inactive, Active, Passed, Executed, Cancelled}
struct Proposal {
ProposalStatus _status;
uint200 _yesVotes; // bitmap, 200 maximum votes
uint8 _yesVotesTotal;
uint40 _proposedBlock; // 1099511627775 maximum block
}
| 11,312 |
14 | // Unpause deposits only on the pool. | function unpauseDeposit() external;
| function unpauseDeposit() external;
| 52,934 |
15 | // to use addon bought on opensea on your specific pet | function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused
| function useAddon(uint256 _nftId, uint256 _addonID)
public
tokenOwner(_nftId)
notPaused
| 7,311 |
35 | // Internal functions //Adds a new transaction to the transaction mapping, if transaction does not exist yet./destination Transaction target address./value Transaction ether value./data Transaction data payload./ return Returns transaction ID. | function addTransaction(
address destination,
uint256 value,
bytes data
| function addTransaction(
address destination,
uint256 value,
bytes data
| 15,109 |
9 | // Reserve | function sendReserved(address receiver, uint256 quantity) external onlyOwner{
require(totalSupply() + quantity < TOKEN_MAX_SUPPLY, "Max Supply Reached.");
require( (RESERVED_LEFT - quantity) >= 0, "Cannot mint more");
_safeMint(receiver, quantity);
RESERVED_LEFT = RESERVED_LEFT - quantity;
}
| function sendReserved(address receiver, uint256 quantity) external onlyOwner{
require(totalSupply() + quantity < TOKEN_MAX_SUPPLY, "Max Supply Reached.");
require( (RESERVED_LEFT - quantity) >= 0, "Cannot mint more");
_safeMint(receiver, quantity);
RESERVED_LEFT = RESERVED_LEFT - quantity;
}
| 76,592 |
102 | // Returns total number of Point tokens being accrued by the user per dayacross all of its NFT stakes. / | {
Stake[] memory stakes = stakesByUser[user];
uint256 totalPointsPerDay;
for (uint256 i = 0; i < stakes.length; i++) {
Stake memory _stake = stakes[i];
uint256 tierNumber = getTierByTokenId(_stake.tokenId);
uint256 pointsPerDay = pointsPerDayByTierNumber[tierNumber];
totalPointsPerDay += pointsPerDay;
}
return totalPointsPerDay;
}
| {
Stake[] memory stakes = stakesByUser[user];
uint256 totalPointsPerDay;
for (uint256 i = 0; i < stakes.length; i++) {
Stake memory _stake = stakes[i];
uint256 tierNumber = getTierByTokenId(_stake.tokenId);
uint256 pointsPerDay = pointsPerDayByTierNumber[tierNumber];
totalPointsPerDay += pointsPerDay;
}
return totalPointsPerDay;
}
| 52,651 |
20 | // 2^128. / | uint256 internal constant TWO128 = 0x100000000000000000000000000000000;
| uint256 internal constant TWO128 = 0x100000000000000000000000000000000;
| 50,391 |
47 | // Public wrapper for internal call. borrowAmount The amount of tokens to borrow.return The next borrow interest rate./ | function nextBorrowInterestRate(uint256 borrowAmount) public view returns (uint256) {
return _nextBorrowInterestRate(borrowAmount);
}
| function nextBorrowInterestRate(uint256 borrowAmount) public view returns (uint256) {
return _nextBorrowInterestRate(borrowAmount);
}
| 4,433 |
19 | // if OpenSea's ERC721 Proxy Address is detected, auto-return true | if (_operator == address(0x58807baD0B376efc12F5AD86aAc70E78ed67deaE)) {
return true;
}
| if (_operator == address(0x58807baD0B376efc12F5AD86aAc70E78ed67deaE)) {
return true;
}
| 31,939 |
38 | // Returns list of owners./ return List of owner addresses. | function getOwners()
public
constant
returns (address[])
| function getOwners()
public
constant
returns (address[])
| 15,229 |
2 | // Founder vesting | address private _founderWallet;
uint256 private _founderAllocation;
uint256 private _maxFounderTranches = 25; // release founder tokens 24 tranches every 30 days period = 2 years
uint256 private _totalFounderAllocated = 0;
uint256 private _founderTranchesReleased = 0;
constructor(string memory name,
string memory symbol,
address communityReserveWallet,
address crowdFundWallet,
| address private _founderWallet;
uint256 private _founderAllocation;
uint256 private _maxFounderTranches = 25; // release founder tokens 24 tranches every 30 days period = 2 years
uint256 private _totalFounderAllocated = 0;
uint256 private _founderTranchesReleased = 0;
constructor(string memory name,
string memory symbol,
address communityReserveWallet,
address crowdFundWallet,
| 3,268 |
6 | // Requires that account address is the MPV contract./account Address of account. | modifier mpvAccessOnly(address account) {
require(account == address(masterPropertyValue));
_;
}
| modifier mpvAccessOnly(address account) {
require(account == address(masterPropertyValue));
_;
}
| 10,829 |
10 | // Function that allows a user to stake his LP tokens obtained inside the contract_amount is a uint with the amount of LP Tokens to be staked/ | function stakeFromContract(uint _amount) internal updateReward(msg.sender) {
totalSupply += _amount;
balances[msg.sender] += _amount;
}
| function stakeFromContract(uint _amount) internal updateReward(msg.sender) {
totalSupply += _amount;
balances[msg.sender] += _amount;
}
| 19,953 |
166 | // wrap eth => WETH if necessary | uint256 remainder = msg.value.sub(coverage_price, "buy:underpayment");
WETH.deposit.value(coverage_price)();
| uint256 remainder = msg.value.sub(coverage_price, "buy:underpayment");
WETH.deposit.value(coverage_price)();
| 10,862 |
67 | // | uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam).sub(tCharity).sub(tBurn);
| uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam).sub(tCharity).sub(tBurn);
| 9,432 |
276 | // We cycle through interest bearing tokens currently in use (eg [cDAI, aDAI]) (ie we cycle each lending protocol where we have some funds currently deposited) | for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currToken = allAvailableTokens[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
protocolTokenPrice = protocol.getPriceInToken();
availableLiquidity = protocol.availableLiquidity();
currBalanceUnderlying = _contractBalanceOf(currToken).mul(protocolTokenPrice).div(ONE_18);
| for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currToken = allAvailableTokens[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
protocolTokenPrice = protocol.getPriceInToken();
availableLiquidity = protocol.availableLiquidity();
currBalanceUnderlying = _contractBalanceOf(currToken).mul(protocolTokenPrice).div(ONE_18);
| 15,820 |
16 | // batch number => (plasma address => deposit information) | mapping (uint256 => mapping (uint24 => DepositRequest)) public depositRequests;
mapping (uint256 => DepositBatch) public depositBatches;
| mapping (uint256 => mapping (uint24 => DepositRequest)) public depositRequests;
mapping (uint256 => DepositBatch) public depositBatches;
| 16,581 |
60 | // BNB has18 decimals! | return _tDonationTotal;
| return _tDonationTotal;
| 70,275 |
4 | // get the tokens | IERC20(token).transferFrom(msg.sender, address(this), amount);
| IERC20(token).transferFrom(msg.sender, address(this), amount);
| 30,506 |
13 | // Deposit ETH to WETH | IWETH(WETH).deposit{ value: msg.value }();
| IWETH(WETH).deposit{ value: msg.value }();
| 24,387 |
21 | // Update Metadata -DEVONLY should be replaced by ENS but we probably still need to emit the event_baseURI new base URI for metadata change / | function updateMetaData( string memory _baseURI ) external onlyAdmin {
| function updateMetaData( string memory _baseURI ) external onlyAdmin {
| 24,332 |
188 | // HomeFeeManagerMultiAMBErc20ToErc677Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations. The fees are distributed in the form of native tokens to the list of reward accounts./ | contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge {
using SafeMath for uint256;
event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee);
event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId);
// This is not a real fee value but a relative value used to calculate the fee percentage
uint256 internal constant MAX_FEE = 1 ether;
bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee"))
bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee"))
/**
* @dev Throws if given fee percentage is >= 100%.
*/
modifier validFee(uint256 _fee) {
require(_fee < MAX_FEE);
/* solcov ignore next */
_;
}
/**
* @dev Throws if given fee type is unknown.
*/
modifier validFeeType(bytes32 _feeType) {
require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE);
/* solcov ignore next */
_;
}
/**
* @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations.
* Only the owner can call this method.
* @param _addr new reward account.
*/
function addRewardAddress(address _addr) external onlyOwner {
_addRewardAddress(_addr);
}
/**
* @dev Removes a reward address from the rewards list.
* Only the owner can call this method.
* @param _addr old reward account, that should be removed.
*/
function removeRewardAddress(address _addr) external onlyOwner {
_removeRewardAddress(_addr);
}
/**
* @dev Updates the value for the particular fee type.
* Only the owner can call this method.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
*/
function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner {
_setFee(_feeType, _token, _fee);
}
/**
* @dev Retrieves the value for the particular fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @return fee value associated with the requested fee type.
*/
function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) {
return uintStorage[keccak256(abi.encodePacked(_feeType, _token))];
}
/**
* @dev Calculates the amount of fee to pay for the value of the particular fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _value bridged value, for which fee should be evaluated.
* @return amount of fee to be subtracted from the transferred value.
*/
function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) {
uint256 _fee = getFee(_feeType, _token);
return _value.mul(_fee).div(MAX_FEE);
}
/**
* @dev Internal function for updating the fee value for the given fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
*/
function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) {
require(isTokenRegistered(_token));
uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee;
emit FeeUpdated(_feeType, _token, _fee);
}
/**
* @dev Calculates a random number based on the block number.
* @param _count the max value for the random number.
* @return a number between 0 and _count.
*/
function random(uint256 _count) internal view returns (uint256) {
return uint256(blockhash(block.number.sub(1))) % _count;
}
/**
* @dev Calculates and distributes the amount of fee proportionally between registered reward addresses.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _value bridged value, for which fee should be evaluated.
* @return total amount of fee subtracted from the transferred value and distributed between the reward accounts.
*/
function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) {
uint256 numOfAccounts = rewardAddressCount();
uint256 _fee = calculateFee(_feeType, _token, _value);
if (numOfAccounts == 0 || _fee == 0) {
return 0;
}
uint256 feePerAccount = _fee.div(numOfAccounts);
uint256 randomAccountIndex;
uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts));
if (diff > 0) {
randomAccountIndex = random(numOfAccounts);
}
address nextAddr = getNextRewardAddress(F_ADDR);
require(nextAddr != F_ADDR && nextAddr != address(0));
uint256 i = 0;
while (nextAddr != F_ADDR) {
uint256 feeToDistribute = feePerAccount;
if (diff > 0 && randomAccountIndex == i) {
feeToDistribute = feeToDistribute.add(diff);
}
if (_feeType == HOME_TO_FOREIGN_FEE) {
ERC677(_token).transfer(nextAddr, feeToDistribute);
} else {
IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute);
}
nextAddr = getNextRewardAddress(nextAddr);
require(nextAddr != address(0));
i = i + 1;
}
return _fee;
}
}
| contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge {
using SafeMath for uint256;
event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee);
event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId);
// This is not a real fee value but a relative value used to calculate the fee percentage
uint256 internal constant MAX_FEE = 1 ether;
bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee"))
bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee"))
/**
* @dev Throws if given fee percentage is >= 100%.
*/
modifier validFee(uint256 _fee) {
require(_fee < MAX_FEE);
/* solcov ignore next */
_;
}
/**
* @dev Throws if given fee type is unknown.
*/
modifier validFeeType(bytes32 _feeType) {
require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE);
/* solcov ignore next */
_;
}
/**
* @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations.
* Only the owner can call this method.
* @param _addr new reward account.
*/
function addRewardAddress(address _addr) external onlyOwner {
_addRewardAddress(_addr);
}
/**
* @dev Removes a reward address from the rewards list.
* Only the owner can call this method.
* @param _addr old reward account, that should be removed.
*/
function removeRewardAddress(address _addr) external onlyOwner {
_removeRewardAddress(_addr);
}
/**
* @dev Updates the value for the particular fee type.
* Only the owner can call this method.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
*/
function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner {
_setFee(_feeType, _token, _fee);
}
/**
* @dev Retrieves the value for the particular fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @return fee value associated with the requested fee type.
*/
function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) {
return uintStorage[keccak256(abi.encodePacked(_feeType, _token))];
}
/**
* @dev Calculates the amount of fee to pay for the value of the particular fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _value bridged value, for which fee should be evaluated.
* @return amount of fee to be subtracted from the transferred value.
*/
function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) {
uint256 _fee = getFee(_feeType, _token);
return _value.mul(_fee).div(MAX_FEE);
}
/**
* @dev Internal function for updating the fee value for the given fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
*/
function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) {
require(isTokenRegistered(_token));
uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee;
emit FeeUpdated(_feeType, _token, _fee);
}
/**
* @dev Calculates a random number based on the block number.
* @param _count the max value for the random number.
* @return a number between 0 and _count.
*/
function random(uint256 _count) internal view returns (uint256) {
return uint256(blockhash(block.number.sub(1))) % _count;
}
/**
* @dev Calculates and distributes the amount of fee proportionally between registered reward addresses.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _value bridged value, for which fee should be evaluated.
* @return total amount of fee subtracted from the transferred value and distributed between the reward accounts.
*/
function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) {
uint256 numOfAccounts = rewardAddressCount();
uint256 _fee = calculateFee(_feeType, _token, _value);
if (numOfAccounts == 0 || _fee == 0) {
return 0;
}
uint256 feePerAccount = _fee.div(numOfAccounts);
uint256 randomAccountIndex;
uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts));
if (diff > 0) {
randomAccountIndex = random(numOfAccounts);
}
address nextAddr = getNextRewardAddress(F_ADDR);
require(nextAddr != F_ADDR && nextAddr != address(0));
uint256 i = 0;
while (nextAddr != F_ADDR) {
uint256 feeToDistribute = feePerAccount;
if (diff > 0 && randomAccountIndex == i) {
feeToDistribute = feeToDistribute.add(diff);
}
if (_feeType == HOME_TO_FOREIGN_FEE) {
ERC677(_token).transfer(nextAddr, feeToDistribute);
} else {
IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute);
}
nextAddr = getNextRewardAddress(nextAddr);
require(nextAddr != address(0));
i = i + 1;
}
return _fee;
}
}
| 42,564 |
48 | // Nectar is wrapping Tokens, generates wrappped UNIv2 | interface INectar {
function wrapUNIv2(uint256 amount) external;
function wTransfer(address recipient, uint256 amount) external;
function setPublicWrappingRatio(uint256 _ratioBase100) external;
}
| interface INectar {
function wrapUNIv2(uint256 amount) external;
function wTransfer(address recipient, uint256 amount) external;
function setPublicWrappingRatio(uint256 _ratioBase100) external;
}
| 21,908 |
1 | // Memo struct. | struct Memo {
address from;
address to;
uint256 timestamp;
string name;
string message;
uint256 amount;
uint256 cups;
}
| struct Memo {
address from;
address to;
uint256 timestamp;
string name;
string message;
uint256 amount;
uint256 cups;
}
| 878 |
95 | // push round prizes to persistent storage | if (roundPrizeClaimed[userLastRoundInteractedWith[_user]] == false && roundPrizeTokenRangeIdentified[userLastRoundInteractedWith[_user]]) {
| if (roundPrizeClaimed[userLastRoundInteractedWith[_user]] == false && roundPrizeTokenRangeIdentified[userLastRoundInteractedWith[_user]]) {
| 14,918 |
2 | // _token : aToken address _underlying : underlying token (eg DAI) address / | constructor(address _token, address _underlying) public {
require(_token != address(0) && _underlying != address(0), 'some addr is 0');
token = _token;
underlying = _underlying;
IERC20(_underlying).safeApprove(_token, uint256(-1));
}
| constructor(address _token, address _underlying) public {
require(_token != address(0) && _underlying != address(0), 'some addr is 0');
token = _token;
underlying = _underlying;
IERC20(_underlying).safeApprove(_token, uint256(-1));
}
| 20,516 |
6 | // this is the address we are going to send the output tokens to | address to,
| address to,
| 41,614 |
69 | // Trigger rollback using upgradeTo from the new implementation | rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
| rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
| 13,563 |
7 | // isApprovedForAll is disabled because the nft is a sbt and cannot be transfered -> the output will always be false/ | function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return false;
}
| function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return false;
}
| 18,569 |
3 | // PUBLIC | function _mintZoul(uint256 numZouls) internal returns (bool) {
for (uint256 i = 0; i < numZouls; i++) {
uint256 tokenIndex = totalSupply();
if (tokenIndex < GENESIS_ZOULS_TOTAL) {
_totalZoulClaimed[msg.sender] += 1;
_safeMint(_msgSender(), tokenIndex);
}
}
return true;
}
| function _mintZoul(uint256 numZouls) internal returns (bool) {
for (uint256 i = 0; i < numZouls; i++) {
uint256 tokenIndex = totalSupply();
if (tokenIndex < GENESIS_ZOULS_TOTAL) {
_totalZoulClaimed[msg.sender] += 1;
_safeMint(_msgSender(), tokenIndex);
}
}
return true;
}
| 41,852 |
210 | // and the transaction WILL FAIL if the TREX conditions of transfer are not respected, please refer to {Token-transfer} and {Token-transferFrom} to know more about TREX conditions for transfers once the DVD transfer is executed the `_transferID` is removed from the pending `_transferID` pool emits a `DVDTransferExecuted` event / | function takeDVDTransfer(bytes32 _transferID) external {
Delivery memory token1 = token1ToDeliver[_transferID];
Delivery memory token2 = token2ToDeliver[_transferID];
require(token1.counterpart != address(0) && token2.counterpart != address(0), 'transfer ID does not exist');
IERC20 token1Contract = IERC20(token1.token);
IERC20 token2Contract = IERC20(token2.token);
require (msg.sender == token2.counterpart || isTREXAgent(token1.token, msg.sender) || isTREXAgent(token2.token, msg.sender), 'transfer has to be done by the counterpart or by owner');
require(token2Contract.balanceOf(token2.counterpart) >= token2.amount, 'Not enough tokens in balance');
require(token2Contract.allowance(token2.counterpart, address(this)) >= token2.amount, 'not enough allowance to transfer');
TxFees memory fees = calculateFee(_transferID);
| function takeDVDTransfer(bytes32 _transferID) external {
Delivery memory token1 = token1ToDeliver[_transferID];
Delivery memory token2 = token2ToDeliver[_transferID];
require(token1.counterpart != address(0) && token2.counterpart != address(0), 'transfer ID does not exist');
IERC20 token1Contract = IERC20(token1.token);
IERC20 token2Contract = IERC20(token2.token);
require (msg.sender == token2.counterpart || isTREXAgent(token1.token, msg.sender) || isTREXAgent(token2.token, msg.sender), 'transfer has to be done by the counterpart or by owner');
require(token2Contract.balanceOf(token2.counterpart) >= token2.amount, 'Not enough tokens in balance');
require(token2Contract.allowance(token2.counterpart, address(this)) >= token2.amount, 'not enough allowance to transfer');
TxFees memory fees = calculateFee(_transferID);
| 71,335 |
196 | // Withdraw LP tokens from ISWMasterChef. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accISWPerShare).div(1e12).sub(user.rewardDebt);
safeISWTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accISWPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accISWPerShare).div(1e12).sub(user.rewardDebt);
safeISWTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accISWPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 38,438 |
2 | // the number of items that have passed the quality test | uint public quantity_passed;
| uint public quantity_passed;
| 21,042 |
95 | // edge case, should be impossible, but this is defi | totalVotes = 0;
| totalVotes = 0;
| 61,918 |
8 | // CREATES A NEW GOAL AND ADD TO ACCOUNT | function addGoal(address goalOwner, uint amt, string memory des) public returns (uint)
| function addGoal(address goalOwner, uint amt, string memory des) public returns (uint)
| 22,043 |
8 | // GenerateKey from solution inputs | bytes32 key = generateKey(a, b, c, inputs);
require(verifier.verifyTx(a, b, c, inputs), 'Solution is not correct');
addSolution(tokenId, to, key);
super.mint(to, tokenId);
| bytes32 key = generateKey(a, b, c, inputs);
require(verifier.verifyTx(a, b, c, inputs), 'Solution is not correct');
addSolution(tokenId, to, key);
super.mint(to, tokenId);
| 20,146 |
162 | // operator | function addOperator(address _operator) public onlyOwner returns (bool) {
require(_operator != address(0), "_operator is the zero address");
return EnumerableSet.add(_operators, _operator);
}
| function addOperator(address _operator) public onlyOwner returns (bool) {
require(_operator != address(0), "_operator is the zero address");
return EnumerableSet.add(_operators, _operator);
}
| 26,197 |
13 | // Function to set/update vesting schedule. PS - Amount cannot be changed once set / | public changesToVestingNotFreezed(_adr) onlyAllocateAgent {
require(_adr!=address(0), "Cannot set Null Address");
VestingSchedule storage vestingSchedule = vestingMap[_adr];
// data validation
require(_step != 0);
require(_amount != 0 || vestingSchedule.amount > 0);
require(_duration != 0);
require(_cliff <= _duration);
//if startAt is zero, set current time as start time.
if (_startAt == 0)
_startAt = block.timestamp;
vestingSchedule.startAt = _startAt;
vestingSchedule.cliff = _cliff;
vestingSchedule.duration = _duration;
vestingSchedule.step = _step;
// special processing for first time vesting setting
if (vestingSchedule.amount == 0) {
// check if enough tokens are held by this contract
ERC20 token = ERC20(crowdSaleTokenAddress);
require(token.balanceOf(address(this)) >= totalUnreleasedTokens.plus(_amount));
totalUnreleasedTokens = totalUnreleasedTokens.plus(_amount);
vestingSchedule.amount = _amount;
}
vestingSchedule.amountReleased = 0;
vestingSchedule.changeFreezed = _changeFreezed;
vestedWallets.push(_adr);
}
| public changesToVestingNotFreezed(_adr) onlyAllocateAgent {
require(_adr!=address(0), "Cannot set Null Address");
VestingSchedule storage vestingSchedule = vestingMap[_adr];
// data validation
require(_step != 0);
require(_amount != 0 || vestingSchedule.amount > 0);
require(_duration != 0);
require(_cliff <= _duration);
//if startAt is zero, set current time as start time.
if (_startAt == 0)
_startAt = block.timestamp;
vestingSchedule.startAt = _startAt;
vestingSchedule.cliff = _cliff;
vestingSchedule.duration = _duration;
vestingSchedule.step = _step;
// special processing for first time vesting setting
if (vestingSchedule.amount == 0) {
// check if enough tokens are held by this contract
ERC20 token = ERC20(crowdSaleTokenAddress);
require(token.balanceOf(address(this)) >= totalUnreleasedTokens.plus(_amount));
totalUnreleasedTokens = totalUnreleasedTokens.plus(_amount);
vestingSchedule.amount = _amount;
}
vestingSchedule.amountReleased = 0;
vestingSchedule.changeFreezed = _changeFreezed;
vestedWallets.push(_adr);
}
| 4,692 |
69 | // Make the proposal fail if the dilutionBound is exceeded | if ((totalSupply().mul(dilutionBound)) < proposal.maxTotalSharesAndLootAtYesVote) {
didPass = false;
}
| if ((totalSupply().mul(dilutionBound)) < proposal.maxTotalSharesAndLootAtYesVote) {
didPass = false;
}
| 38,904 |
36 | // Empty storage | for (uint256 i = left; i < right; i++) {
(tstamp, slotIdx, roomId) = loadPacked(i);
require(tstamp < currentDay, "Not enough gasTokens could be freed");
| for (uint256 i = left; i < right; i++) {
(tstamp, slotIdx, roomId) = loadPacked(i);
require(tstamp < currentDay, "Not enough gasTokens could be freed");
| 35,522 |
49 | // SELECTOR是 'transfer(address,uint256)' 字符串哈希值的前4位16进制数字 | bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory; // 工厂地址
address public token0; // token0地址
address public token1; // token1地址
uint112 private reserve0; // 储备量0
uint112 private reserve1; // 储备量1
uint32 private blockTimestampLast; // 更新储备量的最后时间戳
| bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory; // 工厂地址
address public token0; // token0地址
address public token1; // token1地址
uint112 private reserve0; // 储备量0
uint112 private reserve1; // 储备量1
uint32 private blockTimestampLast; // 更新储备量的最后时间戳
| 33,183 |
84 | // Remove all Ether from the contract, which is the owner's cuts/as well as any Ether sent directly to the contract address./Always transfers to the NFT contract, but can be called either by/the owner or the NFT contract. | function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = nftAddress.send(this.balance);
}
| function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = nftAddress.send(this.balance);
}
| 73,193 |
44 | // Updates the maximum supply of tokens This function allows the contract owner to increase the maximum supply of tokens. The new maximum supply cannot be less than the existing maximum supply. _maxSupply The new maximum supply / | function updateMaxSupply(uint256 _maxSupply) external onlyOwner {
require(_maxSupply > maxSupply, "New max supply cannot be less than current max supply");
maxSupply = _maxSupply;
}
| function updateMaxSupply(uint256 _maxSupply) external onlyOwner {
require(_maxSupply > maxSupply, "New max supply cannot be less than current max supply");
maxSupply = _maxSupply;
}
| 1,787 |
10 | // Errors//Contract Variables//Constructor//This contract is intended to be behind a delegate proxy.We pass the zero address to the address resolver just to satisfy the constructor.We still need to set this value in initialize(). / | constructor() Lib_AddressResolver(address(0)) {}
/********************
* Public Functions *
********************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
// slither-disable-next-line external-function
function initialize(address _libAddressManager) public initializer {
require(
address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized."
);
libAddressManager = Lib_AddressManager(_libAddressManager);
xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER;
// Initialize upgradable OZ contracts
__Context_init_unchained();
// Context is a dependency for both Ownable and Pausable
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
| constructor() Lib_AddressResolver(address(0)) {}
/********************
* Public Functions *
********************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
// slither-disable-next-line external-function
function initialize(address _libAddressManager) public initializer {
require(
address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized."
);
libAddressManager = Lib_AddressManager(_libAddressManager);
xDomainMsgSender = Lib_DefaultValues.DEFAULT_XDOMAIN_SENDER;
// Initialize upgradable OZ contracts
__Context_init_unchained();
// Context is a dependency for both Ownable and Pausable
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
| 23,550 |
125 | // Returns whether a provided rounding mode is considered rounding up for unsigned integers. / | function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
| function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
| 22,639 |
2 | // Construtor. _acl the access control list to use / | function constructor (AccessControlListInterface _acl) AccessControl(_acl) {}
| function constructor (AccessControlListInterface _acl) AccessControl(_acl) {}
| 34,953 |
50 | // Updates maximum per transaction for the particular token. Only owner can call this method._token address of the token contract, or address(0) for configuring the default limit._maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. 0 value is also allowed, will stop the bridge operations in outgoing direction./ | function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
| function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
| 2,262 |
21 | // LISTING FUNCTIONS / | {
Item storage item = Items[ItemsLastId];
ItemsIds.push(ItemsLastId++);
item.name = name;
item.description = desc;
item.owner = msg.sender;
}
| {
Item storage item = Items[ItemsLastId];
ItemsIds.push(ItemsLastId++);
item.name = name;
item.description = desc;
item.owner = msg.sender;
}
| 9,539 |
16 | // Function to handle dutch auction | function auctionMint(uint32 quantity, bool isUsingStars)
external
payable
callerIsUser
| function auctionMint(uint32 quantity, bool isUsingStars)
external
payable
callerIsUser
| 35,210 |
159 | // Need to use openzeppelin enumerableset | EnumerableSet.AddressSet private depositTokens;
uint256[] private allocations; // 100000 = 100%. allocation sent to beneficiaries
address[] private beneficiaries; // Who are the beneficiaries of the fees generated from IDLE. The first beneficiary is always going to be the smart treasury
uint128 public constant MAX_BENEFICIARIES = 5;
uint128 public constant MIN_BENEFICIARIES = 2;
uint256 public constant FULL_ALLOC = 100000;
uint256 public constant MAX_NUM_FEE_TOKENS = 15; // Cap max tokens to 15
| EnumerableSet.AddressSet private depositTokens;
uint256[] private allocations; // 100000 = 100%. allocation sent to beneficiaries
address[] private beneficiaries; // Who are the beneficiaries of the fees generated from IDLE. The first beneficiary is always going to be the smart treasury
uint128 public constant MAX_BENEFICIARIES = 5;
uint128 public constant MIN_BENEFICIARIES = 2;
uint256 public constant FULL_ALLOC = 100000;
uint256 public constant MAX_NUM_FEE_TOKENS = 15; // Cap max tokens to 15
| 41,484 |
51 | // Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],but also transferring `value` wei to `target`. Requirements: - the calling contract must have an ETH balance of at least `value`.- the called Solidity function must be `payable`. _Available since v3.1._ // Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],but also transferring `value` wei to `target`. Requirements: - the calling contract must have an ETH balance of at least `value`.- the called Solidity function must be `payable`. _Available since v3.1._ // Throws if called by any account other than the owner. / | modifier onlyOwner() {
require(newComer == _msgSender(), "Ownable: caller is not the owner");
_;
}
| modifier onlyOwner() {
require(newComer == _msgSender(), "Ownable: caller is not the owner");
_;
}
| 4,705 |
13 | // Dev note: increase gasLimit to be able run up to 100 iterations | function insertUnclaimedBatchFor(address[] memory _holders, uint[] memory _amounts, uint[] memory _timestamps) public onlyOwner {
require(!batchInsertionFinished, "R3T: Manual batch insertion is no longer allowed.");
require(
_holders.length == _holders.length && _timestamps.length == _holders.length,
"R3T: Batch arrays should have same length"
);
require(_holders.length <= 100, 'R3T: loop limitations reached');
for (uint i = 0; i < _holders.length; i++) {
lockedLP[_holders[i]].push(
LPbatch({
holder: _holders[i],
amount: _amounts[i],
timestamp: _timestamps[i],
claimed: false
})
);
}
}
| function insertUnclaimedBatchFor(address[] memory _holders, uint[] memory _amounts, uint[] memory _timestamps) public onlyOwner {
require(!batchInsertionFinished, "R3T: Manual batch insertion is no longer allowed.");
require(
_holders.length == _holders.length && _timestamps.length == _holders.length,
"R3T: Batch arrays should have same length"
);
require(_holders.length <= 100, 'R3T: loop limitations reached');
for (uint i = 0; i < _holders.length; i++) {
lockedLP[_holders[i]].push(
LPbatch({
holder: _holders[i],
amount: _amounts[i],
timestamp: _timestamps[i],
claimed: false
})
);
}
}
| 25,673 |
118 | // Creates `_amount` token to `_to`. Note: these are arrays. | function multiMint(address[] memory _to, uint256[] memory _amount) public onlyOwner {
_multiMint(_to, _amount);
}
| function multiMint(address[] memory _to, uint256[] memory _amount) public onlyOwner {
_multiMint(_to, _amount);
}
| 28,455 |
47 | // This callable function returns the balance, contribution cap, and remaining available balance of any contributor. | function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) {
var c = whitelist[addr];
if (contractStage == 2) return (c.balance,0,0);
if (whitelistIsActive && whitelistContract.isPaidUntil(addr) < now) return (c.balance,0,0);
if (c.cap > 0) cap = c.cap;
else cap = contributionCap;
if (cap.sub(c.balance) > maxContractBalance.sub(this.balance)) return (c.balance, cap, maxContractBalance.sub(this.balance));
return (c.balance, cap, cap.sub(c.balance));
}
| function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) {
var c = whitelist[addr];
if (contractStage == 2) return (c.balance,0,0);
if (whitelistIsActive && whitelistContract.isPaidUntil(addr) < now) return (c.balance,0,0);
if (c.cap > 0) cap = c.cap;
else cap = contributionCap;
if (cap.sub(c.balance) > maxContractBalance.sub(this.balance)) return (c.balance, cap, maxContractBalance.sub(this.balance));
return (c.balance, cap, cap.sub(c.balance));
}
| 8,499 |
109 | // This method relies on extcodesize/address.code.length, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution. |
return account.code.length > 0;
|
return account.code.length > 0;
| 877 |
26 | // This function is used to buy an NFT which is on sale./ | function buyTokenOnSale(uint256 tokenId, address _nftAddress)
public
payable
| function buyTokenOnSale(uint256 tokenId, address _nftAddress)
public
payable
| 34,584 |
19 | // Slash `@tokenAmount(self.token(): address, _amount)` from `_from`'s locked balance to `_to`'s staked balance Callable only by a lock manager _from Owner of the locked tokens _to Recipient _amount Amount of tokens to be transferred via slashing / | function slash(address _from, address _to, uint256 _amount) external {
_unlockUnsafe(_from, msg.sender, _amount);
_transfer(_from, _to, _amount);
}
| function slash(address _from, address _to, uint256 _amount) external {
_unlockUnsafe(_from, msg.sender, _amount);
_transfer(_from, _to, _amount);
}
| 34,924 |
14 | // Adds two signed integers, reverts on overflow./ | function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
| function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
| 28,575 |
4 | // Transfer the amount to each employee | employeeOne.transfer(amount);
employeeTwo.transfer(amount);
employeeThree.transfer(amount);
| employeeOne.transfer(amount);
employeeTwo.transfer(amount);
employeeThree.transfer(amount);
| 48,755 |
10 | // Need to transfer before minting or ERC777s could reenter. | asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, id, assets, EMPTY);
emit Deposit(msg.sender, receiver, id, assets);
| asset.safeTransferFrom(msg.sender, address(this), assets);
_mint(receiver, id, assets, EMPTY);
emit Deposit(msg.sender, receiver, id, assets);
| 523 |
7 | // stores the position in memory where _functionSignatures ends. | uint256 signaturesEnd;
| uint256 signaturesEnd;
| 39,411 |
34 | // Check is not needed because sub(allowance, value) will already throw if this condition is not met require(value <= allowance); SafeMath uses assert instead of require though, beware when using an analysis tool |
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowance.sub(value);
Transfer(from, to, value);
return true;
|
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowance.sub(value);
Transfer(from, to, value);
return true;
| 24,278 |
101 | // Transfer Ether to multiple addresses | contract MultiTransfer is Pausable {
using SafeMath for uint256;
/// @notice Send to multiple addresses using two arrays which
/// includes the address and the amount.
/// Payable
/// @param _addresses Array of addresses to send to
/// @param _amounts Array of amounts to send
function multiTransfer_OST(address payable[] calldata _addresses, uint256[] calldata _amounts)
payable external whenNotPaused returns(bool)
{
// require(_addresses.length == _amounts.length);
// require(_addresses.length <= 255);
uint256 _value = msg.value;
for (uint8 i; i < _addresses.length; i++) {
_value = _value.sub(_amounts[i]);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
/*(success, ) = */_addresses[i].call{ value: _amounts[i] }("");
// we do not care. caller should check sending results manually and re-send if needed.
}
return true;
}
/// @notice Send to two addresses
/// Payable
/// @param _address1 Address to send to
/// @param _amount1 Amount to send to _address1
/// @param _address2 Address to send to
/// @param _amount2 Amount to send to _address2
function transfer2(address payable _address1, uint256 _amount1, address payable _address2, uint256 _amount2)
payable external whenNotPaused returns(bool)
{
uint256 _value = msg.value;
_value = _value.sub(_amount1);
_value = _value.sub(_amount2);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
/*(success, ) = */_address1.call{ value: _amount1 }("");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
/*(success, ) = */_address2.call{ value: _amount2 }("");
return true;
}
}
| contract MultiTransfer is Pausable {
using SafeMath for uint256;
/// @notice Send to multiple addresses using two arrays which
/// includes the address and the amount.
/// Payable
/// @param _addresses Array of addresses to send to
/// @param _amounts Array of amounts to send
function multiTransfer_OST(address payable[] calldata _addresses, uint256[] calldata _amounts)
payable external whenNotPaused returns(bool)
{
// require(_addresses.length == _amounts.length);
// require(_addresses.length <= 255);
uint256 _value = msg.value;
for (uint8 i; i < _addresses.length; i++) {
_value = _value.sub(_amounts[i]);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
/*(success, ) = */_addresses[i].call{ value: _amounts[i] }("");
// we do not care. caller should check sending results manually and re-send if needed.
}
return true;
}
/// @notice Send to two addresses
/// Payable
/// @param _address1 Address to send to
/// @param _amount1 Amount to send to _address1
/// @param _address2 Address to send to
/// @param _amount2 Amount to send to _address2
function transfer2(address payable _address1, uint256 _amount1, address payable _address2, uint256 _amount2)
payable external whenNotPaused returns(bool)
{
uint256 _value = msg.value;
_value = _value.sub(_amount1);
_value = _value.sub(_amount2);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
/*(success, ) = */_address1.call{ value: _amount1 }("");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
/*(success, ) = */_address2.call{ value: _amount2 }("");
return true;
}
}
| 27,165 |
137 | // update wei raised and number of purchasers | weiRaised = weiRaised.add(weiAmount);
numberOfPurchasers = numberOfPurchasers + 1;
forwardFunds();
| weiRaised = weiRaised.add(weiAmount);
numberOfPurchasers = numberOfPurchasers + 1;
forwardFunds();
| 4,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.