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
|
---|---|---|---|---|
10 | // ROYALTY FUNCTIONS / | function getRoyalties(uint256) external view returns (address payable[] memory recipients, uint256[] memory bps);
| function getRoyalties(uint256) external view returns (address payable[] memory recipients, uint256[] memory bps);
| 20,184 |
6 | // What's better than withdrawing? Re-investing profits! | function reinvest()
checkZeroBalance()
| function reinvest()
checkZeroBalance()
| 28,126 |
32 | // math calculations work with the assumption that the price diff is capped to 5% since tick distance is uncapped between currentTick and nextTick we use tempNextTick to satisfy our assumption with MAX_TICK_DISTANCE is set to be matched this condition |
int24 tempNextTick = swapData.nextTick;
if (willUpTick && tempNextTick > C.MAX_TICK_DISTANCE + swapData.currentTick) {
tempNextTick = swapData.currentTick + C.MAX_TICK_DISTANCE;
} else if (!willUpTick && tempNextTick < swapData.currentTick - C.MAX_TICK_DISTANCE) {
|
int24 tempNextTick = swapData.nextTick;
if (willUpTick && tempNextTick > C.MAX_TICK_DISTANCE + swapData.currentTick) {
tempNextTick = swapData.currentTick + C.MAX_TICK_DISTANCE;
} else if (!willUpTick && tempNextTick < swapData.currentTick - C.MAX_TICK_DISTANCE) {
| 26,853 |
12 | // Mapping of Item to a TokenStatus struct | mapping(uint256 => TokenStatus) private _idToItemStatus;
| mapping(uint256 => TokenStatus) private _idToItemStatus;
| 11,240 |
169 | // scale rate proportionally up to 100% | uint256 thisMaxRange = WEI_PERCENT_PRECISION - thisKinkLevel; // will not overflow
utilRate -= thisKinkLevel;
if (utilRate > thisMaxRange)
utilRate = thisMaxRange;
thisMaxRate = thisRateMultiplier
.add(thisBaseRate)
.mul(thisKinkLevel)
.div(WEI_PERCENT_PRECISION);
| uint256 thisMaxRange = WEI_PERCENT_PRECISION - thisKinkLevel; // will not overflow
utilRate -= thisKinkLevel;
if (utilRate > thisMaxRange)
utilRate = thisMaxRange;
thisMaxRate = thisRateMultiplier
.add(thisBaseRate)
.mul(thisKinkLevel)
.div(WEI_PERCENT_PRECISION);
| 13,988 |
27 | // Get media URI for a given Avastar Token ID. _tokenId the Token ID of a previously minted Avastar Prime or Replicantreturn uri the off-chain URI to the Avastar image / | function mediaURI(uint _tokenId)
public view
returns (string memory uri)
| function mediaURI(uint _tokenId)
public view
returns (string memory uri)
| 7,596 |
469 | // Update fee, implicitly requiring that partner name is registered | uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
| uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee);
| 11,556 |
1 | // Hashing function | Hasher hasher;
| Hasher hasher;
| 51,247 |
203 | // 1,2 period, 1,2 period | if(fromPeriod == 1 && toPeriod == 1) {
return _to.sub(_from).mul(64);
| if(fromPeriod == 1 && toPeriod == 1) {
return _to.sub(_from).mul(64);
| 8,915 |
361 | // if no time has passed since the reference time, return current weights (also ensures a single update per block) | uint256 elapsedTime = currentTime - referenceTime;
if (elapsedTime == 0) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
| uint256 elapsedTime = currentTime - referenceTime;
if (elapsedTime == 0) {
return (primaryReserveWeight, externalPrimaryReserveWeight);
}
| 17,431 |
8 | // Upgrade a pass / | function _upgradePass(uint256 tokenId, uint8 level) private {
_tokenLevel[tokenId] = level;
emit TokenLevel(tokenId, level);
}
| function _upgradePass(uint256 tokenId, uint8 level) private {
_tokenLevel[tokenId] = level;
emit TokenLevel(tokenId, level);
}
| 10,152 |
118 | // Calculate binary exponent of x.Revert on overflow.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number / | function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
| function exp_2 (int128 x) internal pure returns (int128) {
unchecked {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (int256 (63 - (x >> 64)));
require (result <= uint256 (int256 (MAX_64x64)));
return int128 (int256 (result));
}
}
| 46,511 |
173 | // Internal call to refund all WETH to the current executor as native ETH. | function doRefundETH() internal {
uint balance = IWETH(weth).balanceOf(address(this));
if (balance > 0) {
IWETH(weth).withdraw(balance);
(bool success, ) = bank.EXECUTOR().call{value: balance}(new bytes(0));
require(success, 'refund ETH failed');
}
}
| function doRefundETH() internal {
uint balance = IWETH(weth).balanceOf(address(this));
if (balance > 0) {
IWETH(weth).withdraw(balance);
(bool success, ) = bank.EXECUTOR().call{value: balance}(new bytes(0));
require(success, 'refund ETH failed');
}
}
| 54,105 |
361 | // Check if player has already minted and record | if (hasMintedPreMarket[player]) {
return;
}
| if (hasMintedPreMarket[player]) {
return;
}
| 12,329 |
26 | // add the ambassadors here - Tokens will be distributed to these addresses from main premine | ambassadors_[0xb2A13A5AE7922325290ce4eAf5029Ef18045Ee2B] = true;
| ambassadors_[0xb2A13A5AE7922325290ce4eAf5029Ef18045Ee2B] = true;
| 44,858 |
85 | // index_delta = w_1_omega - w_1 | let index_delta := addmod(mload(W1_OMEGA_EVAL_LOC), sub(p, mload(W1_EVAL_LOC)), p)
| let index_delta := addmod(mload(W1_OMEGA_EVAL_LOC), sub(p, mload(W1_EVAL_LOC)), p)
| 32,476 |
11 | // returns allocated result | function allocate(address staking, uint rewardAmount) external view returns (uint stakingPart, address[] memory others, uint[] memory othersParts);
| function allocate(address staking, uint rewardAmount) external view returns (uint stakingPart, address[] memory others, uint[] memory othersParts);
| 47,727 |
24 | // `onlyDonor` Approves the proposed milestone list/_hashProposals The keccak256() of the proposed milestone list's/bytecode; this confirms that the `donor` knows the set of milestones/they are approving | function acceptProposedMilestones(bytes32 _hashProposals
| function acceptProposedMilestones(bytes32 _hashProposals
| 40,336 |
167 | // Enumerable mapping from token ids to their owners | EnumerableMap.UintToAddressMap private _tokenOwners;
| EnumerableMap.UintToAddressMap private _tokenOwners;
| 4,821 |
90 | // totalICO = totalICO.sub(token.balanceOf(msg.sender)); | }
| }
| 47,456 |
104 | // Kyber Network main contract | contract KyberNetwork is Withdrawable, Utils2, KyberNetworkInterface, ReentrancyGuard {
bytes public constant PERM_HINT = "PERM";
uint public constant PERM_HINT_GET_RATE = 1 << 255; // for get rate. bit mask hint.
uint public negligibleRateDiff = 10; // basic rate steps will be in 0.01%
KyberReserveInterface[] public reserves;
mapping(address=>ReserveType) public reserveType;
WhiteListInterface public whiteListContract;
ExpectedRateInterface public expectedRateContract;
FeeBurnerInterface public feeBurnerContract;
address public kyberNetworkProxyContract;
uint public maxGasPriceValue = 50 * 1000 * 1000 * 1000; // 50 gwei
bool public isEnabled = false; // network is enabled
mapping(bytes32=>uint) public infoFields; // this is only a UI field for external app.
mapping(address=>address[]) public reservesPerTokenSrc; //reserves supporting token to eth
mapping(address=>address[]) public reservesPerTokenDest;//reserves support eth to token
enum ReserveType {NONE, PERMISSIONED, PERMISSIONLESS}
bytes internal constant EMPTY_HINT = "";
function KyberNetwork(address _admin) public {
require(_admin != address(0));
admin = _admin;
}
event EtherReceival(address indexed sender, uint amount);
/* solhint-disable no-complex-fallback */
// To avoid users trying to swap tokens using default payable function. We added this short code
// to verify Ethers will be received only from reserves if transferred without a specific function call.
function() public payable {
require(reserveType[msg.sender] != ReserveType.NONE);
EtherReceival(msg.sender, msg.value);
}
/* solhint-enable no-complex-fallback */
struct TradeInput {
address trader;
ERC20 src;
uint srcAmount;
ERC20 dest;
address destAddress;
uint maxDestAmount;
uint minConversionRate;
address walletId;
bytes hint;
}
function tradeWithHint(
address trader,
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId,
bytes hint
)
public
nonReentrant
payable
returns(uint)
{
require(msg.sender == kyberNetworkProxyContract);
require((hint.length == 0) || (hint.length == 4));
TradeInput memory tradeInput;
tradeInput.trader = trader;
tradeInput.src = src;
tradeInput.srcAmount = srcAmount;
tradeInput.dest = dest;
tradeInput.destAddress = destAddress;
tradeInput.maxDestAmount = maxDestAmount;
tradeInput.minConversionRate = minConversionRate;
tradeInput.walletId = walletId;
tradeInput.hint = hint;
return trade(tradeInput);
}
event AddReserveToNetwork(KyberReserveInterface indexed reserve, bool add, bool isPermissionless);
/// @notice can be called only by operator
/// @dev add or deletes a reserve to/from the network.
/// @param reserve The reserve address.
/// @param isPermissionless is the new reserve from permissionless type.
function addReserve(KyberReserveInterface reserve, bool isPermissionless) public onlyOperator
returns(bool)
{
require(reserveType[reserve] == ReserveType.NONE);
reserves.push(reserve);
reserveType[reserve] = isPermissionless ? ReserveType.PERMISSIONLESS : ReserveType.PERMISSIONED;
AddReserveToNetwork(reserve, true, isPermissionless);
return true;
}
event RemoveReserveFromNetwork(KyberReserveInterface reserve);
/// @notice can be called only by operator
/// @dev removes a reserve from Kyber network.
/// @param reserve The reserve address.
/// @param index in reserve array.
function removeReserve(KyberReserveInterface reserve, uint index) public onlyOperator
returns(bool)
{
require(reserveType[reserve] != ReserveType.NONE);
require(reserves[index] == reserve);
reserveType[reserve] = ReserveType.NONE;
reserves[index] = reserves[reserves.length - 1];
reserves.length--;
RemoveReserveFromNetwork(reserve);
return true;
}
event ListReservePairs(address indexed reserve, ERC20 src, ERC20 dest, bool add);
/// @notice can be called only by operator
/// @dev allow or prevent a specific reserve to trade a pair of tokens
/// @param reserve The reserve address.
/// @param token token address
/// @param ethToToken will it support ether to token trade
/// @param tokenToEth will it support token to ether trade
/// @param add If true then list this pair, otherwise unlist it.
function listPairForReserve(address reserve, ERC20 token, bool ethToToken, bool tokenToEth, bool add)
public
onlyOperator
returns(bool)
{
require(reserveType[reserve] != ReserveType.NONE);
if (ethToToken) {
listPairs(reserve, token, false, add);
ListReservePairs(reserve, ETH_TOKEN_ADDRESS, token, add);
}
if (tokenToEth) {
listPairs(reserve, token, true, add);
if (add) {
require(token.approve(reserve, 2**255)); // approve infinity
} else {
require(token.approve(reserve, 0));
}
ListReservePairs(reserve, token, ETH_TOKEN_ADDRESS, add);
}
setDecimals(token);
return true;
}
event WhiteListContractSet(WhiteListInterface newContract, WhiteListInterface currentContract);
///@param whiteList can be empty
function setWhiteList(WhiteListInterface whiteList) public onlyAdmin {
WhiteListContractSet(whiteList, whiteListContract);
whiteListContract = whiteList;
}
event ExpectedRateContractSet(ExpectedRateInterface newContract, ExpectedRateInterface currentContract);
function setExpectedRate(ExpectedRateInterface expectedRate) public onlyAdmin {
require(expectedRate != address(0));
ExpectedRateContractSet(expectedRate, expectedRateContract);
expectedRateContract = expectedRate;
}
event FeeBurnerContractSet(FeeBurnerInterface newContract, FeeBurnerInterface currentContract);
function setFeeBurner(FeeBurnerInterface feeBurner) public onlyAdmin {
require(feeBurner != address(0));
FeeBurnerContractSet(feeBurner, feeBurnerContract);
feeBurnerContract = feeBurner;
}
event KyberNetwrokParamsSet(uint maxGasPrice, uint negligibleRateDiff);
function setParams(
uint _maxGasPrice,
uint _negligibleRateDiff
)
public
onlyAdmin
{
require(_negligibleRateDiff <= 100 * 100); // at most 100%
maxGasPriceValue = _maxGasPrice;
negligibleRateDiff = _negligibleRateDiff;
KyberNetwrokParamsSet(maxGasPriceValue, negligibleRateDiff);
}
event KyberNetworkSetEnable(bool isEnabled);
function setEnable(bool _enable) public onlyAdmin {
if (_enable) {
require(feeBurnerContract != address(0));
require(expectedRateContract != address(0));
require(kyberNetworkProxyContract != address(0));
}
isEnabled = _enable;
KyberNetworkSetEnable(isEnabled);
}
function setInfo(bytes32 field, uint value) public onlyOperator {
infoFields[field] = value;
}
event KyberProxySet(address proxy, address sender);
function setKyberProxy(address networkProxy) public onlyAdmin {
require(networkProxy != address(0));
kyberNetworkProxyContract = networkProxy;
KyberProxySet(kyberNetworkProxyContract, msg.sender);
}
/// @dev returns number of reserves
/// @return number of reserves
function getNumReserves() public view returns(uint) {
return reserves.length;
}
/// @notice should be called off chain
/// @dev get an array of all reserves
/// @return An array of all reserves
function getReserves() public view returns(KyberReserveInterface[]) {
return reserves;
}
function maxGasPrice() public view returns(uint) {
return maxGasPriceValue;
}
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
public view
returns(uint expectedRate, uint slippageRate)
{
require(expectedRateContract != address(0));
bool includePermissionless = true;
if (srcQty & PERM_HINT_GET_RATE > 0) {
includePermissionless = false;
srcQty = srcQty & ~PERM_HINT_GET_RATE;
}
return expectedRateContract.getExpectedRate(src, dest, srcQty, includePermissionless);
}
function getExpectedRateOnlyPermission(ERC20 src, ERC20 dest, uint srcQty)
public view
returns(uint expectedRate, uint slippageRate)
{
require(expectedRateContract != address(0));
return expectedRateContract.getExpectedRate(src, dest, srcQty, false);
}
function getUserCapInWei(address user) public view returns(uint) {
if (whiteListContract == address(0)) return (2 ** 255);
return whiteListContract.getUserCapInWei(user);
}
function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint) {
//future feature
user;
token;
require(false);
}
struct BestRateResult {
uint rate;
address reserve1;
address reserve2;
uint weiAmount;
uint rateSrcToEth;
uint rateEthToDest;
uint destAmount;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev best conversion rate for a pair of tokens, if number of reserves have small differences. randomize
/// @param src Src token
/// @param dest Destination token
/// @return obsolete - used to return best reserve index. not relevant anymore for this API.
function findBestRate(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) {
BestRateResult memory result = findBestRateTokenToToken(src, dest, srcAmount, EMPTY_HINT);
return(0, result.rate);
}
function findBestRateOnlyPermission(ERC20 src, ERC20 dest, uint srcAmount)
public
view
returns(uint obsolete, uint rate)
{
BestRateResult memory result = findBestRateTokenToToken(src, dest, srcAmount, PERM_HINT);
return(0, result.rate);
}
function enabled() public view returns(bool) {
return isEnabled;
}
function info(bytes32 field) public view returns(uint) {
return infoFields[field];
}
/* solhint-disable code-complexity */
// Regarding complexity. Below code follows the required algorithm for choosing a reserve.
// It has been tested, reviewed and found to be clear enough.
//@dev this function always src or dest are ether. can't do token to token
function searchBestRate(ERC20 src, ERC20 dest, uint srcAmount, bool usePermissionless)
public
view
returns(address, uint)
{
uint bestRate = 0;
uint bestReserve = 0;
uint numRelevantReserves = 0;
//return 1 for ether to ether
if (src == dest) return (reserves[bestReserve], PRECISION);
address[] memory reserveArr;
reserveArr = src == ETH_TOKEN_ADDRESS ? reservesPerTokenDest[dest] : reservesPerTokenSrc[src];
if (reserveArr.length == 0) return (reserves[bestReserve], bestRate);
uint[] memory rates = new uint[](reserveArr.length);
uint[] memory reserveCandidates = new uint[](reserveArr.length);
for (uint i = 0; i < reserveArr.length; i++) {
//list all reserves that have this token.
if (!usePermissionless && reserveType[reserveArr[i]] == ReserveType.PERMISSIONLESS) {
continue;
}
rates[i] = (KyberReserveInterface(reserveArr[i])).getConversionRate(src, dest, srcAmount, block.number);
if (rates[i] > bestRate) {
//best rate is highest rate
bestRate = rates[i];
}
}
if (bestRate > 0) {
uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligibleRateDiff);
for (i = 0; i < reserveArr.length; i++) {
if (rates[i] >= smallestRelevantRate) {
reserveCandidates[numRelevantReserves++] = i;
}
}
if (numRelevantReserves > 1) {
//when encountering small rate diff from bestRate. draw from relevant reserves
bestReserve = reserveCandidates[uint(block.blockhash(block.number-1)) % numRelevantReserves];
} else {
bestReserve = reserveCandidates[0];
}
bestRate = rates[bestReserve];
}
return (reserveArr[bestReserve], bestRate);
}
/* solhint-enable code-complexity */
function findBestRateTokenToToken(ERC20 src, ERC20 dest, uint srcAmount, bytes hint) internal view
returns(BestRateResult result)
{
//by default we use permission less reserves
bool usePermissionless = true;
// if hint in first 4 bytes == 'PERM' only permissioned reserves will be used.
if ((hint.length >= 4) && (keccak256(hint[0], hint[1], hint[2], hint[3]) == keccak256(PERM_HINT))) {
usePermissionless = false;
}
(result.reserve1, result.rateSrcToEth) =
searchBestRate(src, ETH_TOKEN_ADDRESS, srcAmount, usePermissionless);
result.weiAmount = calcDestAmount(src, ETH_TOKEN_ADDRESS, srcAmount, result.rateSrcToEth);
(result.reserve2, result.rateEthToDest) =
searchBestRate(ETH_TOKEN_ADDRESS, dest, result.weiAmount, usePermissionless);
result.destAmount = calcDestAmount(ETH_TOKEN_ADDRESS, dest, result.weiAmount, result.rateEthToDest);
result.rate = calcRateFromQty(srcAmount, result.destAmount, getDecimals(src), getDecimals(dest));
}
function listPairs(address reserve, ERC20 token, bool isTokenToEth, bool add) internal {
uint i;
address[] storage reserveArr = reservesPerTokenDest[token];
if (isTokenToEth) {
reserveArr = reservesPerTokenSrc[token];
}
for (i = 0; i < reserveArr.length; i++) {
if (reserve == reserveArr[i]) {
if (add) {
break; //already added
} else {
//remove
reserveArr[i] = reserveArr[reserveArr.length - 1];
reserveArr.length--;
break;
}
}
}
if (add && i == reserveArr.length) {
//if reserve wasn't found add it
reserveArr.push(reserve);
}
}
event KyberTrade(address indexed trader, ERC20 src, ERC20 dest, uint srcAmount, uint dstAmount,
address destAddress, uint ethWeiValue, address reserve1, address reserve2, bytes hint);
/* solhint-disable function-max-lines */
// Most of the lines here are functions calls spread over multiple lines. We find this function readable enough
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev trade api for kyber network.
/// @param tradeInput structure of trade inputs
function trade(TradeInput tradeInput) internal returns(uint) {
require(isEnabled);
require(tx.gasprice <= maxGasPriceValue);
require(validateTradeInput(tradeInput.src, tradeInput.srcAmount, tradeInput.dest, tradeInput.destAddress));
BestRateResult memory rateResult =
findBestRateTokenToToken(tradeInput.src, tradeInput.dest, tradeInput.srcAmount, tradeInput.hint);
require(rateResult.rate > 0);
require(rateResult.rate < MAX_RATE);
require(rateResult.rate >= tradeInput.minConversionRate);
uint actualDestAmount;
uint weiAmount;
uint actualSrcAmount;
(actualSrcAmount, weiAmount, actualDestAmount) = calcActualAmounts(tradeInput.src,
tradeInput.dest,
tradeInput.srcAmount,
tradeInput.maxDestAmount,
rateResult);
require(getUserCapInWei(tradeInput.trader) >= weiAmount);
require(handleChange(tradeInput.src, tradeInput.srcAmount, actualSrcAmount, tradeInput.trader));
require(doReserveTrade( //src to ETH
tradeInput.src,
actualSrcAmount,
ETH_TOKEN_ADDRESS,
this,
weiAmount,
KyberReserveInterface(rateResult.reserve1),
rateResult.rateSrcToEth,
true));
require(doReserveTrade( //Eth to dest
ETH_TOKEN_ADDRESS,
weiAmount,
tradeInput.dest,
tradeInput.destAddress,
actualDestAmount,
KyberReserveInterface(rateResult.reserve2),
rateResult.rateEthToDest,
true));
if (tradeInput.src != ETH_TOKEN_ADDRESS) //"fake" trade. (ether to ether) - don't burn.
require(feeBurnerContract.handleFees(weiAmount, rateResult.reserve1, tradeInput.walletId));
if (tradeInput.dest != ETH_TOKEN_ADDRESS) //"fake" trade. (ether to ether) - don't burn.
require(feeBurnerContract.handleFees(weiAmount, rateResult.reserve2, tradeInput.walletId));
KyberTrade({
trader: tradeInput.trader,
src: tradeInput.src,
dest: tradeInput.dest,
srcAmount: actualSrcAmount,
dstAmount: actualDestAmount,
destAddress: tradeInput.destAddress,
ethWeiValue: weiAmount,
reserve1: (tradeInput.src == ETH_TOKEN_ADDRESS) ? address(0) : rateResult.reserve1,
reserve2: (tradeInput.dest == ETH_TOKEN_ADDRESS) ? address(0) : rateResult.reserve2,
hint: tradeInput.hint
});
return actualDestAmount;
}
/* solhint-enable function-max-lines */
function calcActualAmounts (ERC20 src, ERC20 dest, uint srcAmount, uint maxDestAmount, BestRateResult rateResult)
internal view returns(uint actualSrcAmount, uint weiAmount, uint actualDestAmount)
{
if (rateResult.destAmount > maxDestAmount) {
actualDestAmount = maxDestAmount;
weiAmount = calcSrcAmount(ETH_TOKEN_ADDRESS, dest, actualDestAmount, rateResult.rateEthToDest);
actualSrcAmount = calcSrcAmount(src, ETH_TOKEN_ADDRESS, weiAmount, rateResult.rateSrcToEth);
require(actualSrcAmount <= srcAmount);
} else {
actualDestAmount = rateResult.destAmount;
actualSrcAmount = srcAmount;
weiAmount = rateResult.weiAmount;
}
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a reserve
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doReserveTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserveInterface reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == dest) {
//this is for a "fake" trade when both src and dest are ethers.
if (destAddress != (address(this)))
destAddress.transfer(amount);
return true;
}
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
}
// reserve sends tokens/eth to network. network sends it to destination
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
if (destAddress != address(this)) {
//for token to token dest address is network. and Ether / token already here...
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, expectedDestAmount));
}
}
return true;
}
/// when user sets max dest amount we could have too many source tokens == change. so we send it back to user.
function handleChange (ERC20 src, uint srcAmount, uint requiredSrcAmount, address trader) internal returns (bool) {
if (requiredSrcAmount < srcAmount) {
//if there is "change" send back to trader
if (src == ETH_TOKEN_ADDRESS) {
trader.transfer(srcAmount - requiredSrcAmount);
} else {
require(src.transfer(trader, (srcAmount - requiredSrcAmount)));
}
}
return true;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev checks that user sent ether/tokens to contract before trade
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @return true if tradeInput is valid
function validateTradeInput(ERC20 src, uint srcAmount, ERC20 dest, address destAddress)
internal
view
returns(bool)
{
require(srcAmount <= MAX_QTY);
require(srcAmount != 0);
require(destAddress != address(0));
require(src != dest);
if (src == ETH_TOKEN_ADDRESS) {
require(msg.value == srcAmount);
} else {
require(msg.value == 0);
//funds should have been moved to this contract already.
require(src.balanceOf(this) >= srcAmount);
}
return true;
}
}
| contract KyberNetwork is Withdrawable, Utils2, KyberNetworkInterface, ReentrancyGuard {
bytes public constant PERM_HINT = "PERM";
uint public constant PERM_HINT_GET_RATE = 1 << 255; // for get rate. bit mask hint.
uint public negligibleRateDiff = 10; // basic rate steps will be in 0.01%
KyberReserveInterface[] public reserves;
mapping(address=>ReserveType) public reserveType;
WhiteListInterface public whiteListContract;
ExpectedRateInterface public expectedRateContract;
FeeBurnerInterface public feeBurnerContract;
address public kyberNetworkProxyContract;
uint public maxGasPriceValue = 50 * 1000 * 1000 * 1000; // 50 gwei
bool public isEnabled = false; // network is enabled
mapping(bytes32=>uint) public infoFields; // this is only a UI field for external app.
mapping(address=>address[]) public reservesPerTokenSrc; //reserves supporting token to eth
mapping(address=>address[]) public reservesPerTokenDest;//reserves support eth to token
enum ReserveType {NONE, PERMISSIONED, PERMISSIONLESS}
bytes internal constant EMPTY_HINT = "";
function KyberNetwork(address _admin) public {
require(_admin != address(0));
admin = _admin;
}
event EtherReceival(address indexed sender, uint amount);
/* solhint-disable no-complex-fallback */
// To avoid users trying to swap tokens using default payable function. We added this short code
// to verify Ethers will be received only from reserves if transferred without a specific function call.
function() public payable {
require(reserveType[msg.sender] != ReserveType.NONE);
EtherReceival(msg.sender, msg.value);
}
/* solhint-enable no-complex-fallback */
struct TradeInput {
address trader;
ERC20 src;
uint srcAmount;
ERC20 dest;
address destAddress;
uint maxDestAmount;
uint minConversionRate;
address walletId;
bytes hint;
}
function tradeWithHint(
address trader,
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId,
bytes hint
)
public
nonReentrant
payable
returns(uint)
{
require(msg.sender == kyberNetworkProxyContract);
require((hint.length == 0) || (hint.length == 4));
TradeInput memory tradeInput;
tradeInput.trader = trader;
tradeInput.src = src;
tradeInput.srcAmount = srcAmount;
tradeInput.dest = dest;
tradeInput.destAddress = destAddress;
tradeInput.maxDestAmount = maxDestAmount;
tradeInput.minConversionRate = minConversionRate;
tradeInput.walletId = walletId;
tradeInput.hint = hint;
return trade(tradeInput);
}
event AddReserveToNetwork(KyberReserveInterface indexed reserve, bool add, bool isPermissionless);
/// @notice can be called only by operator
/// @dev add or deletes a reserve to/from the network.
/// @param reserve The reserve address.
/// @param isPermissionless is the new reserve from permissionless type.
function addReserve(KyberReserveInterface reserve, bool isPermissionless) public onlyOperator
returns(bool)
{
require(reserveType[reserve] == ReserveType.NONE);
reserves.push(reserve);
reserveType[reserve] = isPermissionless ? ReserveType.PERMISSIONLESS : ReserveType.PERMISSIONED;
AddReserveToNetwork(reserve, true, isPermissionless);
return true;
}
event RemoveReserveFromNetwork(KyberReserveInterface reserve);
/// @notice can be called only by operator
/// @dev removes a reserve from Kyber network.
/// @param reserve The reserve address.
/// @param index in reserve array.
function removeReserve(KyberReserveInterface reserve, uint index) public onlyOperator
returns(bool)
{
require(reserveType[reserve] != ReserveType.NONE);
require(reserves[index] == reserve);
reserveType[reserve] = ReserveType.NONE;
reserves[index] = reserves[reserves.length - 1];
reserves.length--;
RemoveReserveFromNetwork(reserve);
return true;
}
event ListReservePairs(address indexed reserve, ERC20 src, ERC20 dest, bool add);
/// @notice can be called only by operator
/// @dev allow or prevent a specific reserve to trade a pair of tokens
/// @param reserve The reserve address.
/// @param token token address
/// @param ethToToken will it support ether to token trade
/// @param tokenToEth will it support token to ether trade
/// @param add If true then list this pair, otherwise unlist it.
function listPairForReserve(address reserve, ERC20 token, bool ethToToken, bool tokenToEth, bool add)
public
onlyOperator
returns(bool)
{
require(reserveType[reserve] != ReserveType.NONE);
if (ethToToken) {
listPairs(reserve, token, false, add);
ListReservePairs(reserve, ETH_TOKEN_ADDRESS, token, add);
}
if (tokenToEth) {
listPairs(reserve, token, true, add);
if (add) {
require(token.approve(reserve, 2**255)); // approve infinity
} else {
require(token.approve(reserve, 0));
}
ListReservePairs(reserve, token, ETH_TOKEN_ADDRESS, add);
}
setDecimals(token);
return true;
}
event WhiteListContractSet(WhiteListInterface newContract, WhiteListInterface currentContract);
///@param whiteList can be empty
function setWhiteList(WhiteListInterface whiteList) public onlyAdmin {
WhiteListContractSet(whiteList, whiteListContract);
whiteListContract = whiteList;
}
event ExpectedRateContractSet(ExpectedRateInterface newContract, ExpectedRateInterface currentContract);
function setExpectedRate(ExpectedRateInterface expectedRate) public onlyAdmin {
require(expectedRate != address(0));
ExpectedRateContractSet(expectedRate, expectedRateContract);
expectedRateContract = expectedRate;
}
event FeeBurnerContractSet(FeeBurnerInterface newContract, FeeBurnerInterface currentContract);
function setFeeBurner(FeeBurnerInterface feeBurner) public onlyAdmin {
require(feeBurner != address(0));
FeeBurnerContractSet(feeBurner, feeBurnerContract);
feeBurnerContract = feeBurner;
}
event KyberNetwrokParamsSet(uint maxGasPrice, uint negligibleRateDiff);
function setParams(
uint _maxGasPrice,
uint _negligibleRateDiff
)
public
onlyAdmin
{
require(_negligibleRateDiff <= 100 * 100); // at most 100%
maxGasPriceValue = _maxGasPrice;
negligibleRateDiff = _negligibleRateDiff;
KyberNetwrokParamsSet(maxGasPriceValue, negligibleRateDiff);
}
event KyberNetworkSetEnable(bool isEnabled);
function setEnable(bool _enable) public onlyAdmin {
if (_enable) {
require(feeBurnerContract != address(0));
require(expectedRateContract != address(0));
require(kyberNetworkProxyContract != address(0));
}
isEnabled = _enable;
KyberNetworkSetEnable(isEnabled);
}
function setInfo(bytes32 field, uint value) public onlyOperator {
infoFields[field] = value;
}
event KyberProxySet(address proxy, address sender);
function setKyberProxy(address networkProxy) public onlyAdmin {
require(networkProxy != address(0));
kyberNetworkProxyContract = networkProxy;
KyberProxySet(kyberNetworkProxyContract, msg.sender);
}
/// @dev returns number of reserves
/// @return number of reserves
function getNumReserves() public view returns(uint) {
return reserves.length;
}
/// @notice should be called off chain
/// @dev get an array of all reserves
/// @return An array of all reserves
function getReserves() public view returns(KyberReserveInterface[]) {
return reserves;
}
function maxGasPrice() public view returns(uint) {
return maxGasPriceValue;
}
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
public view
returns(uint expectedRate, uint slippageRate)
{
require(expectedRateContract != address(0));
bool includePermissionless = true;
if (srcQty & PERM_HINT_GET_RATE > 0) {
includePermissionless = false;
srcQty = srcQty & ~PERM_HINT_GET_RATE;
}
return expectedRateContract.getExpectedRate(src, dest, srcQty, includePermissionless);
}
function getExpectedRateOnlyPermission(ERC20 src, ERC20 dest, uint srcQty)
public view
returns(uint expectedRate, uint slippageRate)
{
require(expectedRateContract != address(0));
return expectedRateContract.getExpectedRate(src, dest, srcQty, false);
}
function getUserCapInWei(address user) public view returns(uint) {
if (whiteListContract == address(0)) return (2 ** 255);
return whiteListContract.getUserCapInWei(user);
}
function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint) {
//future feature
user;
token;
require(false);
}
struct BestRateResult {
uint rate;
address reserve1;
address reserve2;
uint weiAmount;
uint rateSrcToEth;
uint rateEthToDest;
uint destAmount;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev best conversion rate for a pair of tokens, if number of reserves have small differences. randomize
/// @param src Src token
/// @param dest Destination token
/// @return obsolete - used to return best reserve index. not relevant anymore for this API.
function findBestRate(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) {
BestRateResult memory result = findBestRateTokenToToken(src, dest, srcAmount, EMPTY_HINT);
return(0, result.rate);
}
function findBestRateOnlyPermission(ERC20 src, ERC20 dest, uint srcAmount)
public
view
returns(uint obsolete, uint rate)
{
BestRateResult memory result = findBestRateTokenToToken(src, dest, srcAmount, PERM_HINT);
return(0, result.rate);
}
function enabled() public view returns(bool) {
return isEnabled;
}
function info(bytes32 field) public view returns(uint) {
return infoFields[field];
}
/* solhint-disable code-complexity */
// Regarding complexity. Below code follows the required algorithm for choosing a reserve.
// It has been tested, reviewed and found to be clear enough.
//@dev this function always src or dest are ether. can't do token to token
function searchBestRate(ERC20 src, ERC20 dest, uint srcAmount, bool usePermissionless)
public
view
returns(address, uint)
{
uint bestRate = 0;
uint bestReserve = 0;
uint numRelevantReserves = 0;
//return 1 for ether to ether
if (src == dest) return (reserves[bestReserve], PRECISION);
address[] memory reserveArr;
reserveArr = src == ETH_TOKEN_ADDRESS ? reservesPerTokenDest[dest] : reservesPerTokenSrc[src];
if (reserveArr.length == 0) return (reserves[bestReserve], bestRate);
uint[] memory rates = new uint[](reserveArr.length);
uint[] memory reserveCandidates = new uint[](reserveArr.length);
for (uint i = 0; i < reserveArr.length; i++) {
//list all reserves that have this token.
if (!usePermissionless && reserveType[reserveArr[i]] == ReserveType.PERMISSIONLESS) {
continue;
}
rates[i] = (KyberReserveInterface(reserveArr[i])).getConversionRate(src, dest, srcAmount, block.number);
if (rates[i] > bestRate) {
//best rate is highest rate
bestRate = rates[i];
}
}
if (bestRate > 0) {
uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligibleRateDiff);
for (i = 0; i < reserveArr.length; i++) {
if (rates[i] >= smallestRelevantRate) {
reserveCandidates[numRelevantReserves++] = i;
}
}
if (numRelevantReserves > 1) {
//when encountering small rate diff from bestRate. draw from relevant reserves
bestReserve = reserveCandidates[uint(block.blockhash(block.number-1)) % numRelevantReserves];
} else {
bestReserve = reserveCandidates[0];
}
bestRate = rates[bestReserve];
}
return (reserveArr[bestReserve], bestRate);
}
/* solhint-enable code-complexity */
function findBestRateTokenToToken(ERC20 src, ERC20 dest, uint srcAmount, bytes hint) internal view
returns(BestRateResult result)
{
//by default we use permission less reserves
bool usePermissionless = true;
// if hint in first 4 bytes == 'PERM' only permissioned reserves will be used.
if ((hint.length >= 4) && (keccak256(hint[0], hint[1], hint[2], hint[3]) == keccak256(PERM_HINT))) {
usePermissionless = false;
}
(result.reserve1, result.rateSrcToEth) =
searchBestRate(src, ETH_TOKEN_ADDRESS, srcAmount, usePermissionless);
result.weiAmount = calcDestAmount(src, ETH_TOKEN_ADDRESS, srcAmount, result.rateSrcToEth);
(result.reserve2, result.rateEthToDest) =
searchBestRate(ETH_TOKEN_ADDRESS, dest, result.weiAmount, usePermissionless);
result.destAmount = calcDestAmount(ETH_TOKEN_ADDRESS, dest, result.weiAmount, result.rateEthToDest);
result.rate = calcRateFromQty(srcAmount, result.destAmount, getDecimals(src), getDecimals(dest));
}
function listPairs(address reserve, ERC20 token, bool isTokenToEth, bool add) internal {
uint i;
address[] storage reserveArr = reservesPerTokenDest[token];
if (isTokenToEth) {
reserveArr = reservesPerTokenSrc[token];
}
for (i = 0; i < reserveArr.length; i++) {
if (reserve == reserveArr[i]) {
if (add) {
break; //already added
} else {
//remove
reserveArr[i] = reserveArr[reserveArr.length - 1];
reserveArr.length--;
break;
}
}
}
if (add && i == reserveArr.length) {
//if reserve wasn't found add it
reserveArr.push(reserve);
}
}
event KyberTrade(address indexed trader, ERC20 src, ERC20 dest, uint srcAmount, uint dstAmount,
address destAddress, uint ethWeiValue, address reserve1, address reserve2, bytes hint);
/* solhint-disable function-max-lines */
// Most of the lines here are functions calls spread over multiple lines. We find this function readable enough
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev trade api for kyber network.
/// @param tradeInput structure of trade inputs
function trade(TradeInput tradeInput) internal returns(uint) {
require(isEnabled);
require(tx.gasprice <= maxGasPriceValue);
require(validateTradeInput(tradeInput.src, tradeInput.srcAmount, tradeInput.dest, tradeInput.destAddress));
BestRateResult memory rateResult =
findBestRateTokenToToken(tradeInput.src, tradeInput.dest, tradeInput.srcAmount, tradeInput.hint);
require(rateResult.rate > 0);
require(rateResult.rate < MAX_RATE);
require(rateResult.rate >= tradeInput.minConversionRate);
uint actualDestAmount;
uint weiAmount;
uint actualSrcAmount;
(actualSrcAmount, weiAmount, actualDestAmount) = calcActualAmounts(tradeInput.src,
tradeInput.dest,
tradeInput.srcAmount,
tradeInput.maxDestAmount,
rateResult);
require(getUserCapInWei(tradeInput.trader) >= weiAmount);
require(handleChange(tradeInput.src, tradeInput.srcAmount, actualSrcAmount, tradeInput.trader));
require(doReserveTrade( //src to ETH
tradeInput.src,
actualSrcAmount,
ETH_TOKEN_ADDRESS,
this,
weiAmount,
KyberReserveInterface(rateResult.reserve1),
rateResult.rateSrcToEth,
true));
require(doReserveTrade( //Eth to dest
ETH_TOKEN_ADDRESS,
weiAmount,
tradeInput.dest,
tradeInput.destAddress,
actualDestAmount,
KyberReserveInterface(rateResult.reserve2),
rateResult.rateEthToDest,
true));
if (tradeInput.src != ETH_TOKEN_ADDRESS) //"fake" trade. (ether to ether) - don't burn.
require(feeBurnerContract.handleFees(weiAmount, rateResult.reserve1, tradeInput.walletId));
if (tradeInput.dest != ETH_TOKEN_ADDRESS) //"fake" trade. (ether to ether) - don't burn.
require(feeBurnerContract.handleFees(weiAmount, rateResult.reserve2, tradeInput.walletId));
KyberTrade({
trader: tradeInput.trader,
src: tradeInput.src,
dest: tradeInput.dest,
srcAmount: actualSrcAmount,
dstAmount: actualDestAmount,
destAddress: tradeInput.destAddress,
ethWeiValue: weiAmount,
reserve1: (tradeInput.src == ETH_TOKEN_ADDRESS) ? address(0) : rateResult.reserve1,
reserve2: (tradeInput.dest == ETH_TOKEN_ADDRESS) ? address(0) : rateResult.reserve2,
hint: tradeInput.hint
});
return actualDestAmount;
}
/* solhint-enable function-max-lines */
function calcActualAmounts (ERC20 src, ERC20 dest, uint srcAmount, uint maxDestAmount, BestRateResult rateResult)
internal view returns(uint actualSrcAmount, uint weiAmount, uint actualDestAmount)
{
if (rateResult.destAmount > maxDestAmount) {
actualDestAmount = maxDestAmount;
weiAmount = calcSrcAmount(ETH_TOKEN_ADDRESS, dest, actualDestAmount, rateResult.rateEthToDest);
actualSrcAmount = calcSrcAmount(src, ETH_TOKEN_ADDRESS, weiAmount, rateResult.rateSrcToEth);
require(actualSrcAmount <= srcAmount);
} else {
actualDestAmount = rateResult.destAmount;
actualSrcAmount = srcAmount;
weiAmount = rateResult.weiAmount;
}
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev do one trade with a reserve
/// @param src Src token
/// @param amount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param reserve Reserve to use
/// @param validate If true, additional validations are applicable
/// @return true if trade is successful
function doReserveTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserveInterface reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == dest) {
//this is for a "fake" trade when both src and dest are ethers.
if (destAddress != (address(this)))
destAddress.transfer(amount);
return true;
}
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
}
// reserve sends tokens/eth to network. network sends it to destination
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
if (destAddress != address(this)) {
//for token to token dest address is network. and Ether / token already here...
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, expectedDestAmount));
}
}
return true;
}
/// when user sets max dest amount we could have too many source tokens == change. so we send it back to user.
function handleChange (ERC20 src, uint srcAmount, uint requiredSrcAmount, address trader) internal returns (bool) {
if (requiredSrcAmount < srcAmount) {
//if there is "change" send back to trader
if (src == ETH_TOKEN_ADDRESS) {
trader.transfer(srcAmount - requiredSrcAmount);
} else {
require(src.transfer(trader, (srcAmount - requiredSrcAmount)));
}
}
return true;
}
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev checks that user sent ether/tokens to contract before trade
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @return true if tradeInput is valid
function validateTradeInput(ERC20 src, uint srcAmount, ERC20 dest, address destAddress)
internal
view
returns(bool)
{
require(srcAmount <= MAX_QTY);
require(srcAmount != 0);
require(destAddress != address(0));
require(src != dest);
if (src == ETH_TOKEN_ADDRESS) {
require(msg.value == srcAmount);
} else {
require(msg.value == 0);
//funds should have been moved to this contract already.
require(src.balanceOf(this) >= srcAmount);
}
return true;
}
}
| 80,216 |
2 | // address public constant CURVE_PREMINT_RESERVE = address(uint160(uint256(keccak256("CURVE_PREMINT_RESERVE")) - 1)); | address public constant CURVE_PREMINT_RESERVE = 0x3cc5B802b34A42Db4cBe41ae3aD5c06e1A4481c9;
| address public constant CURVE_PREMINT_RESERVE = 0x3cc5B802b34A42Db4cBe41ae3aD5c06e1A4481c9;
| 73,084 |
55 | // The next contract where the tokens will be migrated. | TokenUpgrader public tokenUpgrader;
| TokenUpgrader public tokenUpgrader;
| 13,266 |
32 | // Starting Added Time (SAT) | uint256 constant public SAT = 30; // seconds
| uint256 constant public SAT = 30; // seconds
| 15,751 |
12 | // Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) | function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
| function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
| 23,858 |
12 | // This allows for gas(less) future collection approval for cross-collection interaction. | mapping(address => bool) public proxyToApproved;
| mapping(address => bool) public proxyToApproved;
| 22,079 |
3 | // See {IERC721Collection-withdraw}. / | function withdraw(address payable recipient, uint256 amount) external override adminRequired {
_withdraw(recipient, amount);
}
| function withdraw(address payable recipient, uint256 amount) external override adminRequired {
_withdraw(recipient, amount);
}
| 62,807 |
9 | // transfer user's cashback to his wallet / | function withdrawCashback() public activeOnly {
uint256 amount = totalCashback[msg.sender];
totalCashback[msg.sender] = 0;
msg.sender.transfer(amount);
emit CashbackWithdrawn(msg.sender, amount);
}
| function withdrawCashback() public activeOnly {
uint256 amount = totalCashback[msg.sender];
totalCashback[msg.sender] = 0;
msg.sender.transfer(amount);
emit CashbackWithdrawn(msg.sender, amount);
}
| 31,840 |
26 | // As defined in the 'ERC777TokensSender And The tokensToSend Hook' section of https:eips.ethereum.org/EIPS/eip-777 | interface IERC777Sender {
function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata data,
bytes calldata operatorData) external;
}
| interface IERC777Sender {
function tokensToSend(address operator, address from, address to, uint256 amount, bytes calldata data,
bytes calldata operatorData) external;
}
| 2,481 |
126 | // Claim Aave. Also unstake all Aave if favorable condition exits or start cooldown. If we unstake all Aave, we can't start cooldown because it requires StakedAave balance. DO NOT convert 'if else' to 2 'if's as we are reading cooldown state once to save gas. / | function _claimAave() internal returns (uint256) {
(uint256 _cooldownStart, uint256 _cooldownEnd, uint256 _unstakeEnd) = cooldownData();
if (_cooldownStart == 0 || block.timestamp > _unstakeEnd) {
// claim stkAave when its first rebalance or unstake period passed.
address[] memory _assets = new address[](1);
_assets[0] = address(aToken);
IAaveIncentivesController(aToken.getIncentivesController()).claimRewards(
_assets,
type(uint256).max,
address(this)
);
}
// Fetch and check again for next action.
(_cooldownStart, _cooldownEnd, _unstakeEnd) = cooldownData();
if (_canUnstake(_cooldownEnd, _unstakeEnd)) {
stkAAVE.redeem(address(this), type(uint256).max);
} else if (_canStartCooldown(_cooldownStart, _unstakeEnd)) {
stkAAVE.cooldown();
}
stkAAVE.claimRewards(address(this), type(uint256).max);
return IERC20(AAVE).balanceOf(address(this));
}
| function _claimAave() internal returns (uint256) {
(uint256 _cooldownStart, uint256 _cooldownEnd, uint256 _unstakeEnd) = cooldownData();
if (_cooldownStart == 0 || block.timestamp > _unstakeEnd) {
// claim stkAave when its first rebalance or unstake period passed.
address[] memory _assets = new address[](1);
_assets[0] = address(aToken);
IAaveIncentivesController(aToken.getIncentivesController()).claimRewards(
_assets,
type(uint256).max,
address(this)
);
}
// Fetch and check again for next action.
(_cooldownStart, _cooldownEnd, _unstakeEnd) = cooldownData();
if (_canUnstake(_cooldownEnd, _unstakeEnd)) {
stkAAVE.redeem(address(this), type(uint256).max);
} else if (_canStartCooldown(_cooldownStart, _unstakeEnd)) {
stkAAVE.cooldown();
}
stkAAVE.claimRewards(address(this), type(uint256).max);
return IERC20(AAVE).balanceOf(address(this));
}
| 46,821 |
3 | // Emitted when ETH is transferred to a recipient through this split contract. account The account which received payment. amount The amount of ETH payment sent to this recipient. / | event ETHTransferred(address indexed account, uint256 amount);
| event ETHTransferred(address indexed account, uint256 amount);
| 20,182 |
116 | // Delegate call to get total supplyreturn Total supply / | function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
| function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
| 11,614 |
19 | // Emits an {Approval} event. Parameters check should be carried out before calling this function. / | function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| function _approve(address owner, address spender, uint256 amount) internal {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 36,732 |
74 | // Events | event Reinvest(address indexed caller, uint256 reward, uint256 bounty);
event AddShare(uint256 indexed id, uint256 share);
event RemoveShare(uint256 indexed id, uint256 share);
event Liquidate(uint256 indexed id, uint256 wad);
| event Reinvest(address indexed caller, uint256 reward, uint256 bounty);
event AddShare(uint256 indexed id, uint256 share);
event RemoveShare(uint256 indexed id, uint256 share);
event Liquidate(uint256 indexed id, uint256 wad);
| 43,218 |
1,500 | // 751 | entry "unpaced" : ENG_ADJECTIVE
| entry "unpaced" : ENG_ADJECTIVE
| 17,363 |
4 | // Creates a DataOrder. The `msg.sender` will become the buyer of the order. audience Target audience of the order. price Price that sellers will receive in exchange of their data. requestedData Requested data type (Geolocation, Facebook, etc). termsAndConditionsHash Hash of the Buyer's terms and conditions for the order. buyerUrl Public URL of the buyer where more information about the DataOrder can be obtained.return The index of the newly created DataOrder. If the DataOrder couldnot be created, reverts. / | function createDataOrder(
string calldata audience,
uint256 price,
string calldata requestedData,
bytes32 termsAndConditionsHash,
string calldata buyerUrl
| function createDataOrder(
string calldata audience,
uint256 price,
string calldata requestedData,
bytes32 termsAndConditionsHash,
string calldata buyerUrl
| 49,440 |
3 | // First delegate gets to initialize the delegator (i.e. storage contract) | delegateTo(implementation, abi.encodeWithSignature("initialize(address,address,address,address,uint256,uint256,string,string,uint8)",
underlying_,
registry_,
controller_,
interestRateModel_,
initialExchangeRateMantissa_,
initialReserveFactorMantissa_,
name_,
symbol_,
decimals_));
| delegateTo(implementation, abi.encodeWithSignature("initialize(address,address,address,address,uint256,uint256,string,string,uint8)",
underlying_,
registry_,
controller_,
interestRateModel_,
initialExchangeRateMantissa_,
initialReserveFactorMantissa_,
name_,
symbol_,
decimals_));
| 3,075 |
72 | // Tell the network... | emit onRebase(totalBalance(), _currentTimestamp);
| emit onRebase(totalBalance(), _currentTimestamp);
| 21,309 |
135 | // Safe NTS transfer function, just in case if rounding error causes pool to not have enough NTSs. | function safeNTSTransfer(address _to, uint256 _amount) internal {
uint256 NTSBal = NTS.balanceOf(address(this));
if (_amount > NTSBal) {
NTS.transfer(_to, NTSBal);
} else {
NTS.transfer(_to, _amount);
}
}
| function safeNTSTransfer(address _to, uint256 _amount) internal {
uint256 NTSBal = NTS.balanceOf(address(this));
if (_amount > NTSBal) {
NTS.transfer(_to, NTSBal);
} else {
NTS.transfer(_to, _amount);
}
}
| 15,713 |
3 | // Lib Sanitize/Utilities to sanitize input values | library LibSanitize {
/// @notice Reverts if address is 0
/// @param _address Address to check
function _notZeroAddress(address _address) internal pure {
if (_address == address(0)) {
revert LibErrors.InvalidZeroAddress();
}
}
/// @notice Reverts if string is empty
/// @param _string String to check
function _notEmptyString(string memory _string) internal pure {
if (bytes(_string).length == 0) {
revert LibErrors.InvalidEmptyString();
}
}
/// @notice Reverts if fee is invalid
/// @param _fee Fee to check
function _validFee(uint256 _fee) internal pure {
if (_fee > LibBasisPoints.BASIS_POINTS_MAX) {
revert LibErrors.InvalidFee();
}
}
}
| library LibSanitize {
/// @notice Reverts if address is 0
/// @param _address Address to check
function _notZeroAddress(address _address) internal pure {
if (_address == address(0)) {
revert LibErrors.InvalidZeroAddress();
}
}
/// @notice Reverts if string is empty
/// @param _string String to check
function _notEmptyString(string memory _string) internal pure {
if (bytes(_string).length == 0) {
revert LibErrors.InvalidEmptyString();
}
}
/// @notice Reverts if fee is invalid
/// @param _fee Fee to check
function _validFee(uint256 _fee) internal pure {
if (_fee > LibBasisPoints.BASIS_POINTS_MAX) {
revert LibErrors.InvalidFee();
}
}
}
| 43,500 |
147 | // Extend parent behavior requiring beneficiary to be in whitelist. _beneficiary Token beneficiary _weiAmount Amount of wei contributed / | function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
isWhitelisted(_beneficiary)
| function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
isWhitelisted(_beneficiary)
| 41,131 |
13 | // Vest the next PNG allocation. Requires vestingCliff seconds in between calls. PNG willbe distributed to the recipient. / | function claim() external nonReentrant returns (uint) {
require(vestingEnabled, 'TreasuryVester::claim: vesting not enabled');
require(msg.sender == recipient, 'TreasuryVester::claim: only recipient can claim');
require(block.timestamp >= lastUpdate + vestingCliff, 'TreasuryVester::claim: not time yet');
// If we've finished a halving period, reduce the amount
if (nextSlash == 0) {
nextSlash = halvingPeriod - 1;
vestingAmount = vestingAmount / 2;
} else {
nextSlash = nextSlash.sub(1);
}
// Update the timelock
lastUpdate = block.timestamp;
// Distribute the tokens
IERC20(png).safeTransfer(recipient, vestingAmount);
emit TokensVested(vestingAmount, recipient);
return vestingAmount;
}
| function claim() external nonReentrant returns (uint) {
require(vestingEnabled, 'TreasuryVester::claim: vesting not enabled');
require(msg.sender == recipient, 'TreasuryVester::claim: only recipient can claim');
require(block.timestamp >= lastUpdate + vestingCliff, 'TreasuryVester::claim: not time yet');
// If we've finished a halving period, reduce the amount
if (nextSlash == 0) {
nextSlash = halvingPeriod - 1;
vestingAmount = vestingAmount / 2;
} else {
nextSlash = nextSlash.sub(1);
}
// Update the timelock
lastUpdate = block.timestamp;
// Distribute the tokens
IERC20(png).safeTransfer(recipient, vestingAmount);
emit TokensVested(vestingAmount, recipient);
return vestingAmount;
}
| 30,423 |
3 | // Modifier to ensure only current EVs can execute a function | modifier onlyEv() {
require(current_evs[msg.sender] == true);
_;
}
| modifier onlyEv() {
require(current_evs[msg.sender] == true);
_;
}
| 47,612 |
11 | // Marketing100,000,000 (10%) | uint constant public maxMktSupply = 100000000 * E18;
| uint constant public maxMktSupply = 100000000 * E18;
| 83,436 |
10 | // ---------------------------------------------------DPS:TEST : NEW | if (_key == 170) {
trustedAgentEnabled = 0; //-------------------THIS IS A PERMANENT ACTION AND CANNOT BE UNDONE
}
| if (_key == 170) {
trustedAgentEnabled = 0; //-------------------THIS IS A PERMANENT ACTION AND CANNOT BE UNDONE
}
| 32,925 |
16 | // change the Transaction cost_newTxFee the new Transaction cost | function setTxFee( uint256 _newTxFee ) onlyOwner external {
txFee = _newTxFee;
emit SetTxFee( _newTxFee );
}
| function setTxFee( uint256 _newTxFee ) onlyOwner external {
txFee = _newTxFee;
emit SetTxFee( _newTxFee );
}
| 29,781 |
37 | // Public sale is not open yet | require(PublicSaleActived, 'Not open yet!');
| require(PublicSaleActived, 'Not open yet!');
| 67,289 |
5 | // Gets the tokens scheduled to be distributed for a specific period. / | function getTokensForPeriod(uint256 _periodIndex)
external
view
override
returns (uint256)
| function getTokensForPeriod(uint256 _periodIndex)
external
view
override
returns (uint256)
| 23,460 |
16 | // address of distributor | address public distributor;
| address public distributor;
| 14,305 |
5 | // Returns a list of all supported pools. | function allPools() external view returns (Pool[] memory pools);
| function allPools() external view returns (Pool[] memory pools);
| 8,116 |
87 | // Send to Marketing address | transferToAddressETH(marketingAddress, transferredBalance.mul(marketingDivisor).div(100));
| transferToAddressETH(marketingAddress, transferredBalance.mul(marketingDivisor).div(100));
| 2,882 |
56 | // User provided data for app callbacks | bytes userData;
| bytes userData;
| 23,962 |
2 | // =============================================== Setters ======================================================== |
function sendCoins()
public
|
function sendCoins()
public
| 26,941 |
90 | // keep track of issuers | for(uint256 i=0; i<issuers.length; i++){
if(issuers[i]==payer)
found = true;
}
| for(uint256 i=0; i<issuers.length; i++){
if(issuers[i]==payer)
found = true;
}
| 26,140 |
84 | // View function to see pending Apes on frontend. | function pendingAPE(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accApePerShare = pool.accApePerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _apeReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accApePerShare = accApePerShare.add(_apeReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accApePerShare).div(1e18).sub(user.rewardDebt);
}
| function pendingAPE(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accApePerShare = pool.accApePerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _apeReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accApePerShare = accApePerShare.add(_apeReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accApePerShare).div(1e18).sub(user.rewardDebt);
}
| 81,028 |
41 | // Logged when the owner of a node transfers ownership to a new account. | event Transfer(bytes32 indexed node, address owner);
| event Transfer(bytes32 indexed node, address owner);
| 2,750 |
6 | // Reflection Token | address public reflectionToken;
uint256 public accReflectionPerPoint;
bool public hasDividend;
bool public autoAdjustableForRewardRate = false;
| address public reflectionToken;
uint256 public accReflectionPerPoint;
bool public hasDividend;
bool public autoAdjustableForRewardRate = false;
| 7,813 |
10 | // Meta numberOfSides,targetSupply, prize, gradientDominator, ended | function getMatch(uint256 _index) public view returns(uint8, uint256, uint256, uint256, bool) {
return (matches[_index].numberOfSides, matches[_index].targetSupply, matches[_index].prize, matches[_index].gradient, matches[_index].ended);
}
| function getMatch(uint256 _index) public view returns(uint8, uint256, uint256, uint256, bool) {
return (matches[_index].numberOfSides, matches[_index].targetSupply, matches[_index].prize, matches[_index].gradient, matches[_index].ended);
}
| 13,813 |
2 | // The operator can only update EmissionRate and AllocPoint to protect tokenomicsi.e some wrong setting and a pools get too much allocation accidentally | address private _operator;
| address private _operator;
| 28,484 |
9 | // The block number when PAW mining starts. | uint256 public immutable startBlock;
event Add(address indexed user, uint256 allocPoint, IERC20 indexed token, bool massUpdatePools);
event Set(address indexed user, uint256 pid, uint256 allocPoint);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool harvest);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool harvest);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event HarvestMultiple(address indexed user, uint256[] _pids, uint256 amount);
event HarvestAll(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
| uint256 public immutable startBlock;
event Add(address indexed user, uint256 allocPoint, IERC20 indexed token, bool massUpdatePools);
event Set(address indexed user, uint256 pid, uint256 allocPoint);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool harvest);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool harvest);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event HarvestMultiple(address indexed user, uint256[] _pids, uint256 amount);
event HarvestAll(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
| 12,969 |
1 | // Calculated borrow rate based on expectedLiquidity and availableLiquidity/expectedLiquidity Expected liquidity in the pool/availableLiquidity Available liquidity in the pool | function calcBorrowRate(uint256 expectedLiquidity, uint256 availableLiquidity)
external
view
returns (uint256);
| function calcBorrowRate(uint256 expectedLiquidity, uint256 availableLiquidity)
external
view
returns (uint256);
| 6,778 |
2 | // It emits with the user's address and the the value after the change. | event ProductivityIncreased(address indexed user, uint256 value); /// @dev This emit when a users' productivity has changed
| event ProductivityIncreased(address indexed user, uint256 value); /// @dev This emit when a users' productivity has changed
| 17,059 |
13 | // See {IERC1155Collection-withdraw}. / | function withdraw(address payable recipient, uint256 amount) external override adminRequired {
_withdraw(recipient, amount);
}
| function withdraw(address payable recipient, uint256 amount) external override adminRequired {
_withdraw(recipient, amount);
}
| 7,095 |
13 | // ERC721AQueryable.ERC721A subclass with convenience query functions. / | abstract contract ERC721AQueryable is ERC721A, IERC721AQueryable {
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
*
* - `addr = address(0)`
* - `startTimestamp = 0`
* - `burned = false`
* - `extraData = 0`
*
* If the `tokenId` is burned:
*
* - `addr = <Address of owner before token was burned>`
* - `startTimestamp = <Timestamp when token was burned>`
* - `burned = true`
* - `extraData = <Extra data when token was burned>`
*
* Otherwise:
*
* - `addr = <Address of owner>`
* - `startTimestamp = <Timestamp of start of ownership>`
* - `burned = false`
* - `extraData = <Extra data at start of ownership>`
*/
function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] calldata tokenIds)
external
view
virtual
override
returns (TokenOwnership[] memory)
{
unchecked {
uint256 tokenIdsLength = tokenIds.length;
TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
for (uint256 i; i != tokenIdsLength; ++i) {
ownerships[i] = explicitOwnershipOf(tokenIds[i]);
}
return ownerships;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start < stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view virtual override returns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _nextTokenId();
// Set `start = max(start, _startTokenId())`.
if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, stopLimit)`.
if (stop > stopLimit) {
stop = stopLimit;
}
uint256 tokenIdsMaxLength = balanceOf(owner);
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
// to cater for cases where `balanceOf(owner)` is too big.
if (start < stop) {
uint256 rangeLength = stop - start;
if (rangeLength < tokenIdsMaxLength) {
tokenIdsMaxLength = rangeLength;
}
} else {
tokenIdsMaxLength = 0;
}
uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
if (tokenIdsMaxLength == 0) {
return tokenIds;
}
// We need to call `explicitOwnershipOf(start)`,
// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
// `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
// Downsize the array to fit.
assembly {
mstore(tokenIds, tokenIdsIdx)
}
return tokenIds;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(`totalSupply`) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K collections should be fine).
*/
function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
}
| abstract contract ERC721AQueryable is ERC721A, IERC721AQueryable {
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
*
* - `addr = address(0)`
* - `startTimestamp = 0`
* - `burned = false`
* - `extraData = 0`
*
* If the `tokenId` is burned:
*
* - `addr = <Address of owner before token was burned>`
* - `startTimestamp = <Timestamp when token was burned>`
* - `burned = true`
* - `extraData = <Extra data when token was burned>`
*
* Otherwise:
*
* - `addr = <Address of owner>`
* - `startTimestamp = <Timestamp of start of ownership>`
* - `burned = false`
* - `extraData = <Extra data at start of ownership>`
*/
function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] calldata tokenIds)
external
view
virtual
override
returns (TokenOwnership[] memory)
{
unchecked {
uint256 tokenIdsLength = tokenIds.length;
TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
for (uint256 i; i != tokenIdsLength; ++i) {
ownerships[i] = explicitOwnershipOf(tokenIds[i]);
}
return ownerships;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start < stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view virtual override returns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _nextTokenId();
// Set `start = max(start, _startTokenId())`.
if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, stopLimit)`.
if (stop > stopLimit) {
stop = stopLimit;
}
uint256 tokenIdsMaxLength = balanceOf(owner);
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
// to cater for cases where `balanceOf(owner)` is too big.
if (start < stop) {
uint256 rangeLength = stop - start;
if (rangeLength < tokenIdsMaxLength) {
tokenIdsMaxLength = rangeLength;
}
} else {
tokenIdsMaxLength = 0;
}
uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
if (tokenIdsMaxLength == 0) {
return tokenIds;
}
// We need to call `explicitOwnershipOf(start)`,
// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
// `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
// Downsize the array to fit.
assembly {
mstore(tokenIds, tokenIdsIdx)
}
return tokenIds;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(`totalSupply`) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K collections should be fine).
*/
function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
}
| 34,655 |
30 | // Call this when in Phase.Enrollment for more than joinTimeout blocks and not enough members have joined. | function joinTimedOut()
inPhase(Phase.Enrollment)
external
| function joinTimedOut()
inPhase(Phase.Enrollment)
external
| 31,190 |
29 | // The duration of voting on a proposal, in blocks | function votingPeriod() external pure returns (uint);
| function votingPeriod() external pure returns (uint);
| 16,972 |
28 | // Calculate the amount of underlying token available to withdrawwhen withdrawing via only single token account the address that is withdrawing tokens tokenAmount the amount of LP token to burn tokenIndex index of which token will be withdrawnreturn availableTokenAmount calculated amount of underlying tokenavailable to withdraw / | function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
| function calculateRemoveLiquidityOneToken(
address account,
uint256 tokenAmount,
uint8 tokenIndex
| 5,461 |
32 | // note: Testing revert condition; token owner calls `wrap` with insufficient value when wrapping native tokens. / | function test_revert_wrap_nativeTokens_insufficientValue() public {
address recipient = address(0x123);
ITokenBundle.Token[] memory nativeTokenContentToWrap = new ITokenBundle.Token[](1);
vm.deal(address(tokenOwner), 100 ether);
nativeTokenContentToWrap[0] = ITokenBundle.Token({
assetContract: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE,
tokenType: ITokenBundle.TokenType.ERC20,
tokenId: 0,
totalAmount: 10 ether
});
vm.prank(address(tokenOwner));
vm.expectRevert("msg.value != amount");
multiwrap.wrap(nativeTokenContentToWrap, uriForWrappedToken, recipient);
}
| function test_revert_wrap_nativeTokens_insufficientValue() public {
address recipient = address(0x123);
ITokenBundle.Token[] memory nativeTokenContentToWrap = new ITokenBundle.Token[](1);
vm.deal(address(tokenOwner), 100 ether);
nativeTokenContentToWrap[0] = ITokenBundle.Token({
assetContract: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE,
tokenType: ITokenBundle.TokenType.ERC20,
tokenId: 0,
totalAmount: 10 ether
});
vm.prank(address(tokenOwner));
vm.expectRevert("msg.value != amount");
multiwrap.wrap(nativeTokenContentToWrap, uriForWrappedToken, recipient);
}
| 4,909 |
23 | // Players only paying ============================================ | function payToCharm(string toCharmName, uint256 value) onlyPlayers {
require(_validCharm(toCharmName));
_transfer(msg.sender, ownerToCharm[msg.sender], charmToOwner[toCharmName], toCharmName, value);
}
| function payToCharm(string toCharmName, uint256 value) onlyPlayers {
require(_validCharm(toCharmName));
_transfer(msg.sender, ownerToCharm[msg.sender], charmToOwner[toCharmName], toCharmName, value);
}
| 25,771 |
8 | // EnumDefinition | enum Enum { E1, E2 }
| enum Enum { E1, E2 }
| 54,993 |
38 | // Allows the owner to change the symbol of the contract / | function changeSymbol(bytes32 newSymbol) onlyOwner() public {
symbol = newSymbol;
}
| function changeSymbol(bytes32 newSymbol) onlyOwner() public {
symbol = newSymbol;
}
| 41,337 |
114 | // Enum describing the current state of a loanState change flow: Created -> Active -> Repaid -> Auction -> Defaulted / | enum LoanState {
// We need a default that is not 'Created' - this is the zero value
None,
// The loan data is stored, but not initiated yet.
Created,
// The loan has been initialized, funds have been delivered to the borrower and the collateral is held.
Active,
// The loan is in auction, higest price liquidator will got chance to claim it.
Auction,
// The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.
Repaid,
// The loan was delinquent and collateral claimed by the liquidator. This is a terminal state.
Defaulted
}
| enum LoanState {
// We need a default that is not 'Created' - this is the zero value
None,
// The loan data is stored, but not initiated yet.
Created,
// The loan has been initialized, funds have been delivered to the borrower and the collateral is held.
Active,
// The loan is in auction, higest price liquidator will got chance to claim it.
Auction,
// The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.
Repaid,
// The loan was delinquent and collateral claimed by the liquidator. This is a terminal state.
Defaulted
}
| 26,348 |
39 | // Variables related to fees | mapping (address => uint) private _isTimeLimit;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _excludeFromMaxTxLimit;
mapping (address => bool) private _excludeFromTimeLimit;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private _FDTeamTax = 200;
uint256 private _PromoTax= 200;
uint256 private _BurnTax= 100;
| mapping (address => uint) private _isTimeLimit;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _excludeFromMaxTxLimit;
mapping (address => bool) private _excludeFromTimeLimit;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private _FDTeamTax = 200;
uint256 private _PromoTax= 200;
uint256 private _BurnTax= 100;
| 3,050 |
3 | // HUNDRED_PERCENT Calculate what % we are off from the target | uint256 deltaAbsolute = totalStakedNowPercentage < stakeTarget
? stakeTarget - totalStakedNowPercentage
: totalStakedNowPercentage - stakeTarget;
uint256 deltaPercentage = deltaAbsolute * HUNDRED_PERCENT / stakeTarget;
| uint256 deltaAbsolute = totalStakedNowPercentage < stakeTarget
? stakeTarget - totalStakedNowPercentage
: totalStakedNowPercentage - stakeTarget;
uint256 deltaPercentage = deltaAbsolute * HUNDRED_PERCENT / stakeTarget;
| 9,356 |
2 | // Allowed withdrawals of previous bids | mapping(address => uint) pendingReturns;
| mapping(address => uint) pendingReturns;
| 16,163 |
0 | // DNN Token Contract/ | DNNToken public dnnToken;
| DNNToken public dnnToken;
| 45,950 |
32 | // Public Functions //Set claim status and partially or fully approve claim. By Lockdrop contract creator only Allow the combined approved amount for lock and signal to be greater than the current user token balance since setting the claim status may occur after the term is finished when the user may have already moved the funds that they locked or signaled. / | function setClaimStatus(address _user, ClaimType _claimType, address _tokenContractAddress,
ClaimStatus _claimStatus, uint256 _approvedTokenERC20Amount, uint256 _pendingTokenERC20Amount, uint256 _rejectedTokenERC20Amount
)
public onlylockdropContractCreator
| function setClaimStatus(address _user, ClaimType _claimType, address _tokenContractAddress,
ClaimStatus _claimStatus, uint256 _approvedTokenERC20Amount, uint256 _pendingTokenERC20Amount, uint256 _rejectedTokenERC20Amount
)
public onlylockdropContractCreator
| 20,903 |
76 | // Removes single address from whitelist./_beneficiary Address to be removed to the whitelist | function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
WhitelistAddressRemoved(_beneficiary);
}
| function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
WhitelistAddressRemoved(_beneficiary);
}
| 7,510 |
7 | // bytes4(keccak256("Error(string)")) | mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
| mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
| 39,093 |
8 | // Ratio of (time elapsed since last claim) / (duration of vesting schedule). | uint256 lastTimeApplicable = (block.timestamp >= schedule.endTime) ? schedule.endTime : block.timestamp;
uint256 availableTokens = schedule.numberOfTokens.mul(lastTimeApplicable.sub(schedule.lastClaimTime)).div(schedule.endTime.sub(schedule.startTime));
schedules[msg.sender].lastClaimTime = block.timestamp;
claimedTokens[msg.sender] = claimedTokens[msg.sender].add(availableTokens);
tokensVesting = (availableTokens >= tokensVesting) ? 0 : tokensVesting.sub(availableTokens);
TGEN.transfer(msg.sender, availableTokens);
emit ClaimedTokens(msg.sender, availableTokens);
| uint256 lastTimeApplicable = (block.timestamp >= schedule.endTime) ? schedule.endTime : block.timestamp;
uint256 availableTokens = schedule.numberOfTokens.mul(lastTimeApplicable.sub(schedule.lastClaimTime)).div(schedule.endTime.sub(schedule.startTime));
schedules[msg.sender].lastClaimTime = block.timestamp;
claimedTokens[msg.sender] = claimedTokens[msg.sender].add(availableTokens);
tokensVesting = (availableTokens >= tokensVesting) ? 0 : tokensVesting.sub(availableTokens);
TGEN.transfer(msg.sender, availableTokens);
emit ClaimedTokens(msg.sender, availableTokens);
| 9,462 |
81 | // ambassador pre-mine within 1 hour before startTime, sequences enforced | (now >= startTime - 1 hours && !ambassadorsPremined[msg.sender] && ambassadorsPremined[ambassadorsPrerequisite[msg.sender]] && _incomingEthereum <= ambassadorsMaxPremine[msg.sender]) ||
| (now >= startTime - 1 hours && !ambassadorsPremined[msg.sender] && ambassadorsPremined[ambassadorsPrerequisite[msg.sender]] && _incomingEthereum <= ambassadorsMaxPremine[msg.sender]) ||
| 22,981 |
36 | // Update users reward debt | user.rewardDebt = boostedLiquidityAfter.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION);
| user.rewardDebt = boostedLiquidityAfter.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION);
| 14,481 |
123 | // Gets the token ID at a given index of all the tokens in this contractReverts if the index is greater or equal to the total number of tokens. _index uint256 representing the index to be accessed of the tokens listreturn uint256 token ID at the given index of the tokens list / | function tokenByIndex(uint256 _index) public view returns (uint256) {
(uint256 tokenId, ) = tokenOwners.at(_index);
return tokenId;
}
| function tokenByIndex(uint256 _index) public view returns (uint256) {
(uint256 tokenId, ) = tokenOwners.at(_index);
return tokenId;
}
| 50,413 |
6 | // https:github.com/m1guelpf/erc721-drop/blob/main/src/LilOwnable.sol | abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
constructor() {
_owner = msg.sender;
}
function owner() external view returns (address) {
return _owner;
}
function transferOwnership(address _newOwner) external {
if (msg.sender != _owner) revert NotOwner();
_owner = _newOwner;
}
function renounceOwnership() public {
if (msg.sender != _owner) revert NotOwner();
_owner = address(0);
}
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
returns (bool)
{
return interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173
}
}
| abstract contract Ownable {
address internal _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(_owner == msg.sender);
_;
}
constructor() {
_owner = msg.sender;
}
function owner() external view returns (address) {
return _owner;
}
function transferOwnership(address _newOwner) external {
if (msg.sender != _owner) revert NotOwner();
_owner = _newOwner;
}
function renounceOwnership() public {
if (msg.sender != _owner) revert NotOwner();
_owner = address(0);
}
function supportsInterface(bytes4 interfaceId)
public
pure
virtual
returns (bool)
{
return interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173
}
}
| 35,426 |
82 | // Gets the balance of the specified address._owner The address to query the the balance of. return An uint256 representing the amount owned by the passed address./ | function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
| function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
| 40,832 |
8 | // ------------------------ SafeMath Library ------------------------- | library SafeMath {
|/ |/ /___) / / ' / ) / / ) /___) / / )
__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_
____ _____ _____ _____
| _ \ / ____|/ ____| | __ \
| |_) | (___ | | | | | | _____ __
| _ < \___ \| | | | | |/ _ \ \/ /
| |_) |____) | |____ | |__| | __/> <
|____/|_____/ \_____| |_____/ \___/_/\_\
------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
| library SafeMath {
|/ |/ /___) / / ' / ) / / ) /___) / / )
__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_
____ _____ _____ _____
| _ \ / ____|/ ____| | __ \
| |_) | (___ | | | | | | _____ __
| _ < \___ \| | | | | |/ _ \ \/ /
| |_) |____) | |____ | |__| | __/> <
|____/|_____/ \_____| |_____/ \___/_/\_\
------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
| 25,031 |
0 | // return whether given signature is signed by contract owner / | function _isValidSignature (
bytes32 hash,
bytes memory signature
| function _isValidSignature (
bytes32 hash,
bytes memory signature
| 5,521 |
15 | // callback function to keep the returned value from Oracle contract / | function fulfill(bytes32 _requestId, uint256 _data)
public
recordChainlinkFulfillment(_requestId)
| function fulfill(bytes32 _requestId, uint256 _data)
public
recordChainlinkFulfillment(_requestId)
| 9,105 |
12 | // Product id => order | mapping(uint256 => Order) public orderById;
| mapping(uint256 => Order) public orderById;
| 40,066 |
30 | // retrieve stable coins total staked per user in epoch | uint valueUsdc = _staking.getEpochUserBalance(userAddress, _usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground
uint valueSusd = _staking.getEpochUserBalance(userAddress, _susd, epochId);
uint valueDai = _staking.getEpochUserBalance(userAddress, _dai, epochId);
return valueUsdc.add(valueSusd).add(valueDai);
| uint valueUsdc = _staking.getEpochUserBalance(userAddress, _usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground
uint valueSusd = _staking.getEpochUserBalance(userAddress, _susd, epochId);
uint valueDai = _staking.getEpochUserBalance(userAddress, _dai, epochId);
return valueUsdc.add(valueSusd).add(valueDai);
| 42,521 |
14 | // Returns the scaled balance of the user and the scaled total supply. user The address of the userreturn The scaled balance of the userreturn The scaled balance and the scaled total supply / | {
return (super.balanceOf(user), super.totalSupply());
}
| {
return (super.balanceOf(user), super.totalSupply());
}
| 21,852 |
13 | // Withdraws refund amount/ return refundAmount Refund amount | function refund()
public
timedTransitions
atStage(Stages.AuctionFailed)
returns (uint refundAmount)
| function refund()
public
timedTransitions
atStage(Stages.AuctionFailed)
returns (uint refundAmount)
| 23,898 |
920 | // 461 | entry "unmonetized" : ENG_ADJECTIVE
| entry "unmonetized" : ENG_ADJECTIVE
| 17,073 |
211 | // Mint claimable giraffes to sender | for (uint256 i = 0; i < claimableGiraffes/100; i++) {
uint256 index = totalSupply();
if (index < maxGiraffes) {
_safeMint(msg.sender, index);
}
| for (uint256 i = 0; i < claimableGiraffes/100; i++) {
uint256 index = totalSupply();
if (index < maxGiraffes) {
_safeMint(msg.sender, index);
}
| 51,338 |
140 | // Emit an event to track the minting | emit Transfer(address(0), account, amount);
| emit Transfer(address(0), account, amount);
| 15,256 |
32 | // Get the amount of this pools token owned by the SaffronStaking contract | uint256 lpSupply = pool.lpToken.balanceOf(address(this));
| uint256 lpSupply = pool.lpToken.balanceOf(address(this));
| 21,824 |
34 | // Storage for Governor Bravo Delegate For future upgrades, do not change DegenDAOStorageV1. Create a newcontract which implements DegenDAOStorageV1 and following the naming conventionDegenDAOStorageVX. / | contract DegenDAOStorageV1 is DegenDAOProxyStorage {
/// @notice Vetoer who has the ability to veto any proposal
address public vetoer;
/// @notice The delay before voting on a proposal may take place, once proposed, in blocks
uint256 public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint256 public votingPeriod;
/// @notice The basis point number of votes required in order for a voter to become a proposer. *DIFFERS from GovernerBravo
uint256 public proposalThresholdBPS;
/// @notice The basis point number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed. *DIFFERS from GovernerBravo
uint256 public quorumVotesBPS;
/// @notice The total number of proposals
uint256 public proposalCount;
/// @notice The address of the Nouns DAO Executor DegenDAOExecutor
IDegenDAOExecutor public timelock;
/// @notice The address of the Nouns tokens
DogsTokenLike public dogs;
/// @notice The official record of all proposals ever proposed
mapping(uint256 => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping(address => uint256) public latestProposalIds;
struct Proposal {
uint256 id;
address proposer;
uint256 proposalThreshold;
uint256 quorumVotes;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool vetoed;
bool executed;
mapping(address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed,
Vetoed
}
}
| contract DegenDAOStorageV1 is DegenDAOProxyStorage {
/// @notice Vetoer who has the ability to veto any proposal
address public vetoer;
/// @notice The delay before voting on a proposal may take place, once proposed, in blocks
uint256 public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint256 public votingPeriod;
/// @notice The basis point number of votes required in order for a voter to become a proposer. *DIFFERS from GovernerBravo
uint256 public proposalThresholdBPS;
/// @notice The basis point number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed. *DIFFERS from GovernerBravo
uint256 public quorumVotesBPS;
/// @notice The total number of proposals
uint256 public proposalCount;
/// @notice The address of the Nouns DAO Executor DegenDAOExecutor
IDegenDAOExecutor public timelock;
/// @notice The address of the Nouns tokens
DogsTokenLike public dogs;
/// @notice The official record of all proposals ever proposed
mapping(uint256 => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping(address => uint256) public latestProposalIds;
struct Proposal {
uint256 id;
address proposer;
uint256 proposalThreshold;
uint256 quorumVotes;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint256 startBlock;
uint256 endBlock;
uint256 forVotes;
uint256 againstVotes;
uint256 abstainVotes;
bool canceled;
bool vetoed;
bool executed;
mapping(address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed,
Vetoed
}
}
| 38,079 |
90 | // This contract is used to generate clone contracts from a contract./In solidity this is the way to create a contract from a contract of the/same class | contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
| contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
| 20,015 |
20 | // Conversion functionality for migrating VNL v1 tokens to VNL v1.1 | abstract contract VanillaV1Converter is IVanillaV1Converter {
/// @inheritdoc IVanillaV1Converter
IVanillaV1MigrationState public override migrationState;
IERC20 internal vnl;
constructor(IVanillaV1MigrationState _state, IERC20 _VNLv1) {
migrationState = _state;
vnl = _VNLv1;
}
function mintConverted(address target, uint256 amount) internal virtual;
/// @inheritdoc IVanillaV1Converter
function checkEligibility(bytes32[] memory proof) external view override returns (bool convertible, bool transferable) {
uint256 balance = vnl.balanceOf(msg.sender);
convertible = migrationState.verifyEligibility(proof, msg.sender, balance);
transferable = balance > 0 && vnl.allowance(msg.sender, address(this)) >= balance;
}
/// @inheritdoc IVanillaV1Converter
function convertVNL(bytes32[] memory proof) external override {
if (block.timestamp >= migrationState.conversionDeadline()) {
revert ConversionWindowClosed();
}
uint256 convertedAmount = vnl.balanceOf(msg.sender);
if (convertedAmount == 0) {
revert NoConvertibleVNL();
}
// because VanillaV1Token01's cannot be burned, the conversion just locks them into this contract permanently
address freezer = address(this);
uint256 previouslyFrozen = vnl.balanceOf(freezer);
// we know that OpenZeppelin ERC20 returns always true and reverts on failure, so no need to check the return value
vnl.transferFrom(msg.sender, freezer, convertedAmount);
// These should never fail as we know precisely how VanillaV1Token01.transferFrom is implemented
if (vnl.balanceOf(freezer) != previouslyFrozen + convertedAmount) {
revert FreezerBalanceMismatch();
}
if (vnl.balanceOf(msg.sender) > 0) {
revert UnexpectedTokensAfterConversion();
}
if (!migrationState.verifyEligibility(proof, msg.sender, convertedAmount)) {
revert VerificationFailed();
}
// finally let implementor to mint the converted amount of tokens and log the event
mintConverted(msg.sender, convertedAmount);
emit VNLConverted(msg.sender, convertedAmount);
}
}
| abstract contract VanillaV1Converter is IVanillaV1Converter {
/// @inheritdoc IVanillaV1Converter
IVanillaV1MigrationState public override migrationState;
IERC20 internal vnl;
constructor(IVanillaV1MigrationState _state, IERC20 _VNLv1) {
migrationState = _state;
vnl = _VNLv1;
}
function mintConverted(address target, uint256 amount) internal virtual;
/// @inheritdoc IVanillaV1Converter
function checkEligibility(bytes32[] memory proof) external view override returns (bool convertible, bool transferable) {
uint256 balance = vnl.balanceOf(msg.sender);
convertible = migrationState.verifyEligibility(proof, msg.sender, balance);
transferable = balance > 0 && vnl.allowance(msg.sender, address(this)) >= balance;
}
/// @inheritdoc IVanillaV1Converter
function convertVNL(bytes32[] memory proof) external override {
if (block.timestamp >= migrationState.conversionDeadline()) {
revert ConversionWindowClosed();
}
uint256 convertedAmount = vnl.balanceOf(msg.sender);
if (convertedAmount == 0) {
revert NoConvertibleVNL();
}
// because VanillaV1Token01's cannot be burned, the conversion just locks them into this contract permanently
address freezer = address(this);
uint256 previouslyFrozen = vnl.balanceOf(freezer);
// we know that OpenZeppelin ERC20 returns always true and reverts on failure, so no need to check the return value
vnl.transferFrom(msg.sender, freezer, convertedAmount);
// These should never fail as we know precisely how VanillaV1Token01.transferFrom is implemented
if (vnl.balanceOf(freezer) != previouslyFrozen + convertedAmount) {
revert FreezerBalanceMismatch();
}
if (vnl.balanceOf(msg.sender) > 0) {
revert UnexpectedTokensAfterConversion();
}
if (!migrationState.verifyEligibility(proof, msg.sender, convertedAmount)) {
revert VerificationFailed();
}
// finally let implementor to mint the converted amount of tokens and log the event
mintConverted(msg.sender, convertedAmount);
emit VNLConverted(msg.sender, convertedAmount);
}
}
| 67,201 |
53 | // set the initial nonce to be provided when constructing the salt. | uint256 nonce = 0;
| uint256 nonce = 0;
| 23,388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.