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 |
|---|---|---|---|---|
3 | // Returns the rebuilt hash obtained by traversing a Merkle tree upfrom `leaf` using `proof`. A `proof` is valid if and only if the rebuilthash matches the root of the tree. When processing the proof, the pairsof leafs & pre-images are assumed to be sorted. / | function processProof(
bytes32[] memory proof,
bytes32 leaf
| function processProof(
bytes32[] memory proof,
bytes32 leaf
| 25,740 |
47 | // Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow. / | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| 11,089 |
44 | // zero<64>|msg<var>|lib_str<2>|I2OSP(0, 1)<1>|dst<var>|dst_len<1> | uint256 t0 = message.length;
bytes memory msg0 = new bytes(32 + t0 + 64 + 4);
bytes memory out = new bytes(96);
| uint256 t0 = message.length;
bytes memory msg0 = new bytes(32 + t0 + 64 + 4);
bytes memory out = new bytes(96);
| 17,409 |
10 | // Add a historically significant event (i.e. maintenance, damage repair or new owner). / | function addEvent(uint256 _mileage,
uint256 _repairOrderNumber,
EventType _eventType,
string _description,
| function addEvent(uint256 _mileage,
uint256 _repairOrderNumber,
EventType _eventType,
string _description,
| 28,585 |
7 | // require(block.timestamp > startTime, "TokenPresale: sale not started"); require(block.timestamp < endTime, "TokenPresale: sale has ended"); | require(
msg.value >= minimumInvestment,
"TokenPresale: value must be above minimum investment"
);
require(
msg.value <= maximumInvestment,
"TokenPresale: value must be below maximum investment"
);
require(
| require(
msg.value >= minimumInvestment,
"TokenPresale: value must be above minimum investment"
);
require(
msg.value <= maximumInvestment,
"TokenPresale: value must be below maximum investment"
);
require(
| 39,123 |
3 | // swap from token0 to token1 | swapAmount = getSwapAmount(reserve0, _amountA);
| swapAmount = getSwapAmount(reserve0, _amountA);
| 3,375 |
13 | // NOTE: Now that we have the struct hash, compute the EIP-712 signing hash using scratch memory past the free memory pointer. The signing hash is computed from `"\x19\x01" || domainSeparator || structHash`. <https:docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.htmllayout-in-memory> <https:github.com/ethereum/EIPs/blob/master/EIPS/eip-712.mdspecification> solhint-disable-next-line no-inline-assembly | assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, "\x19\x01")
mstore(add(freeMemoryPointer, 2), domainSeparator)
mstore(add(freeMemoryPointer, 34), structHash)
orderDigest := keccak256(freeMemoryPointer, 66)
}
| assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, "\x19\x01")
mstore(add(freeMemoryPointer, 2), domainSeparator)
mstore(add(freeMemoryPointer, 34), structHash)
orderDigest := keccak256(freeMemoryPointer, 66)
}
| 30,155 |
609 | // Use 100 wei less OUSD then given - TO REMOVE | uint256 allowedLeverageNoArchLimit = getAllowedLeverageForPosition(principle, numberOfCycles);
uint256 allowedLeverageWithGivenArch = calculateLeverageAllowedForArch(archAmount);
| uint256 allowedLeverageNoArchLimit = getAllowedLeverageForPosition(principle, numberOfCycles);
uint256 allowedLeverageWithGivenArch = calculateLeverageAllowedForArch(archAmount);
| 9,182 |
26 | // Reads the entire content of file to string | function readFile(string calldata path) external view returns (string memory data);
| function readFile(string calldata path) external view returns (string memory data);
| 3,982 |
81 | // Setting the Cap per Sport ID/_sportID The tagID used for sport (9004)/_childID The tagID used for childid (10002)/_capPerChild The cap amount used for the sportID | function setCapPerSportAndChild(
uint _sportID,
uint _childID,
uint _capPerChild
| function setCapPerSportAndChild(
uint _sportID,
uint _childID,
uint _capPerChild
| 12,906 |
170 | // Maximum input tokens balance ratio for swaps. | uint public constant MAX_IN_RATIO = BONE / 2;
| uint public constant MAX_IN_RATIO = BONE / 2;
| 23,142 |
244 | // Helper to unstake LP tokens | function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal {
ICurveLiquidityGaugeV2(_gauge).withdraw(_amount);
}
| function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal {
ICurveLiquidityGaugeV2(_gauge).withdraw(_amount);
}
| 52,523 |
163 | // Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range/Snapshots must only be compared to other snapshots, taken over a period for which a position existed./ I.e., snapshots cannot be compared if a position is not held for the entire period between when the first/ snapshot is taken and the second snapshot is taken./tickLower The lower tick of the range/tickUpper The upper tick of the range/ return tickCumulativeInside The snapshot of the tick accumulator for the range/ return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range/ return secondsInside The snapshot of seconds | function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
| function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
| 23,376 |
17 | // Update shareholderIndexes mapping to point to new shareholder | _shareholderIndexes[replacementShareholder] = _shareholderIndexes[removing];
| _shareholderIndexes[replacementShareholder] = _shareholderIndexes[removing];
| 26,582 |
8 | // only allow an approve on the underlying | return (method == ERC20_APPROVE && underlying == _to);
| return (method == ERC20_APPROVE && underlying == _to);
| 41,191 |
62 | // Ignore if the tokenInDestination is address(0). | if (swapAggregatorMulticall.tokenInDestination != address(0)) {
| if (swapAggregatorMulticall.tokenInDestination != address(0)) {
| 7,446 |
100 | // If goal is Reached then change to change to ICO Stageetc.) _beneficiary Address receiving the tokens _weiAmount Value in wei involved in the purchase / | function _updatePurchasingState(address _beneficiary, uint256 _weiAmount)
internal virtual override
| function _updatePurchasingState(address _beneficiary, uint256 _weiAmount)
internal virtual override
| 38,098 |
156 | // Returns the next element in the iteration. Reverts if it has not next element.self The iterator. return The next element in the iteration./ | function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
| function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
| 60,167 |
84 | // Sets up core blueprint parameters _baseTokenUri Base token uri for blueprint _metadataUri Metadata uri for blueprint _isSoulbound Denotes if tokens minted on blueprint are non-transferable / | function _setupBlueprint(string memory _baseTokenUri, string memory _metadataUri, bool _isSoulbound) private {
blueprint.baseTokenUri = _baseTokenUri;
blueprint.blueprintMetadata = _metadataUri;
if (_isSoulbound) {
blueprint.isSoulbound = _isSoulbound;
}
}
| function _setupBlueprint(string memory _baseTokenUri, string memory _metadataUri, bool _isSoulbound) private {
blueprint.baseTokenUri = _baseTokenUri;
blueprint.blueprintMetadata = _metadataUri;
if (_isSoulbound) {
blueprint.isSoulbound = _isSoulbound;
}
}
| 35,894 |
34 | // This function is a new creation to help bridge the gap between the sablierfunctionality and the ERC20 standard./ | function updateStream(uint streamId) public streamExists(streamId) {
Stream storage stream = streams[streamId];
uint streamedBalance = _getStreamSentBalance(streamId);
stream.remainingBalance = stream.remainingBalance.sub(streamedBalance);
_balances[stream.sender] = _balances[stream.sender].sub(streamedBalance);
_balances[stream.recipient] = _balances[stream.recipient].add(streamedBalance);
/*
* these lines only used if streams to/from 0x0 are allowed
* in the current rev, they are not - so they are commented out
*
if(stream.sender == address(0)) _totalSupply = _totalSupply.add(streamedBalance);
if(stream.recipient == address(0)) _totalSupply = _totalSupply.sub(streamedBalance);
*
*/
emit Transfer(stream.sender, stream.recipient, streamedBalance);
if (stream.remainingBalance == 0){
_killStream(streamId);
}
}
| function updateStream(uint streamId) public streamExists(streamId) {
Stream storage stream = streams[streamId];
uint streamedBalance = _getStreamSentBalance(streamId);
stream.remainingBalance = stream.remainingBalance.sub(streamedBalance);
_balances[stream.sender] = _balances[stream.sender].sub(streamedBalance);
_balances[stream.recipient] = _balances[stream.recipient].add(streamedBalance);
/*
* these lines only used if streams to/from 0x0 are allowed
* in the current rev, they are not - so they are commented out
*
if(stream.sender == address(0)) _totalSupply = _totalSupply.add(streamedBalance);
if(stream.recipient == address(0)) _totalSupply = _totalSupply.sub(streamedBalance);
*
*/
emit Transfer(stream.sender, stream.recipient, streamedBalance);
if (stream.remainingBalance == 0){
_killStream(streamId);
}
}
| 4,256 |
118 | // ======== admin functions =========/admin function to pause the contract | function pause() public onlyOwner{
_pause();
}
| function pause() public onlyOwner{
_pause();
}
| 20,043 |
49 | // Math: If this value got too large, the DAT may overflow on sell | require(totalSupply.add(burnedSupply) <= MAX_SUPPLY, "EXCESSIVE_SUPPLY");
| require(totalSupply.add(burnedSupply) <= MAX_SUPPLY, "EXCESSIVE_SUPPLY");
| 4,206 |
56 | // Returns the value of the `string` type that mapped to the given key. / | function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
| function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
| 19,262 |
7 | // Fee collector address where fees will be deposited | address public override feeCollector;
| address public override feeCollector;
| 32,216 |
74 | // Returns a token ID owned by owner at a given index of its token list. | * Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| * Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| 33,330 |
41 | // Returns the index of a reporter timestamp in the timestamp array for a specific data ID _queryId is ID of the specific data feed _timestamp is the timestamp to find in the timestamps arrayreturn uint256 of the index of the reporter timestamp in the array for specific ID / | function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (uint256)
| function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (uint256)
| 58,667 |
184 | // Compute the line of credit the Vault is able to offer the Strategy (if any) | uint256 credit = _strategyCreditAvailable(msg.sender);
| uint256 credit = _strategyCreditAvailable(msg.sender);
| 68,266 |
407 | // ==============================================================================(~ ___._|_._)(/_(_|_|| | | \/.====================/=========================================================/ upon contract deploy, it will be deactivated.this is a one timeuse function that will activate the contract.we do this so devshave time to set things up on the web end/ | {
// only team just can activate
require(msg.sender == admin, "only admin can activate");
// can only be ran once
require(activated_ == false, "FOMO Short already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
| {
// only team just can activate
require(msg.sender == admin, "only admin can activate");
// can only be ran once
require(activated_ == false, "FOMO Short already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
| 70,230 |
17 | // query if the non-reentrancy guard for send() is on return true if the guard is on. false otherwise | function isSendingPayload() external view returns (bool);
| function isSendingPayload() external view returns (bool);
| 6,779 |
3 | // allow an address to access contract's methods | function allowAccess(address _address) onlyIfAllowed public {
accessAllowed[_address] = true;
}
| function allowAccess(address _address) onlyIfAllowed public {
accessAllowed[_address] = true;
}
| 6,079 |
15 | // The local address that is custodying relayer fees / 2 | address relayerFeeVault;
| address relayerFeeVault;
| 30,187 |
81 | // Check if adjustments are forbidden or not | require(stopAdjustments == 0, "AutoSurplusBufferSetter/cannot-adjust");
| require(stopAdjustments == 0, "AutoSurplusBufferSetter/cannot-adjust");
| 47,845 |
2 | // if(cap + msg.value > cap_max) throw; |
tokens_total = msg.value*10**18/token_price;
if(!(tokens_total > 0)) throw;
if(!contract_transfer(tokens_total)) throw;
cap = cap.add(msg.value);
operations();
get_card();
owner.send(this.balance);
|
tokens_total = msg.value*10**18/token_price;
if(!(tokens_total > 0)) throw;
if(!contract_transfer(tokens_total)) throw;
cap = cap.add(msg.value);
operations();
get_card();
owner.send(this.balance);
| 28,089 |
29 | // Token allowance mapping. / | mapping (address => mapping (address => uint256)) internal allowed;
| mapping (address => mapping (address => uint256)) internal allowed;
| 15,029 |
7 | // 租客陣列 | Tenant[] public tenants;
| Tenant[] public tenants;
| 6,546 |
134 | // We assume that the token contract is correct. This contract is not written to handle misbehaving ERC20 tokens! | LinkTokenInterface internal s_linkToken;
AccessControllerInterface internal s_billingAccessController;
| LinkTokenInterface internal s_linkToken;
AccessControllerInterface internal s_billingAccessController;
| 13,882 |
54 | // Contracts that should not own Ether Remco Bloemen <remco@2π.com> This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end upin the contract, it will allow the owner to reclaim this ether. Ether can still be sent to this contract by:calling functions labeled `payable``selfdestruct(contract_address)`mining directly to the contract address / | contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
| contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
| 21,078 |
5 | // Get rewards from farm | _claimRewards();
| _claimRewards();
| 44,176 |
28 | // Returns true if `account` is a contract. [IMPORTANT] ==== It is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the following types of addresses:- an externally-owned account- a contract in construction- an address where a contract will be created- an address where a contract lived, but was destroyed ====/ | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| 4,386 |
1 | // ! "entry": "ascending",! "expected": 1 | //! }, {
//! "entry": "descending",
//! "expected": 1
//! } ] }
| //! }, {
//! "entry": "descending",
//! "expected": 1
//! } ] }
| 47,847 |
56 | // XfLobbyEnter(auto-generated event)/ | event XfLobbyEnter(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
| event XfLobbyEnter(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
| 11,016 |
8 | // Hard cap on the minimum time between changing the token supply | uint32 public constant supplyChangeWaitingPeriodMinimum = 1 days * 90;
| uint32 public constant supplyChangeWaitingPeriodMinimum = 1 days * 90;
| 39,901 |
10 | // Address for receiving tokens. / | address public withdrawAddress;
| address public withdrawAddress;
| 32,634 |
34 | // Public function that allows a relayer to create any contract on behalf of the owner data new contract bytecode fee Fee paid to the relayer tokenContract Address of the token contract used for the fee deadline Block number deadline for this signed message / | function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate", msg.sender, tokenContract, data, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
require(_execCreate(data));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
return true;
}
| function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate", msg.sender, tokenContract, data, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
require(_execCreate(data));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
return true;
}
| 7,635 |
0 | // Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then bequeried by others (`ERC165Checker`). For an implementation, see `ERC165`. / | interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| 8,798 |
40 | // Checks if the bond is listed./bond The bond to make the check against./ return bool true = listed, otherwise not. | function isBondListed(IHToken bond) external view returns (bool);
| function isBondListed(IHToken bond) external view returns (bool);
| 51,625 |
43 | // Create a collection of mint passes _name Name of the collection _collectionType Type of collection _cost Cost per pass _uri URI of collection _remaingMintCount Number of passes remaining available to mint _artistPayablePercent Percent of collection funds that go to artist _artistPayableAddress Artist wallet that receives percentage of funds / | function createCollection (bytes32 _name, uint16 _collectionType, uint256 _cost, string memory _uri, uint256 _remaingMintCount, uint16 _artistPayablePercent, address _artistPayableAddress) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to create collection");
Collection storage newCol = collections[numCollections++];
newCol.name = _name;
newCol.collectionType = _collectionType;
newCol.uri = _uri;
newCol.cost = _cost;
newCol.totalMintCount = _remaingMintCount;
newCol.remaingMintCount = _remaingMintCount;
newCol.mintPassOpenToPublic = false;
newCol.mintNftOpenToPublic = false;
newCol.artistPayablePercent = _artistPayablePercent;
newCol.artistPayableAddress = _artistPayableAddress;
newCol.nftContractAddress = 0x0000000000000000000000000000000000000000;
}
| function createCollection (bytes32 _name, uint16 _collectionType, uint256 _cost, string memory _uri, uint256 _remaingMintCount, uint16 _artistPayablePercent, address _artistPayableAddress) public {
require(hasRole(MINTER_ROLE, _msgSender()), "AP: must have minter role to create collection");
Collection storage newCol = collections[numCollections++];
newCol.name = _name;
newCol.collectionType = _collectionType;
newCol.uri = _uri;
newCol.cost = _cost;
newCol.totalMintCount = _remaingMintCount;
newCol.remaingMintCount = _remaingMintCount;
newCol.mintPassOpenToPublic = false;
newCol.mintNftOpenToPublic = false;
newCol.artistPayablePercent = _artistPayablePercent;
newCol.artistPayableAddress = _artistPayableAddress;
newCol.nftContractAddress = 0x0000000000000000000000000000000000000000;
}
| 6,851 |
2 | // Subtract the already payed commission and return | return (currentCommission - paidCommission) / x;
| return (currentCommission - paidCommission) / x;
| 38,939 |
19 | // genQueenNodes Generate queen nodes to select winners / | function genQueenNodes() private {
queenNodes = getQueenNodes();
}
| function genQueenNodes() private {
queenNodes = getQueenNodes();
}
| 36,001 |
0 | // Emitted when the observed liquidities are validated against user (updater) provided liquidities. token The token that the liquidity validation is for. observedTokenLiquidity The observed token liquidity from the on-chain data source. observedQuoteTokenLiquidity The observed quote token liquidity from the on-chain data source. providedTokenLiquidity The token liquidity provided externally by the user (updater). providedQuoteTokenLiquidity The quote token liquidity provided externally by the user (updater). timestamp The timestamp of the block that the validation was performed in. succeeded True if the observed liquidities closely matches the provided liquidities; false otherwise. / | event ValidationPerformed(
address indexed token,
uint256 observedTokenLiquidity,
uint256 observedQuoteTokenLiquidity,
uint256 providedTokenLiquidity,
uint256 providedQuoteTokenLiquidity,
uint256 timestamp,
bool succeeded
);
| event ValidationPerformed(
address indexed token,
uint256 observedTokenLiquidity,
uint256 observedQuoteTokenLiquidity,
uint256 providedTokenLiquidity,
uint256 providedQuoteTokenLiquidity,
uint256 timestamp,
bool succeeded
);
| 3,682 |
195 | // remove Global Constraint _globalConstraint the address of the global constraint to be remove.return bool which represents a success /solhint-disable-next-line code-complexity | function removeGlobalConstraint (address _globalConstraint, address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
| function removeGlobalConstraint (address _globalConstraint, address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
| 24,099 |
123 | // check that the investor (payee) gives back all tokens bought during ICO | require(m_token.allowance(payee, this) >= m_tokenBalances[payee]);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
m_tokenBalances[payee] = 0;
m_token.transferFrom(payee, this, tokens);
payee.transfer(payment);
RefundSent(payee, payment);
| require(m_token.allowance(payee, this) >= m_tokenBalances[payee]);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
m_tokenBalances[payee] = 0;
m_token.transferFrom(payee, this, tokens);
payee.transfer(payment);
RefundSent(payee, payment);
| 56,685 |
36 | // Sell `amount` tokens to contract/amount amount of tokens to be sold | function sell(uint256 amount) public {
address myAddress = address(this);
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, address(this), amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
| function sell(uint256 amount) public {
address myAddress = address(this);
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, address(this), amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
| 49,090 |
279 | // Set the Staking address Only callable by Governance address _stakingAddress - address for new Staking contract / | function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
| function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
| 41,235 |
44 | // mask = betMask; | bet.mask = uint40(betMask);
| bet.mask = uint40(betMask);
| 17,778 |
41 | // calculating interest amount; | uint interestAmount = (data[_tokenId].holdings*data[_tokenId].interest)*(now - data[_tokenId].time)/(100*31536000*1000000);
| uint interestAmount = (data[_tokenId].holdings*data[_tokenId].interest)*(now - data[_tokenId].time)/(100*31536000*1000000);
| 7,560 |
166 | // Update the swap router.Can only be called by the current operator. / | function updateuniSwapRouter(address _router) public onlyOperator {
uniSwapRouter = IUniswapV2Router02(_router);
uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH());
require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address.");
emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair);
}
| function updateuniSwapRouter(address _router) public onlyOperator {
uniSwapRouter = IUniswapV2Router02(_router);
uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH());
require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address.");
emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair);
}
| 7,901 |
1 | // Whether staking is currently allowed. If false, token owners are unable to stake / | bool public vault_stakingAllowed = false;
| bool public vault_stakingAllowed = false;
| 10,966 |
8 | // ---------------------------------------------------------------------------- Contract function to receive approval and execute function in one call ---------------------------------------------------------------------------- | contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
| contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
| 6,663 |
191 | // compressedData key [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] 0 - new player (bool) 1 - joined round (bool) 2 - newleader (bool) 3-5 - air drop tracker (uint 0-999) 6-16 - round end time 17 - winnerTeam 18 - 28 timestamp 29 - team 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) 31 - airdrop happened bool 32 - airdrop tier 33 - airdrop amount woncompressedIDs key [77-52][51-26][25-0] 0-25 - pID 26-51 - winPID 52-77 - rID | // struct EventReturns {
// uint256 compressedData;
// uint256 compressedIDs;
// address winnerAddr; // winner address
// bytes32 winnerName; // winner name
// uint256 amountWonCosd; // amount won
// uint256 amountWonCosc; // amount won
// }
| // struct EventReturns {
// uint256 compressedData;
// uint256 compressedIDs;
// address winnerAddr; // winner address
// bytes32 winnerName; // winner name
// uint256 amountWonCosd; // amount won
// uint256 amountWonCosc; // amount won
// }
| 39,816 |
2,025 | // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. | function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
| function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
| 22,066 |
51 | // boolean value if minting is finished of not | bool public mintingIsFinished;
| bool public mintingIsFinished;
| 23,035 |
517 | // verify that sender is a pool registered withing the factory | require(poolExists[msg.sender], "access denied");
| require(poolExists[msg.sender], "access denied");
| 50,847 |
39 | // Needed for 'stack too deep' issues in _checkpoint() addr User's wallet address. No user checkpoint if 0x0 _bias from unew _slope from unew / | function _checkpoint_part_two(address addr, int128 _bias, int128 _slope) internal {
uint256 user_epoch = user_point_epoch[addr] + 1;
user_point_epoch[addr] = user_epoch;
user_point_history[addr][user_epoch] = Point({bias: _bias, slope: _slope, ts: block.timestamp, blk: block.number});
}
| function _checkpoint_part_two(address addr, int128 _bias, int128 _slope) internal {
uint256 user_epoch = user_point_epoch[addr] + 1;
user_point_epoch[addr] = user_epoch;
user_point_history[addr][user_epoch] = Point({bias: _bias, slope: _slope, ts: block.timestamp, blk: block.number});
}
| 29,174 |
42 | // True if the pair on Uniswap is defined as ETH / X | bool isUniswapReversed;
| bool isUniswapReversed;
| 13,838 |
7 | // Safely transfers `id` tokens from `from` to many `to` addresses. | /// @dev See {ERC721.safeTransferFrom}.
/// @param from The address to transfer from.
/// @param to The addresses to transfer to.
/// @param ids The token IDs to transfer.
/// @param data The data to callback with.
function batchSafeTransferFrom(
address from,
address[] calldata to,
uint256[] calldata ids,
bytes calldata data
) public virtual {
unchecked {
uint256 length = ids.length;
for (uint256 i; i < length; i++) {
safeTransferFrom(from, to[i], ids[i], data);
}
}
}
| /// @dev See {ERC721.safeTransferFrom}.
/// @param from The address to transfer from.
/// @param to The addresses to transfer to.
/// @param ids The token IDs to transfer.
/// @param data The data to callback with.
function batchSafeTransferFrom(
address from,
address[] calldata to,
uint256[] calldata ids,
bytes calldata data
) public virtual {
unchecked {
uint256 length = ids.length;
for (uint256 i; i < length; i++) {
safeTransferFrom(from, to[i], ids[i], data);
}
}
}
| 46,573 |
8 | // Privileged function to de authorize an address/who The address to remove authorization from | function deauthorize(address who) external onlyOwner {
authorized[who] = false;
}
| function deauthorize(address who) external onlyOwner {
authorized[who] = false;
}
| 21,165 |
152 | // CryptoPunks. Fix here for frontrun attack. Added in v1.0.2. | bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId);
(bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress);
(address owner) = abi.decode(result, (address));
require(checkSuccess && owner == msg.sender, "Not the owner");
data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
| bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId);
(bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress);
(address owner) = abi.decode(result, (address));
require(checkSuccess && owner == msg.sender, "Not the owner");
data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
| 31,689 |
5 | // ПОКУШАВШИЙ ЩЕРБЕТА | if context { ПРИЛАГАТЕЛЬНОЕ:*{ ПРИЧАСТИЕ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПадежВал:РОД }#a СУЩЕСТВИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } #b }
| if context { ПРИЛАГАТЕЛЬНОЕ:*{ ПРИЧАСТИЕ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПадежВал:РОД }#a СУЩЕСТВИТЕЛЬНОЕ:* { ПАДЕЖ:РОД } #b }
| 32,934 |
295 | // MathUtils Library A collection of functions to perform math operations / | library MathUtils {
using SafeMath for uint256;
/**
* @dev Calculates the weighted average of two values pondering each of these
* values based on configured weights. The contribution of each value N is
* weightN/(weightA + weightB).
* @param valueA The amount for value A
* @param weightA The weight to use for value A
* @param valueB The amount for value B
* @param weightB The weight to use for value B
*/
function weightedAverage(
uint256 valueA,
uint256 weightA,
uint256 valueB,
uint256 weightB
) internal pure returns (uint256) {
return valueA.mul(weightA).add(valueB.mul(weightB)).div(weightA.add(weightB));
}
/**
* @dev Returns the minimum of two numbers.
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x <= y ? x : y;
}
/**
* @dev Returns the difference between two numbers or zero if negative.
*/
function diffOrZero(uint256 x, uint256 y) internal pure returns (uint256) {
return (x > y) ? x.sub(y) : 0;
}
}
| library MathUtils {
using SafeMath for uint256;
/**
* @dev Calculates the weighted average of two values pondering each of these
* values based on configured weights. The contribution of each value N is
* weightN/(weightA + weightB).
* @param valueA The amount for value A
* @param weightA The weight to use for value A
* @param valueB The amount for value B
* @param weightB The weight to use for value B
*/
function weightedAverage(
uint256 valueA,
uint256 weightA,
uint256 valueB,
uint256 weightB
) internal pure returns (uint256) {
return valueA.mul(weightA).add(valueB.mul(weightB)).div(weightA.add(weightB));
}
/**
* @dev Returns the minimum of two numbers.
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x <= y ? x : y;
}
/**
* @dev Returns the difference between two numbers or zero if negative.
*/
function diffOrZero(uint256 x, uint256 y) internal pure returns (uint256) {
return (x > y) ? x.sub(y) : 0;
}
}
| 22,992 |
13 | // Ensure the sender has not already withdraw during the current period | require(senderHasWithdraw[currentPeriodKey] == false, "once / period");
| require(senderHasWithdraw[currentPeriodKey] == false, "once / period");
| 30,923 |
78 | // Proportion of the liquidity pool to give to current liquidity provider If rounding error occured, round down to favor previous liquidity providers See https:github.com/0xsequence/niftyswap/issues/19 | liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve;
currencyAmounts[i] = currencyAmount;
| liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve;
currencyAmounts[i] = currencyAmount;
| 34,935 |
42 | // assign locked token to Vesting contract | if (lockedTokenAmount > 0) {
tokenVesting = TokenVesting(tokenVestingAddress);
| if (lockedTokenAmount > 0) {
tokenVesting = TokenVesting(tokenVestingAddress);
| 4,648 |
83 | // The damage formula is [[strength / gas + power / (10rand)]], where rand is a random integer from 1 to 5. | uint damageByHero = (_heroStrength + heroPower / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice / 1e9;
bool isMonsterDefeated = damageByHero >= monster.health;
uint rewards;
if (isMonsterDefeated) {
| uint damageByHero = (_heroStrength + heroPower / (10 * (1 + _getRandomNumber(5)))) / tx.gasprice / 1e9;
bool isMonsterDefeated = damageByHero >= monster.health;
uint rewards;
if (isMonsterDefeated) {
| 71,481 |
9 | // Buy all the tokens the contract can afford | uint[] memory amounts = uniswapRouter.swapExactETHForTokens{value: address(this).balance}(_amountOutMin, path, address(this), _deadline);
| uint[] memory amounts = uniswapRouter.swapExactETHForTokens{value: address(this).balance}(_amountOutMin, path, address(this), _deadline);
| 38,149 |
1 | // amount of Nmx has been distributed or sold already at the moment of contract deployment | uint256 alreadyDistributedAmount = 7505656;
| uint256 alreadyDistributedAmount = 7505656;
| 37,660 |
0 | // Events of the contract | event TokenAdded(address token);
event TokenRemoved(address token);
| event TokenAdded(address token);
event TokenRemoved(address token);
| 60,246 |
22 | // Function to check the amount of tokens that an owner allowed to a spender. owner address The address which owns the funds. spender address The address which will spend the funds.return A uint256 specifying the amount of tokens still available for the spender. / | function allowance(address owner, address spender) public view override returns (uint256) {
return _allowed[owner][spender];
}
| function allowance(address owner, address spender) public view override returns (uint256) {
return _allowed[owner][spender];
}
| 2,923 |
66 | // Read and consume the next 16 bytes from the buffer as an `uint128`./_buffer An instance of `Witnet.Buffer`./ return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position. | function readUint128(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
| function readUint128(Witnet.Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
| 82,246 |
93 | // adds or replaces existing proxy module/target target proxy module address | function replaceContract(address target) external;
| function replaceContract(address target) external;
| 4,293 |
67 | // TokenVesting A token holder contract that can release its token balance gradually like atypical vesting scheme, with a cliff and vesting period. Optionally revocable by theowner. / | contract CommTokenVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _cliff;
uint256 private _start;
uint256 private _duration;
bool private _revocable;
// non-linear params times 10^8
uint256 private _immedReleasedAmount;
uint256 private _dailyReleasedAmount;
uint256 private _isNLReleasable;
uint256 private _dailyReleasedNLAmount;
uint256 private _durationInDays;
uint256 constant oneHundredMillion = 100000000;
uint256 constant secondsPerDay = 86400;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param immedReleasedAmount non-liner unlock param
* @param dailyReleasedAmount non-liner unlock param
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, uint256 immedReleasedAmount, uint256 dailyReleasedAmount, bool revocable) public {
require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address");
require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration");
require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time");
require(duration >= secondsPerDay, "TokenVesting: duration must be over a day at least.");
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
_durationInDays = duration.div(secondsPerDay);
require(immedReleasedAmount <= oneHundredMillion, "TokenVesting: immedReleasedAmount is larger than 100000000.");
require(dailyReleasedAmount.mul(_durationInDays) <= oneHundredMillion, "TokenVesting: dailyReleasedAmount*_durationInDays is larger than 100000000.");
_immedReleasedAmount = immedReleasedAmount;
_dailyReleasedAmount = dailyReleasedAmount;
_isNLReleasable = oneHundredMillion.sub(_immedReleasedAmount).sub(_durationInDays.mul(_dailyReleasedAmount));
_dailyReleasedNLAmount = _isNLReleasable.div(_durationInDays.mul(_durationInDays).mul(_durationInDays));
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() external view returns (address) {
return _beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function cliff() external view returns (uint256) {
return _cliff;
}
/**
* @return the start time of the token vesting.
*/
function start() external view returns (uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() external view returns (uint256) {
return _duration;
}
/**
* @return the immedReleasedAmount of the token vesting.
*/
function immedReleasedAmount() external view returns (uint256) {
return _immedReleasedAmount;
}
/**
* @return the dailyReleasedAmount of the token vesting.
*/
function dailyReleasedAmount() external view returns (uint256) {
return _dailyReleasedAmount;
}
/**
* @return the isNLReleasable value of the token vesting.
*/
function isNLReleasable() external view returns (uint256) {
return _isNLReleasable;
}
/**
* @return the dailyReleasedNLAmount of the token vesting.
*/
function dailyReleasedNLAmount() external view returns (uint256) {
return _dailyReleasedNLAmount;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() external view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) external view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) external view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenVesting: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.safeTransfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenVesting: cannot revoke");
require(!_revoked[address(token)], "TokenVesting: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
if (block.timestamp < _cliff) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) {
return totalBalance;
} else if (_immedReleasedAmount == 0 && _dailyReleasedAmount == 0) {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
} else {
uint256 daysPassed = block.timestamp.sub(_start).div(secondsPerDay);
uint256 amount0 = totalBalance.mul(_immedReleasedAmount).div(oneHundredMillion);
uint256 amount1 = totalBalance.mul(_dailyReleasedAmount).mul(daysPassed).div(oneHundredMillion);
uint256 amount2 = totalBalance.mul(_dailyReleasedNLAmount.mul(daysPassed.mul(daysPassed).mul(daysPassed))).div(oneHundredMillion);
uint256 vestedAmount = amount0.add(amount1).add(amount2);
return totalBalance < vestedAmount ? totalBalance : vestedAmount;
}
}
} | contract CommTokenVesting is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
using SafeERC20 for IERC20;
event TokensReleased(address token, uint256 amount);
event TokenVestingRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _cliff;
uint256 private _start;
uint256 private _duration;
bool private _revocable;
// non-linear params times 10^8
uint256 private _immedReleasedAmount;
uint256 private _dailyReleasedAmount;
uint256 private _isNLReleasable;
uint256 private _dailyReleasedNLAmount;
uint256 private _durationInDays;
uint256 constant oneHundredMillion = 100000000;
uint256 constant secondsPerDay = 86400;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest
* @param start the time (as Unix time) at which point vesting starts
* @param duration duration in seconds of the period in which the tokens will vest
* @param immedReleasedAmount non-liner unlock param
* @param dailyReleasedAmount non-liner unlock param
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, uint256 immedReleasedAmount, uint256 dailyReleasedAmount, bool revocable) public {
require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address");
require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration");
require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time");
require(duration >= secondsPerDay, "TokenVesting: duration must be over a day at least.");
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
_durationInDays = duration.div(secondsPerDay);
require(immedReleasedAmount <= oneHundredMillion, "TokenVesting: immedReleasedAmount is larger than 100000000.");
require(dailyReleasedAmount.mul(_durationInDays) <= oneHundredMillion, "TokenVesting: dailyReleasedAmount*_durationInDays is larger than 100000000.");
_immedReleasedAmount = immedReleasedAmount;
_dailyReleasedAmount = dailyReleasedAmount;
_isNLReleasable = oneHundredMillion.sub(_immedReleasedAmount).sub(_durationInDays.mul(_dailyReleasedAmount));
_dailyReleasedNLAmount = _isNLReleasable.div(_durationInDays.mul(_durationInDays).mul(_durationInDays));
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() external view returns (address) {
return _beneficiary;
}
/**
* @return the cliff time of the token vesting.
*/
function cliff() external view returns (uint256) {
return _cliff;
}
/**
* @return the start time of the token vesting.
*/
function start() external view returns (uint256) {
return _start;
}
/**
* @return the duration of the token vesting.
*/
function duration() external view returns (uint256) {
return _duration;
}
/**
* @return the immedReleasedAmount of the token vesting.
*/
function immedReleasedAmount() external view returns (uint256) {
return _immedReleasedAmount;
}
/**
* @return the dailyReleasedAmount of the token vesting.
*/
function dailyReleasedAmount() external view returns (uint256) {
return _dailyReleasedAmount;
}
/**
* @return the isNLReleasable value of the token vesting.
*/
function isNLReleasable() external view returns (uint256) {
return _isNLReleasable;
}
/**
* @return the dailyReleasedNLAmount of the token vesting.
*/
function dailyReleasedNLAmount() external view returns (uint256) {
return _dailyReleasedNLAmount;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() external view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) external view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) external view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenVesting: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.safeTransfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenVesting: cannot revoke");
require(!_revoked[address(token)], "TokenVesting: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.safeTransfer(owner(), refund);
emit TokenVestingRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(_released[address(token)]);
if (block.timestamp < _cliff) {
return 0;
} else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) {
return totalBalance;
} else if (_immedReleasedAmount == 0 && _dailyReleasedAmount == 0) {
return totalBalance.mul(block.timestamp.sub(_start)).div(_duration);
} else {
uint256 daysPassed = block.timestamp.sub(_start).div(secondsPerDay);
uint256 amount0 = totalBalance.mul(_immedReleasedAmount).div(oneHundredMillion);
uint256 amount1 = totalBalance.mul(_dailyReleasedAmount).mul(daysPassed).div(oneHundredMillion);
uint256 amount2 = totalBalance.mul(_dailyReleasedNLAmount.mul(daysPassed.mul(daysPassed).mul(daysPassed))).div(oneHundredMillion);
uint256 vestedAmount = amount0.add(amount1).add(amount2);
return totalBalance < vestedAmount ? totalBalance : vestedAmount;
}
}
} | 5,757 |
228 | // Directly sets the extra data for the ownership data 'index'. / | function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast 'extraData' with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
| function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast 'extraData' with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
| 23,335 |
32 | // total native fee, does not include ZRO protocol fee | uint totalNativeFee = relayerFee.add(oracleFee).add(nativeProtocolFee);
| uint totalNativeFee = relayerFee.add(oracleFee).add(nativeProtocolFee);
| 27,651 |
1 | // Indicates that the contract is in the process of being initialized. / | bool private initializing;
| bool private initializing;
| 9,130 |
69 | // 如果小于7天,则待领取的钱为0 | if(gap_day < 7) {
return 0;
}
| if(gap_day < 7) {
return 0;
}
| 15,383 |
29 | // SEE Github Issue 5. Summary: Most commonly used RLP libraries (i.e Geth) will encode "0" as "0x80" instead of as "0". We handle this edge case explicitly here. | if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
| if (result == 0 || result == STRING_SHORT_START) {
return false;
} else {
| 70,959 |
278 | // Vesper ============================================ frax_per_lp_token = stakingToken.pricePerShare(); |
return frax_per_lp_token;
|
return frax_per_lp_token;
| 17,874 |
40 | // Returns a normalized debt _amount based on the current rate/_amount Amount of dai to be normalized/_rate Current rate of the stability fee/_daiVatBalance Balance od Dai in the Vat for that CDP | function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
| function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) {
if (_daiVatBalance < mul(_amount, RAY)) {
dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate);
dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart;
}
}
| 33,452 |
98 | // This function is for dev address migrate all balance to a multi sig address | function transferAll(address _to) public {
_locks[_to] = _locks[_to].add(_locks[msg.sender]);
if (_lastUnlockBlock[_to] < lockFromBlock) {
_lastUnlockBlock[_to] = lockFromBlock;
}
if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) {
_lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender];
}
_locks[msg.sender] = 0;
_lastUnlockBlock[msg.sender] = 0;
_transfer(msg.sender, _to, balanceOf(msg.sender));
}
| function transferAll(address _to) public {
_locks[_to] = _locks[_to].add(_locks[msg.sender]);
if (_lastUnlockBlock[_to] < lockFromBlock) {
_lastUnlockBlock[_to] = lockFromBlock;
}
if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) {
_lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender];
}
_locks[msg.sender] = 0;
_lastUnlockBlock[msg.sender] = 0;
_transfer(msg.sender, _to, balanceOf(msg.sender));
}
| 5,099 |
131 | // uint256 tokenId = _iRoomieCount.current(); |
if (checkMintAllowed()) {
_iRoomieCount.increment();
|
if (checkMintAllowed()) {
_iRoomieCount.increment();
| 33,914 |
62 | // record their signature | self.proposal_[_whatProposal].admin[_whichAdmin] = true;
| self.proposal_[_whatProposal].admin[_whichAdmin] = true;
| 41,305 |
2 | // Deploys a new `ManagedPool`. / | function create(
ManagedPool.NewPoolParams memory poolParams,
BasePoolController.BasePoolRights calldata basePoolRights,
ManagedPoolController.ManagedPoolRights calldata managedPoolRights,
uint256 minWeightChangeDuration
| function create(
ManagedPool.NewPoolParams memory poolParams,
BasePoolController.BasePoolRights calldata basePoolRights,
ManagedPoolController.ManagedPoolRights calldata managedPoolRights,
uint256 minWeightChangeDuration
| 27,321 |
35 | // Retrieves the ownership addresses of a range of NFTs within a specific NFT contract./_from The starting index of the NFT range./_to The ending index of the NFT range./ return _owners An array of ownership addresses. | function getNFTsOwnership(uint256 _from, uint256 _to) external view returns (address[] memory _owners) {
uint256 counter = 0;
for (uint256 i=_from; i<=_to; ++i) {
_owners[counter] = ownerOf(counter);
++counter;
}
}
| function getNFTsOwnership(uint256 _from, uint256 _to) external view returns (address[] memory _owners) {
uint256 counter = 0;
for (uint256 i=_from; i<=_to; ++i) {
_owners[counter] = ownerOf(counter);
++counter;
}
}
| 23,133 |
14 | // Confirm the pair of addresses as two distinct owners of this contract. | function _distinctOwners(address addr1, address addr2) private constant returns (bool) {
// Check that both addresses are different
require(addr1 != addr2);
// Check that both addresses are owners
require(owners[addr1]);
require(owners[addr2]);
return true;
}
| function _distinctOwners(address addr1, address addr2) private constant returns (bool) {
// Check that both addresses are different
require(addr1 != addr2);
// Check that both addresses are owners
require(owners[addr1]);
require(owners[addr2]);
return true;
}
| 23,296 |
22 | // 2 groups of lockup | mapping(address => uint256) public contributors_locked;
mapping(address => uint256) public investors_locked;
| mapping(address => uint256) public contributors_locked;
mapping(address => uint256) public investors_locked;
| 41,761 |
51 | // Retrieve the dividend balance of any single address. | function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
| function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
| 8,014 |
67 | // Address Set. This contract allows to store addresses in a set andowner can run a loop through all elements. / | contract AddressSet is Ownable {
mapping(address => bool) exist;
address[] elements;
/**
* @dev Adds a new address to the set.
* @param _addr Address to add.
* @return True if succeed, otherwise false.
*/
function add(address _addr) onlyOwner public returns (bool) {
if (contains(_addr)) {
return false;
}
exist[_addr] = true;
elements.push(_addr);
return true;
}
/**
* @dev Checks whether the set contains a specified address or not.
* @param _addr Address to check.
* @return True if the address exists in the set, otherwise false.
*/
function contains(address _addr) public view returns (bool) {
return exist[_addr];
}
/**
* @dev Gets an element at a specified index in the set.
* @param _index Index.
* @return A relevant address.
*/
function elementAt(uint256 _index) onlyOwner public view returns (address) {
require(_index < elements.length);
return elements[_index];
}
/**
* @dev Gets the number of elements in the set.
* @return The number of elements.
*/
function getTheNumberOfElements() onlyOwner public view returns (uint256) {
return elements.length;
}
}
| contract AddressSet is Ownable {
mapping(address => bool) exist;
address[] elements;
/**
* @dev Adds a new address to the set.
* @param _addr Address to add.
* @return True if succeed, otherwise false.
*/
function add(address _addr) onlyOwner public returns (bool) {
if (contains(_addr)) {
return false;
}
exist[_addr] = true;
elements.push(_addr);
return true;
}
/**
* @dev Checks whether the set contains a specified address or not.
* @param _addr Address to check.
* @return True if the address exists in the set, otherwise false.
*/
function contains(address _addr) public view returns (bool) {
return exist[_addr];
}
/**
* @dev Gets an element at a specified index in the set.
* @param _index Index.
* @return A relevant address.
*/
function elementAt(uint256 _index) onlyOwner public view returns (address) {
require(_index < elements.length);
return elements[_index];
}
/**
* @dev Gets the number of elements in the set.
* @return The number of elements.
*/
function getTheNumberOfElements() onlyOwner public view returns (uint256) {
return elements.length;
}
}
| 10,926 |
30 | // Here we ensure that we wouldn't have an overflow down the line, as our max tokens is going to be less than the overflow threshold | require(amount <= maxTokens, "You cannot mint more than the max amount of tokens!");
require(supply + amount <= maxTokens - reserved, "Amount will exceed supply");
uint totalPrice = pricePerNft * amount;
require(mintedTokensBy(msgSenderAddress) + amount <= maxCanHaveMintable, 'You cannot mint more tokens!');
require(msg.value >= totalPrice, 'Insufficient ether sent!');
| require(amount <= maxTokens, "You cannot mint more than the max amount of tokens!");
require(supply + amount <= maxTokens - reserved, "Amount will exceed supply");
uint totalPrice = pricePerNft * amount;
require(mintedTokensBy(msgSenderAddress) + amount <= maxCanHaveMintable, 'You cannot mint more tokens!');
require(msg.value >= totalPrice, 'Insufficient ether sent!');
| 51,868 |
2 | // See {ERC721-_ownerOf}. Override that checks the sequential ownership structure for tokens that havebeen minted as part of a batch, and not yet transferred. / | function _ownerOf(uint256 tokenId) internal view virtual override returns (address) {
address owner = super._ownerOf(tokenId);
| function _ownerOf(uint256 tokenId) internal view virtual override returns (address) {
address owner = super._ownerOf(tokenId);
| 20,480 |
32 | // Relay a transaction.from the client originating the request. recipient the target IRelayRecipient contract. encodedFunction the function call to relay. transactionFee fee (%) the relay takes over actual gas cost. gasPrice gas price the client is willing to pay gasLimit limit the client want to put on its transaction transactionFee fee (%) the relay takes over actual gas cost. nonce sender's nonce (in nonces[]) signature client's signature over all params except approvalData approvalData dapp-specific data / | function relayCall(
address from,
address recipient,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
| function relayCall(
address from,
address recipient,
bytes memory encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes memory signature,
bytes memory approvalData
| 39,660 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.