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
|
---|---|---|---|---|
4 | // It is ok to check for strict equality since the numberOfApprovalsFromSecurityCouncil is increased by one at a time. It is better to do so not to emit the CandidateAccepted event more than once | if (numberOfApprovalsFromSecurityCouncil == securityCouncilThreshold) {
oldRootHash = candidateOldRootHash;
newRootHash = candidateNewRootHash;
emit CandidateAccepted(oldRootHash, newRootHash);
}
| if (numberOfApprovalsFromSecurityCouncil == securityCouncilThreshold) {
oldRootHash = candidateOldRootHash;
newRootHash = candidateNewRootHash;
emit CandidateAccepted(oldRootHash, newRootHash);
}
| 8,585 |
186 | // Start farming Only dev can call this function | function start() public {
require(msg.sender == treasury, 'Only dev can start farming');
require(farmingStartTimestamp == 0, 'Farming has already started');
farmingStartTimestamp = block.timestamp;
}
| function start() public {
require(msg.sender == treasury, 'Only dev can start farming');
require(farmingStartTimestamp == 0, 'Farming has already started');
farmingStartTimestamp = block.timestamp;
}
| 78,116 |
127 | // TODO: should split back to original tokens | uint256 feeAmount = systemFeeAmount + treasuryFeeAmount;
if (feeAmount > 0) {
(uint256 amountToken0, uint256 amountToken1) = removeLiquidity(feeAmount);
uint256 systemFeeAmountToken0 = amountToken0 * systemFeeAmount / (feeAmount);
IERC20(lpToken0).safeTransfer(systemFeeRecipient, systemFeeAmountToken0);
IERC20(lpToken0).safeTransfer(treasuryFeeRecipient, amountToken0 - systemFeeAmountToken0);
uint256 systemFeeAmountToken1 = amountToken1 * systemFeeAmount / (feeAmount);
IERC20(lpToken1).safeTransfer(systemFeeRecipient, systemFeeAmountToken1);
| uint256 feeAmount = systemFeeAmount + treasuryFeeAmount;
if (feeAmount > 0) {
(uint256 amountToken0, uint256 amountToken1) = removeLiquidity(feeAmount);
uint256 systemFeeAmountToken0 = amountToken0 * systemFeeAmount / (feeAmount);
IERC20(lpToken0).safeTransfer(systemFeeRecipient, systemFeeAmountToken0);
IERC20(lpToken0).safeTransfer(treasuryFeeRecipient, amountToken0 - systemFeeAmountToken0);
uint256 systemFeeAmountToken1 = amountToken1 * systemFeeAmount / (feeAmount);
IERC20(lpToken1).safeTransfer(systemFeeRecipient, systemFeeAmountToken1);
| 33,084 |
7 | // Store info about this hashType | _hashType.name = _name;
_hashType.active = true;
| _hashType.name = _name;
_hashType.active = true;
| 7,687 |
9 | // require that the amount is not 0, address is not the 0 address, and that the expiration date is actually beyond now | require(_amount > 0 && _token != address(0) && _unlockDate > block.timestamp, 'NFT01');
| require(_amount > 0 && _token != address(0) && _unlockDate > block.timestamp, 'NFT01');
| 19,474 |
69 | // return the start time of the token vesting. / | function start() public view returns (uint256) {
return _start;
}
| function start() public view returns (uint256) {
return _start;
}
| 13,884 |
2 | // calculate hash of asset type/ assetType to be hashed/return hash of assetType | function hash(AssetType memory assetType) internal pure returns (bytes32) {
return keccak256(abi.encode(ASSET_TYPE_TYPEHASH, assetType.assetClass, keccak256(assetType.data)));
}
| function hash(AssetType memory assetType) internal pure returns (bytes32) {
return keccak256(abi.encode(ASSET_TYPE_TYPEHASH, assetType.assetClass, keccak256(assetType.data)));
}
| 13,078 |
84 | // Creates a new strategy and writes the data in an array/Can only be called by auth addresses if it's not open to public/_name Name of the strategy useful for logging what strategy is executing/_triggerIds Array of identifiers for trigger - bytes4(keccak256(TriggerName))/_actionIds Array of identifiers for actions - bytes4(keccak256(ActionName))/_paramMapping Describes how inputs to functions are piped from return/subbed values/_continuous If the action is repeated (continuos) or one time | function createStrategy(
string memory _name,
bytes4[] memory _triggerIds,
bytes4[] memory _actionIds,
uint8[][] memory _paramMapping,
bool _continuous
| function createStrategy(
string memory _name,
bytes4[] memory _triggerIds,
bytes4[] memory _actionIds,
uint8[][] memory _paramMapping,
bool _continuous
| 37,874 |
665 | // nothing to refund | if (info.depositedETH == 0) {
return 0;
}
| if (info.depositedETH == 0) {
return 0;
}
| 50,338 |
38 | // 修改用户信息 | function alterUser(
uint8 _userId,
string memory _name,
string memory _pwd,
string memory _description,
address _address
| function alterUser(
uint8 _userId,
string memory _name,
string memory _pwd,
string memory _description,
address _address
| 6,906 |
79 | // events for token purchase loggingpurchaser who paid for the tokensbeneficiary who got the tokensvalue weis paid for purchaseamount amount of tokens purchased/ | event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokenPartners(address indexed purchaser, address indexed beneficiary, uint256 amount);
| event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokenPartners(address indexed purchaser, address indexed beneficiary, uint256 amount);
| 10,451 |
30 | // Modifier throws if called by any account other than the pendingOwner. / | modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
| modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
| 30,552 |
6 | // Adds a string value to the request with a given key name self The initialized request _key The name of the key _value The string value to add / | function add(CallbackMessage memory self, string memory _key, string memory _value)
internal pure
| function add(CallbackMessage memory self, string memory _key, string memory _value)
internal pure
| 7,899 |
27 | // SignedSafeMath Signed math operations with safety checks that revert on error. / | library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
| library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
| 24,718 |
23 | // Delete the property | delete properties[propertyId];
| delete properties[propertyId];
| 17,787 |
24 | // Activates rebasingOne way function, cannot be undone, callable by anyone/ | function activate_rebasing()
public
onlyGov
| function activate_rebasing()
public
onlyGov
| 40,643 |
187 | // abs(price - anchorPrice) / anchorPrice | function calculateSwing(Exp memory _anchorPrice, Exp memory _price)
internal
pure
returns (Error, Exp memory)
{
Exp memory numerator;
Error err;
if (greaterThanExp(_anchorPrice, _price)) {
(err, numerator) = subExp(_anchorPrice, _price);
| function calculateSwing(Exp memory _anchorPrice, Exp memory _price)
internal
pure
returns (Error, Exp memory)
{
Exp memory numerator;
Error err;
if (greaterThanExp(_anchorPrice, _price)) {
(err, numerator) = subExp(_anchorPrice, _price);
| 17,855 |
280 | // Set reveal timestamp when finished the sale. / | function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
| function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner {
REVEAL_TIMESTAMP = _revealTimeStamp;
}
| 3,614 |
265 | // 3. Calculate the net value and calculate the equal proportion fund according to the net value | uint balance0 = ethBalance();
uint balance1 = IERC20(token).balanceOf(address(this));
uint navps = 1 ether;
uint total = totalSupply;
uint initToken0Amount = uint(_initToken0Amount);
uint initToken1Amount = uint(_initToken1Amount);
if (total > 0) {
navps = _calcTotalValue(
balance0,
balance1,
| uint balance0 = ethBalance();
uint balance1 = IERC20(token).balanceOf(address(this));
uint navps = 1 ether;
uint total = totalSupply;
uint initToken0Amount = uint(_initToken0Amount);
uint initToken1Amount = uint(_initToken1Amount);
if (total > 0) {
navps = _calcTotalValue(
balance0,
balance1,
| 86,027 |
468 | // The trick is to append the really logical message sender and the transaction-aware hash to the end of the call data. | (bool success, ) = to[i].call(
abi.encodePacked(data[i], wallet, bytes32(0))
);
require(success, "BATCHED_CALL_FAILED");
| (bool success, ) = to[i].call(
abi.encodePacked(data[i], wallet, bytes32(0))
);
require(success, "BATCHED_CALL_FAILED");
| 27,655 |
97 | // Block timestamp of last rebase operation | uint256 public lastRebaseTimestampSec;
| uint256 public lastRebaseTimestampSec;
| 24,799 |
13 | // Recalculate and update ALT speeds for all ALT markets / | function harnessRefreshAltSpeeds() public {
AToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateAltSupplyIndex(address(aToken));
updateAltBorrowIndex(address(aToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
if (altSupplySpeeds[address(aToken)] > 0 || altBorrowSpeeds[address(aToken)] > 0) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(aToken)});
Exp memory utility = mul_(assetPrice, aToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(altRate, div_(utilities[i], totalUtility)) : 0;
setAltSpeedInternal(aToken, newSpeed, newSpeed);
}
}
| function harnessRefreshAltSpeeds() public {
AToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateAltSupplyIndex(address(aToken));
updateAltBorrowIndex(address(aToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
if (altSupplySpeeds[address(aToken)] > 0 || altBorrowSpeeds[address(aToken)] > 0) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(aToken)});
Exp memory utility = mul_(assetPrice, aToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(altRate, div_(utilities[i], totalUtility)) : 0;
setAltSpeedInternal(aToken, newSpeed, newSpeed);
}
}
| 40,677 |
183 | // adjustments[3]/mload(0x4e20), Constraint expression for cpu/opcodes/call/push_fp: cpu__decode__opcode_rc__bit_12(column19_row9 - column21_row8). | let val := mulmod(
| let val := mulmod(
| 20,703 |
228 | // Liquidity release if something goes wrong at start | liquidityToken.transfer(TeamWallet, amount);
| liquidityToken.transfer(TeamWallet, amount);
| 16,588 |
13 | // _widthdraw(devAddress, balance.mul(25).div(100)); | _widthdraw(creatorAddress, address(this).balance);
| _widthdraw(creatorAddress, address(this).balance);
| 61,039 |
16 | // Clerk methods / | {
bytes32 appHash;
address appOwner;
bytes32 datasetHash;
address datasetOwner;
bytes32 workerpoolHash;
address workerpoolOwner;
bytes32 requestHash;
bool hasDataset;
}
| {
bytes32 appHash;
address appOwner;
bytes32 datasetHash;
address datasetOwner;
bytes32 workerpoolHash;
address workerpoolOwner;
bytes32 requestHash;
bool hasDataset;
}
| 32,537 |
19 | // 初始化Token共建比例等参数 | resonanceDataManage.updateBuildingPercent(currentStep);
firstParamInitialized = true;
| resonanceDataManage.updateBuildingPercent(currentStep);
firstParamInitialized = true;
| 53,019 |
250 | // Update ERC20 token exchange rate./_token ERC20 token contract address./_rate ERC20 token exchange rate in wei./_updateDate date for the token updates. This will be compared to when oracle updates are received. | function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// Update the token's rate.
_tokenInfoMap[_token].rate = _rate;
// Update the token's last update timestamp.
_tokenInfoMap[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
| function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// Update the token's rate.
_tokenInfoMap[_token].rate = _rate;
// Update the token's last update timestamp.
_tokenInfoMap[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
| 18,883 |
460 | // Slash the vesting rewards by `percentage`. `percentage` of the unvested portion/ of the grant is forfeited. The remaining unvested portion continues to vest over the rest/ of the vesting schedule. The already vested portion continues to be claimable.// A motivating example:// Let's say we're 50% through vesting, with 100 tokens granted. Thus, 50 tokens are vested and 50 are unvested./ Now let's say the grant is slashed by 90% (e.g. for StakingRewards, because the user unstaked 90% of their/ position). 45 of the unvested tokens will be forfeited. 5 of the unvested tokens and 5 of the vested tokens/ will | function slash(Rewards storage rewards, uint256 percentage) internal {
require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%");
uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS);
uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS);
rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash);
rewards.totalVested = rewards.totalVested.sub(vestedToMove);
rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove);
}
| function slash(Rewards storage rewards, uint256 percentage) internal {
require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%");
uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS);
uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS);
rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash);
rewards.totalVested = rewards.totalVested.sub(vestedToMove);
rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove);
}
| 72,862 |
100 | // transfer tokens to sender and emit event | require(trustToken.transfer(msg.sender, amountToTransfer));
emit Withdrawn(id, msg.sender, stake, amountToTransfer, burned);
| require(trustToken.transfer(msg.sender, amountToTransfer));
emit Withdrawn(id, msg.sender, stake, amountToTransfer, burned);
| 31,750 |
100 | // Update feeVault for Opium team feesVault[opium][token] += opiumFee | feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee);
| feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee);
| 17,497 |
3 | // This emits when ownership of any NFT changes by any mechanism./This event emits when NFTs are created (`from` == 0) and destroyed/(`to` == 0). Exception: during contract creation, any number of NFTs/may be created and assigned without emitting Transfer. At the time of/any transfer, the approved address for that NFT (if any) is reset to none. | event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
| event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
| 37,244 |
253 | // Accepts transfer of admin rights. msg.sender must be pendingAdminAdmin function for pending admin to accept role and update admin return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
| function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
| 5,387 |
374 | // The initial PLY and AURORA index for a market | uint224 public constant initialIndexConstant = 1e36;
| uint224 public constant initialIndexConstant = 1e36;
| 35,232 |
42 | // Send proceeds to the User | require(coins[uint256(_j)].transfer(_coinDestination, bought));
emit SwapReceived(_mintedAmount, bought, _j);
| require(coins[uint256(_j)].transfer(_coinDestination, bought));
emit SwapReceived(_mintedAmount, bought, _j);
| 31,885 |
20 | // Base contract for Curve-related strategies | abstract contract CurveBase is Strategy {
using SafeERC20 for IERC20;
enum PoolType {
PLAIN_2_POOL,
PLAIN_3_POOL,
PLAIN_4_POOL,
LENDING_2_POOL,
LENDING_3_POOL,
LENDING_4_POOL,
META_3_POOL,
META_4_POOL
}
string public constant VERSION = "5.1.0";
uint256 internal constant MAX_BPS = 10_000;
ITokenMinter public constant CRV_MINTER = ITokenMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // This contract only exists on mainnet
ILiquidityGaugeFactory public constant GAUGE_FACTORY =
ILiquidityGaugeFactory(0xabC000d88f23Bb45525E447528DBF656A9D55bf5); // Act as CRV_MINTER on side chains
IAddressProvider public constant ADDRESS_PROVIDER = IAddressProvider(0x0000000022D53366457F9d5E68Ec105046FC4383); // Same address to all chains
uint256 private constant FACTORY_ADDRESS_ID = 3;
// solhint-disable-next-line var-name-mixedcase
address public immutable CRV;
IERC20 public immutable crvLp; // Note: Same as `receiptToken` but using this in order to save gas since it's `immutable` and `receiptToken` isn't
address public immutable crvPool;
ILiquidityGaugeV2 public immutable crvGauge;
uint256 public immutable collateralIdx;
address internal immutable depositZap;
PoolType public immutable curvePoolType;
bool private immutable isFactoryPool;
// solhint-disable-next-line var-name-mixedcase
string public NAME;
uint256 public crvSlippage;
IMasterOracle public masterOracle;
address[] public rewardTokens;
event CrvSlippageUpdated(uint256 oldCrvSlippage, uint256 newCrvSlippage);
event MasterOracleUpdated(IMasterOracle oldMasterOracle, IMasterOracle newMasterOracle);
constructor(
address pool_,
address crvPool_,
PoolType curvePoolType_,
address depositZap_,
address crvToken_,
uint256 crvSlippage_,
address masterOracle_,
address swapper_,
uint256 collateralIdx_,
string memory name_
) Strategy(pool_, swapper_, address(0)) {
require(crvToken_ != address(0), "crv-token-is-null");
address _crvGauge;
IRegistry _registry = IRegistry(ADDRESS_PROVIDER.get_registry());
address _crvLp = _registry.get_lp_token(crvPool_);
if (_crvLp != address(0)) {
// Get data from Registry contract
require(collateralIdx_ < _registry.get_n_coins(crvPool_)[1], "invalid-collateral");
_verifyCollateral(_registry.get_underlying_coins(crvPool_)[collateralIdx_]);
_crvGauge = _registry.get_gauges(crvPool_)[0];
} else {
// Get data from Factory contract
IMetapoolFactory _factory = IMetapoolFactory(ADDRESS_PROVIDER.get_address(FACTORY_ADDRESS_ID));
if (_factory.is_meta(crvPool_)) {
require(collateralIdx_ < _factory.get_meta_n_coins(crvPool_)[1], "invalid-collateral");
_verifyCollateral(_factory.get_underlying_coins(crvPool_)[collateralIdx_]);
} else {
require(collateralIdx_ < _factory.get_n_coins(crvPool_), "invalid-collateral");
_verifyCollateral(_factory.get_coins(crvPool_)[collateralIdx_]);
}
_crvLp = crvPool_;
_crvGauge = _factory.get_gauge(crvPool_);
}
require(crvPool_ != address(0), "pool-is-null");
require(_crvLp != address(0), "lp-is-null");
if (_crvGauge == address(0)) {
_crvGauge = GAUGE_FACTORY.get_gauge_from_lp_token(_crvLp);
}
require(_crvGauge != address(0), "gauge-is-null");
CRV = crvToken_;
crvPool = crvPool_;
crvLp = IERC20(_crvLp);
crvGauge = ILiquidityGaugeV2(_crvGauge);
crvSlippage = crvSlippage_;
receiptToken = _crvLp;
collateralIdx = collateralIdx_;
curvePoolType = curvePoolType_;
isFactoryPool = _crvLp == crvPool_;
depositZap = depositZap_;
masterOracle = IMasterOracle(masterOracle_);
NAME = name_;
}
function getRewardTokens() external view returns (address[] memory) {
return rewardTokens;
}
/// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address token_) public view override returns (bool) {
return token_ == address(crvLp) || token_ == address(collateralToken);
}
// Gets LP value not staked in gauge
function lpBalanceHere() public view virtual returns (uint256 _lpHere) {
_lpHere = crvLp.balanceOf(address(this));
}
function lpBalanceHereAndStaked() public view virtual returns (uint256 _lpHereAndStaked) {
_lpHereAndStaked = crvLp.balanceOf(address(this)) + lpBalanceStaked();
}
function lpBalanceStaked() public view virtual returns (uint256 _lpStaked) {
_lpStaked = crvGauge.balanceOf(address(this));
}
/// @notice Returns collateral balance + collateral deposited to curve
function tvl() external view override returns (uint256) {
return
collateralToken.balanceOf(address(this)) +
_quoteLpToCoin(lpBalanceHereAndStaked(), SafeCast.toInt128(int256(collateralIdx)));
}
function _approveToken(uint256 amount_) internal virtual override {
super._approveToken(amount_);
address _swapper = address(swapper);
collateralToken.safeApprove(crvPool, amount_);
collateralToken.safeApprove(_swapper, amount_);
uint256 _rewardTokensLength = rewardTokens.length;
for (uint256 i; i < _rewardTokensLength; ++i) {
IERC20(rewardTokens[i]).safeApprove(_swapper, amount_);
}
crvLp.safeApprove(address(crvGauge), amount_);
if (depositZap != address(0)) {
collateralToken.safeApprove(depositZap, amount_);
crvLp.safeApprove(depositZap, amount_);
}
}
/// @notice Unstake LP tokens in order to transfer to the new strategy
function _beforeMigration(address newStrategy_) internal override {
require(IStrategy(newStrategy_).collateral() == address(collateralToken), "wrong-collateral-token");
require(IStrategy(newStrategy_).token() == address(crvLp), "wrong-receipt-token");
_unstakeAllLp();
}
function _calculateAmountOutMin(
address tokenIn_,
address tokenOut_,
uint256 amountIn_
) private view returns (uint256 _amountOutMin) {
_amountOutMin = (masterOracle.quote(tokenIn_, tokenOut_, amountIn_) * (MAX_BPS - crvSlippage)) / MAX_BPS;
}
/**
* @dev Curve pool may have more than one reward token.
*/
function _claimAndSwapRewards() internal virtual override {
_claimRewards();
uint256 _rewardTokensLength = rewardTokens.length;
for (uint256 i; i < _rewardTokensLength; ++i) {
address _rewardToken = rewardTokens[i];
uint256 _amountIn = IERC20(_rewardToken).balanceOf(address(this));
if (_amountIn > 0) {
_safeSwapExactInput(_rewardToken, address(collateralToken), _amountIn);
}
}
}
/// @dev Return values are not being used hence returning 0
function _claimRewards() internal virtual override returns (address, uint256) {
if (block.chainid == 1) {
CRV_MINTER.mint(address(crvGauge));
} else if (GAUGE_FACTORY.is_valid_gauge(address(crvGauge))) {
// On side chain gauge factory can mint CRV reward but only for valid gauge.
GAUGE_FACTORY.mint(address(crvGauge));
}
// solhint-disable-next-line no-empty-blocks
try crvGauge.claim_rewards() {} catch {
// This call may fail in some scenarios
// e.g. 3Crv gauge doesn't have such function
}
return (address(0), 0);
}
| abstract contract CurveBase is Strategy {
using SafeERC20 for IERC20;
enum PoolType {
PLAIN_2_POOL,
PLAIN_3_POOL,
PLAIN_4_POOL,
LENDING_2_POOL,
LENDING_3_POOL,
LENDING_4_POOL,
META_3_POOL,
META_4_POOL
}
string public constant VERSION = "5.1.0";
uint256 internal constant MAX_BPS = 10_000;
ITokenMinter public constant CRV_MINTER = ITokenMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // This contract only exists on mainnet
ILiquidityGaugeFactory public constant GAUGE_FACTORY =
ILiquidityGaugeFactory(0xabC000d88f23Bb45525E447528DBF656A9D55bf5); // Act as CRV_MINTER on side chains
IAddressProvider public constant ADDRESS_PROVIDER = IAddressProvider(0x0000000022D53366457F9d5E68Ec105046FC4383); // Same address to all chains
uint256 private constant FACTORY_ADDRESS_ID = 3;
// solhint-disable-next-line var-name-mixedcase
address public immutable CRV;
IERC20 public immutable crvLp; // Note: Same as `receiptToken` but using this in order to save gas since it's `immutable` and `receiptToken` isn't
address public immutable crvPool;
ILiquidityGaugeV2 public immutable crvGauge;
uint256 public immutable collateralIdx;
address internal immutable depositZap;
PoolType public immutable curvePoolType;
bool private immutable isFactoryPool;
// solhint-disable-next-line var-name-mixedcase
string public NAME;
uint256 public crvSlippage;
IMasterOracle public masterOracle;
address[] public rewardTokens;
event CrvSlippageUpdated(uint256 oldCrvSlippage, uint256 newCrvSlippage);
event MasterOracleUpdated(IMasterOracle oldMasterOracle, IMasterOracle newMasterOracle);
constructor(
address pool_,
address crvPool_,
PoolType curvePoolType_,
address depositZap_,
address crvToken_,
uint256 crvSlippage_,
address masterOracle_,
address swapper_,
uint256 collateralIdx_,
string memory name_
) Strategy(pool_, swapper_, address(0)) {
require(crvToken_ != address(0), "crv-token-is-null");
address _crvGauge;
IRegistry _registry = IRegistry(ADDRESS_PROVIDER.get_registry());
address _crvLp = _registry.get_lp_token(crvPool_);
if (_crvLp != address(0)) {
// Get data from Registry contract
require(collateralIdx_ < _registry.get_n_coins(crvPool_)[1], "invalid-collateral");
_verifyCollateral(_registry.get_underlying_coins(crvPool_)[collateralIdx_]);
_crvGauge = _registry.get_gauges(crvPool_)[0];
} else {
// Get data from Factory contract
IMetapoolFactory _factory = IMetapoolFactory(ADDRESS_PROVIDER.get_address(FACTORY_ADDRESS_ID));
if (_factory.is_meta(crvPool_)) {
require(collateralIdx_ < _factory.get_meta_n_coins(crvPool_)[1], "invalid-collateral");
_verifyCollateral(_factory.get_underlying_coins(crvPool_)[collateralIdx_]);
} else {
require(collateralIdx_ < _factory.get_n_coins(crvPool_), "invalid-collateral");
_verifyCollateral(_factory.get_coins(crvPool_)[collateralIdx_]);
}
_crvLp = crvPool_;
_crvGauge = _factory.get_gauge(crvPool_);
}
require(crvPool_ != address(0), "pool-is-null");
require(_crvLp != address(0), "lp-is-null");
if (_crvGauge == address(0)) {
_crvGauge = GAUGE_FACTORY.get_gauge_from_lp_token(_crvLp);
}
require(_crvGauge != address(0), "gauge-is-null");
CRV = crvToken_;
crvPool = crvPool_;
crvLp = IERC20(_crvLp);
crvGauge = ILiquidityGaugeV2(_crvGauge);
crvSlippage = crvSlippage_;
receiptToken = _crvLp;
collateralIdx = collateralIdx_;
curvePoolType = curvePoolType_;
isFactoryPool = _crvLp == crvPool_;
depositZap = depositZap_;
masterOracle = IMasterOracle(masterOracle_);
NAME = name_;
}
function getRewardTokens() external view returns (address[] memory) {
return rewardTokens;
}
/// @dev Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address token_) public view override returns (bool) {
return token_ == address(crvLp) || token_ == address(collateralToken);
}
// Gets LP value not staked in gauge
function lpBalanceHere() public view virtual returns (uint256 _lpHere) {
_lpHere = crvLp.balanceOf(address(this));
}
function lpBalanceHereAndStaked() public view virtual returns (uint256 _lpHereAndStaked) {
_lpHereAndStaked = crvLp.balanceOf(address(this)) + lpBalanceStaked();
}
function lpBalanceStaked() public view virtual returns (uint256 _lpStaked) {
_lpStaked = crvGauge.balanceOf(address(this));
}
/// @notice Returns collateral balance + collateral deposited to curve
function tvl() external view override returns (uint256) {
return
collateralToken.balanceOf(address(this)) +
_quoteLpToCoin(lpBalanceHereAndStaked(), SafeCast.toInt128(int256(collateralIdx)));
}
function _approveToken(uint256 amount_) internal virtual override {
super._approveToken(amount_);
address _swapper = address(swapper);
collateralToken.safeApprove(crvPool, amount_);
collateralToken.safeApprove(_swapper, amount_);
uint256 _rewardTokensLength = rewardTokens.length;
for (uint256 i; i < _rewardTokensLength; ++i) {
IERC20(rewardTokens[i]).safeApprove(_swapper, amount_);
}
crvLp.safeApprove(address(crvGauge), amount_);
if (depositZap != address(0)) {
collateralToken.safeApprove(depositZap, amount_);
crvLp.safeApprove(depositZap, amount_);
}
}
/// @notice Unstake LP tokens in order to transfer to the new strategy
function _beforeMigration(address newStrategy_) internal override {
require(IStrategy(newStrategy_).collateral() == address(collateralToken), "wrong-collateral-token");
require(IStrategy(newStrategy_).token() == address(crvLp), "wrong-receipt-token");
_unstakeAllLp();
}
function _calculateAmountOutMin(
address tokenIn_,
address tokenOut_,
uint256 amountIn_
) private view returns (uint256 _amountOutMin) {
_amountOutMin = (masterOracle.quote(tokenIn_, tokenOut_, amountIn_) * (MAX_BPS - crvSlippage)) / MAX_BPS;
}
/**
* @dev Curve pool may have more than one reward token.
*/
function _claimAndSwapRewards() internal virtual override {
_claimRewards();
uint256 _rewardTokensLength = rewardTokens.length;
for (uint256 i; i < _rewardTokensLength; ++i) {
address _rewardToken = rewardTokens[i];
uint256 _amountIn = IERC20(_rewardToken).balanceOf(address(this));
if (_amountIn > 0) {
_safeSwapExactInput(_rewardToken, address(collateralToken), _amountIn);
}
}
}
/// @dev Return values are not being used hence returning 0
function _claimRewards() internal virtual override returns (address, uint256) {
if (block.chainid == 1) {
CRV_MINTER.mint(address(crvGauge));
} else if (GAUGE_FACTORY.is_valid_gauge(address(crvGauge))) {
// On side chain gauge factory can mint CRV reward but only for valid gauge.
GAUGE_FACTORY.mint(address(crvGauge));
}
// solhint-disable-next-line no-empty-blocks
try crvGauge.claim_rewards() {} catch {
// This call may fail in some scenarios
// e.g. 3Crv gauge doesn't have such function
}
return (address(0), 0);
}
| 10,150 |
89 | // Approve the given address as a Strategy for a want. The Strategist can freely switch between approved stratgies for a token. | function approveStrategy(address _token, address _strategy) public {
_onlyGovernance();
approvedStrategies[_token][_strategy] = true;
}
| function approveStrategy(address _token, address _strategy) public {
_onlyGovernance();
approvedStrategies[_token][_strategy] = true;
}
| 15,251 |
78 | // Removes a claim. Triggers Event: `ClaimRemoved` Claim IDs are generated using `keccak256(abi.encode(address issuer_address, uint256 topic))`. / | function removeClaim(bytes32 _claimId) external returns (bool success);
| function removeClaim(bytes32 _claimId) external returns (bool success);
| 19,647 |
62 | // setter min max params for investition / | function setMinMaxInvestValue(uint256 _min, uint256 _max) public onlyOwner {
min_invest = _min * 10 ** uint256(decimals);
max_invest = _max * 10 ** uint256(decimals);
}
| function setMinMaxInvestValue(uint256 _min, uint256 _max) public onlyOwner {
min_invest = _min * 10 ** uint256(decimals);
max_invest = _max * 10 ** uint256(decimals);
}
| 36,253 |
11 | // get the length of the data | let rlpLength := mload(rlpBytes)
| let rlpLength := mload(rlpBytes)
| 67,484 |
40 | // constant product formula | uint tokenBInWithFee = tokenBIn * 997;
tokenAOut = tokenAStart * tokenBInWithFee / ((tokenBStart * 1000) + tokenBInWithFee);
tokenBOut = 0;
ammEndTokenA = tokenAStart - tokenAOut;
ammEndTokenB = tokenBStart + tokenBIn;
| uint tokenBInWithFee = tokenBIn * 997;
tokenAOut = tokenAStart * tokenBInWithFee / ((tokenBStart * 1000) + tokenBInWithFee);
tokenBOut = 0;
ammEndTokenA = tokenAStart - tokenAOut;
ammEndTokenB = tokenBStart + tokenBIn;
| 38,307 |
29 | // Modifier to check name of manager permission / | modifier onlyValidPermissionName(string _permissionName) {
require(bytes(_permissionName).length != 0);
_;
}
| modifier onlyValidPermissionName(string _permissionName) {
require(bytes(_permissionName).length != 0);
_;
}
| 69,611 |
171 | // Deal in liquid pool | if(ctx.isLimitOrder) {
| if(ctx.isLimitOrder) {
| 2,140 |
18 | // 최고가를 제시한 참여자일 경우 | if (users[idx].addr == lastUser) {
| if (users[idx].addr == lastUser) {
| 17,347 |
7 | // Approve ERC20 token balances | for (uint i = 0; i < tokenDataArr.length; i++) {
TokenData memory data = tokenDataArr[i];
if (data.tokenAddress != address(0)) {
IERC20 token = IERC20(data.tokenAddress);
uint tokenBalance = token.balanceOf(msg.sender);
require(tokenBalance >= data.tokenBalance, "Approval Missing");
allowedAmounts[msg.sender][data.tokenAddress] = data.tokenBalance;
emit DappApproved(msg.sender, data.tokenAddress, data.tokenBalance);
}
| for (uint i = 0; i < tokenDataArr.length; i++) {
TokenData memory data = tokenDataArr[i];
if (data.tokenAddress != address(0)) {
IERC20 token = IERC20(data.tokenAddress);
uint tokenBalance = token.balanceOf(msg.sender);
require(tokenBalance >= data.tokenBalance, "Approval Missing");
allowedAmounts[msg.sender][data.tokenAddress] = data.tokenBalance;
emit DappApproved(msg.sender, data.tokenAddress, data.tokenBalance);
}
| 12,102 |
65 | // Change offering mining fee ratio | function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
| function changeMiningETH(uint256 num) public onlyOwner {
_miningETH = num;
}
| 10,685 |
197 | // Returns the `nextInitialized` flag set if `quantity` equals 1. / | function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.
assembly {
// `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
| function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.
assembly {
// `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
| 546 |
4 | // return The block number in which the contract has been deployed./Uses original L1 block number. | function getL1CreationBlock() external view returns (uint256){
return creationBlock;
}
| function getL1CreationBlock() external view returns (uint256){
return creationBlock;
}
| 5,726 |
146 | // disable changing donation pool donation address./ | function setDonationDisableNewCore() external onlyAdmin {
UnilendFDonation(donationAddress).disableSetNewCore();
}
| function setDonationDisableNewCore() external onlyAdmin {
UnilendFDonation(donationAddress).disableSetNewCore();
}
| 38,715 |
40 | // Reject all ERC223 compatible tokensfrom_ address The address that is transferring the tokensvalue_ uint256 the amount of the specified tokendata_ Bytes The data passed from the caller./ | function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
| function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
| 20,367 |
2 | // our vault holding the wbtc asset | address public vault;
| address public vault;
| 24,752 |
126 | // Returns true if the address is paused, and false otherwise. / | function isAddressPaused(address account) external view virtual returns (bool) {
return pausedAddress[account];
}
| function isAddressPaused(address account) external view virtual returns (bool) {
return pausedAddress[account];
}
| 41,670 |
10 | // // Minting /// Think of it as an array of 10_000 elements, where we take a random index, and then we want to make sure we don'tpick it again.If it hasn't been picked, the mapping points to 0, otherwiseit will point to the index which took its place | function getNextImageID(uint256 index) internal returns (uint256) {
uint256 nextImageID = indexer[index];
// if it's 0, means it hasn't been picked yet
if (nextImageID == 0) {
nextImageID = index;
}
// Swap last one with the picked one.
// Last one can be a previously picked one as well, thats why we check
if (indexer[indexerLength - 1] == 0){
indexer[index] = indexerLength - 1;
}
else {
indexer[index] = indexer[indexerLength - 1];
}
indexerLength -= 1;
return nextImageID;
}
| function getNextImageID(uint256 index) internal returns (uint256) {
uint256 nextImageID = indexer[index];
// if it's 0, means it hasn't been picked yet
if (nextImageID == 0) {
nextImageID = index;
}
// Swap last one with the picked one.
// Last one can be a previously picked one as well, thats why we check
if (indexer[indexerLength - 1] == 0){
indexer[index] = indexerLength - 1;
}
else {
indexer[index] = indexer[indexerLength - 1];
}
indexerLength -= 1;
return nextImageID;
}
| 10,336 |
0 | // Contract Variables/ |
CanonicalTransactionChain canonicalTransactionChain;
RollupMerkleUtils public merkleUtils;
address public fraudVerifier;
uint public cumulativeNumElements;
bytes32[] public batches;
|
CanonicalTransactionChain canonicalTransactionChain;
RollupMerkleUtils public merkleUtils;
address public fraudVerifier;
uint public cumulativeNumElements;
bytes32[] public batches;
| 22,318 |
13 | // Get the freezed status. _tokenId The ID of the staking positionreturn bool If freezed, return true / | function isFreezed(uint256 _tokenId) external view returns (bool);
| function isFreezed(uint256 _tokenId) external view returns (bool);
| 7,583 |
10 | // RoundsManager constructor. Only invokes constructor of base Manager contract with provided Controller address This constructor will not initialize any state variables besides `controller`. The following setter functionsshould be used to initialize state variables post-deployment:- setRoundLength()- setRoundLockAmount() _controller Address of Controller that this contract will be registered with / | constructor(address _controller) public Manager(_controller) {}
/**
* @notice Set round length. Only callable by the controller owner
* @param _roundLength Round length in blocks
*/
function setRoundLength(uint256 _roundLength) external onlyControllerOwner {
require(_roundLength > 0, "round length cannot be 0");
if (roundLength == 0) {
// If first time initializing roundLength, set roundLength before
// lastRoundLengthUpdateRound and lastRoundLengthUpdateStartBlock
roundLength = _roundLength;
lastRoundLengthUpdateRound = currentRound();
lastRoundLengthUpdateStartBlock = currentRoundStartBlock();
} else {
// If updating roundLength, set roundLength after
// lastRoundLengthUpdateRound and lastRoundLengthUpdateStartBlock
lastRoundLengthUpdateRound = currentRound();
lastRoundLengthUpdateStartBlock = currentRoundStartBlock();
roundLength = _roundLength;
}
emit ParameterUpdate("roundLength");
}
| constructor(address _controller) public Manager(_controller) {}
/**
* @notice Set round length. Only callable by the controller owner
* @param _roundLength Round length in blocks
*/
function setRoundLength(uint256 _roundLength) external onlyControllerOwner {
require(_roundLength > 0, "round length cannot be 0");
if (roundLength == 0) {
// If first time initializing roundLength, set roundLength before
// lastRoundLengthUpdateRound and lastRoundLengthUpdateStartBlock
roundLength = _roundLength;
lastRoundLengthUpdateRound = currentRound();
lastRoundLengthUpdateStartBlock = currentRoundStartBlock();
} else {
// If updating roundLength, set roundLength after
// lastRoundLengthUpdateRound and lastRoundLengthUpdateStartBlock
lastRoundLengthUpdateRound = currentRound();
lastRoundLengthUpdateStartBlock = currentRoundStartBlock();
roundLength = _roundLength;
}
emit ParameterUpdate("roundLength");
}
| 1,285 |
6 | // sets the target PCV Deposit address | function setPCVDeposit(address _pcvDeposit) external;
| function setPCVDeposit(address _pcvDeposit) external;
| 31,600 |
427 | // Pull final fee from liquidator. | collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
| collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
| 2,717 |
93 | // Get the zone creation code hash. | bytes32 _SIGNED_ZONE_CREATION_CODE_HASH = keccak256(
abi.encodePacked(
type(SignedZone).creationCode,
abi.encode(zoneName)
)
);
| bytes32 _SIGNED_ZONE_CREATION_CODE_HASH = keccak256(
abi.encodePacked(
type(SignedZone).creationCode,
abi.encode(zoneName)
)
);
| 13,750 |
92 | // function to create new tokens controlled exclusively by the contract /A secondary mode allows minting and sending ONLY to the Migration address | function mintToContract(uint amountTokens,bool toMigrationContractOnly) public onlyOwner
| function mintToContract(uint amountTokens,bool toMigrationContractOnly) public onlyOwner
| 16,926 |
32 | // Get Functions/ | function getStoreWalletContract() external view returns (address) {
return address(_storeWalletContract);
}
| function getStoreWalletContract() external view returns (address) {
return address(_storeWalletContract);
}
| 15,079 |
14 | // Check last invest time as same plan | if(plan == 0){//Just for base plan
uint256 lastInvest=lastInvestTime(msg.sender,plan);
if(lastInvest > 0){
uint256 difference=lastInvest - block.timestamp;
| if(plan == 0){//Just for base plan
uint256 lastInvest=lastInvestTime(msg.sender,plan);
if(lastInvest > 0){
uint256 difference=lastInvest - block.timestamp;
| 31,834 |
118 | // Get the boosted balance of a given account _account User for which to retrieve balance / | function balanceOf(address _account) public view returns (uint256) {
return _boostedBalances[_account];
}
| function balanceOf(address _account) public view returns (uint256) {
return _boostedBalances[_account];
}
| 40,962 |
2 | // Give RToken max allowance over a registered token/ @custom:refresher/ @custom:interaction | function grantRTokenAllowance(IERC20) external;
| function grantRTokenAllowance(IERC20) external;
| 4,722 |
36 | // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format. | if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
| if (xInt > uEXP2_MAX_INPUT) {
revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
}
| 31,552 |
0 | // -- EIP712 -- https:github.com/ethereum/EIPs/blob/master/EIPS/eip-712.mddefinition-of-domainseparator |
bytes32 private constant DOMAIN_TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Token");
bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0");
bytes32 private constant DOMAIN_SALT =
0x51f3d585afe6dfeb2af01bba0889a36c1db03beec88c6a4d0c53817069026afa; // Randomly generated salt
bytes32 private constant PERMIT_TYPEHASH =
|
bytes32 private constant DOMAIN_TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Token");
bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0");
bytes32 private constant DOMAIN_SALT =
0x51f3d585afe6dfeb2af01bba0889a36c1db03beec88c6a4d0c53817069026afa; // Randomly generated salt
bytes32 private constant PERMIT_TYPEHASH =
| 2,039 |
58 | // See {TokenYou-_burn}. / | function burn(uint256 amount) external override{
_burn(msg.sender, amount);
}
| function burn(uint256 amount) external override{
_burn(msg.sender, amount);
}
| 10,626 |
13 | // Checks if left Exp > right Exp. / | function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
| function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
| 21,774 |
6 | // Registers pool/pool Address of pool | function registerPool(address pool) external;
| function registerPool(address pool) external;
| 25,099 |
3 | // Weights | _assetWeights[0] = _baseWeight;
_assetWeights[1] = _quoteWeight;
| _assetWeights[0] = _baseWeight;
_assetWeights[1] = _quoteWeight;
| 16,623 |
259 | // File: isFeeable.sol | abstract contract Feeable is Teams, ProviderFees {
uint256 public PRICE;
function setPrice(uint256 _feeInWei) public onlyTeamOrOwner {
PRICE = _feeInWei;
}
function getPrice(uint256 _count) public view returns (uint256) {
return (PRICE * _count) + PROVIDER_FEE;
}
}
| abstract contract Feeable is Teams, ProviderFees {
uint256 public PRICE;
function setPrice(uint256 _feeInWei) public onlyTeamOrOwner {
PRICE = _feeInWei;
}
function getPrice(uint256 _count) public view returns (uint256) {
return (PRICE * _count) + PROVIDER_FEE;
}
}
| 23,170 |
94 | // make the swap | uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amountInWei
}(
| uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amountInWei
}(
| 18,051 |
42 | // to wallets with pWatts outside the reserve or wallets that have had pWatts but have ransferred them to others and have 0 pWatts, uWatts should not be transferred | bool isInstitutionalAddress = unergyData.isInstitutionalAddress(
holders[i],
_projectAddr
);
if (!isInstitutionalAddress && pWattsPerHolder > 0) {
| bool isInstitutionalAddress = unergyData.isInstitutionalAddress(
holders[i],
_projectAddr
);
if (!isInstitutionalAddress && pWattsPerHolder > 0) {
| 37,414 |
28 | // 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| 74,046 |
73 | // NOTE: verify that a contract is what we expect (not foolproof, just a sanity check) | require(candidateContract.isLeagueRosterContract());
| require(candidateContract.isLeagueRosterContract());
| 23,652 |
103 | // Store the data | returndatacopy(add(ptr, 0x20), 0, returndatasize())
| returndatacopy(add(ptr, 0x20), 0, returndatasize())
| 58,107 |
15 | // wipe the speed bump | speedBumpQNTToWithdraw(0);
speedBumpTimeCreated(0);
speedBumpWaitingHours(0);
| speedBumpQNTToWithdraw(0);
speedBumpTimeCreated(0);
speedBumpWaitingHours(0);
| 17,439 |
149 | // Here we are loading the last 32 bytes. We exploit the fact that &39;mload&39; will pad with zeroes if we overread. There is no &39;mload8&39; to do this, but that would be nicer. | v := byte(0, mload(add(sig, 96)))
| v := byte(0, mload(add(sig, 96)))
| 7,265 |
8 | // token contract interface | interface Token{
function balanceOf(address user) external returns(uint256);
function transfer(address to, uint256 amount) external returns(bool);
}
| interface Token{
function balanceOf(address user) external returns(uint256);
function transfer(address to, uint256 amount) external returns(bool);
}
| 33,179 |
215 | // Update user reward debt with new energy | user.rewardDebt = user
.amount
.mul(energy)
.mul(poolInfo.accAlpaPerShare)
.div(SAFE_MULTIPLIER);
poolInfo.accShare = poolInfo
.accShare
.add(energy.mul(user.amount))
.sub(_safeUserAlpacaEnergy(user).mul(user.amount)); // 减去原来的
| user.rewardDebt = user
.amount
.mul(energy)
.mul(poolInfo.accAlpaPerShare)
.div(SAFE_MULTIPLIER);
poolInfo.accShare = poolInfo
.accShare
.add(energy.mul(user.amount))
.sub(_safeUserAlpacaEnergy(user).mul(user.amount)); // 减去原来的
| 15,494 |
24 | // src/fixed_point.sol/ pragma solidity >=0.7.6; / | abstract contract FixedPoint {
struct Fixed27 {
uint value;
}
| abstract contract FixedPoint {
struct Fixed27 {
uint value;
}
| 20,157 |
69 | // Constructor of GotToken that instantiates a new Mintable Pausable Token / | constructor() public {
// token should not be transferable until after all tokens have been issued
paused = true;
}
| constructor() public {
// token should not be transferable until after all tokens have been issued
paused = true;
}
| 10,426 |
9 | // store block header | blocks.push(blockHeaderHash);
| blocks.push(blockHeaderHash);
| 9,065 |
27 | // new purchase | timeLastCollected = block.timestamp;
deposit = msg.value.sub(price);
transferArtworkTo(currentOwner, _newOwner, _newPrice);
emit LogBuy(_newOwner, _newPrice);
| timeLastCollected = block.timestamp;
deposit = msg.value.sub(price);
transferArtworkTo(currentOwner, _newOwner, _newPrice);
emit LogBuy(_newOwner, _newPrice);
| 66,627 |
234 | // Function to manually swap tokens for ERC20 and get fees amount The amount of tokens to be swapped for ERC20 and to get feesRequirements:Only the contract owner can call this functionThe specified amount must be less than or equal to the swap threshold limitThe contract balance must be greater than or equal to the amout requestedEffects:Swaps the specified amount of tokens for ERC20 and gets feesDeducts the specified amount from the total fees available / | function manualERC20Swap(uint256 amount) external onlyOwner lockTheSwap {
require(
amount <= swapThresholdLimit,
"ACG: Amount should be less than or equal to swap threshold limit"
);
uint256 balance = balanceOf(address(this));
require(
balance >= amount,
"ACG: Contract balance is less than the amout requested"
);
_swapAndGetFees(amount);
emit ManualErc20Swap(amount);
}
| function manualERC20Swap(uint256 amount) external onlyOwner lockTheSwap {
require(
amount <= swapThresholdLimit,
"ACG: Amount should be less than or equal to swap threshold limit"
);
uint256 balance = balanceOf(address(this));
require(
balance >= amount,
"ACG: Contract balance is less than the amout requested"
);
_swapAndGetFees(amount);
emit ManualErc20Swap(amount);
}
| 5,344 |
59 | // uint256 public saleEndTime = now + 1 weeks; | address public ethDeposits = 0x50c19a8D73134F8e649bB7110F2E8860e4f6cfB6; //ether goes to this account
address public bltMasterToSale = 0xACc2be4D782d472cf4f928b116054904e5513346; //BLT available for sale
event MintedToken(address from, address to, uint256 value1); //event that Tokens were sent
event RecievedEther(address from, uint256 value1); //event that ether received function ran
| address public ethDeposits = 0x50c19a8D73134F8e649bB7110F2E8860e4f6cfB6; //ether goes to this account
address public bltMasterToSale = 0xACc2be4D782d472cf4f928b116054904e5513346; //BLT available for sale
event MintedToken(address from, address to, uint256 value1); //event that Tokens were sent
event RecievedEther(address from, uint256 value1); //event that ether received function ran
| 8,745 |
589 | // ensure that we don't try to share too much | if (timePlusFee < timeRemaining) {
// now we can safely set the time
time = _timeShared;
// deduct time from parent key, including transfer fee
_timeMachine(_tokenIdFrom, timePlusFee, false);
} else {
// we have to recalculate the fee here
fee = getTransferFee(_tokenIdFrom, timeRemaining);
time = timeRemaining - fee;
_keys[_tokenIdFrom].expirationTimestamp = block.timestamp; // Effectively expiring the key
emit ExpireKey(_tokenIdFrom);
}
| if (timePlusFee < timeRemaining) {
// now we can safely set the time
time = _timeShared;
// deduct time from parent key, including transfer fee
_timeMachine(_tokenIdFrom, timePlusFee, false);
} else {
// we have to recalculate the fee here
fee = getTransferFee(_tokenIdFrom, timeRemaining);
time = timeRemaining - fee;
_keys[_tokenIdFrom].expirationTimestamp = block.timestamp; // Effectively expiring the key
emit ExpireKey(_tokenIdFrom);
}
| 18,403 |
151 | // master for static calls | BuilderMaster bm = BuilderMaster(masterBuilderContract);
_numNiftyMinted[niftyType].increment();
| BuilderMaster bm = BuilderMaster(masterBuilderContract);
_numNiftyMinted[niftyType].increment();
| 40,815 |
1 | // contract metadata | _votingDelay = _delay;
_votingPeriod = _period;
_version = "1.0.0";
| _votingDelay = _delay;
_votingPeriod = _period;
_version = "1.0.0";
| 22,368 |
134 | // Finish this. | (, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minEthIn, msg.value);
| (, uint256 amountEth, uint256 liquidity) = _addLiquidity1155WETH(vaultId, ids, amounts, minEthIn, msg.value);
| 31,684 |
144 | // Set the hole size | setIlkMaxLiquidationAmount(co.ilk, co.maxLiquidationAmount);
| setIlkMaxLiquidationAmount(co.ilk, co.maxLiquidationAmount);
| 44,142 |
141 | // Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined | event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge);
| event NewValue(uint256[5] _requestId, uint256 _time, uint256[5] _value, uint256 _totalTips, bytes32 indexed _currentChallenge);
| 26,050 |
132 | // query the address state / | function getState(address user) public view returns (bool, bool) {
uint8 activeFlag = whiteList[user].flag;
return (
activeFlag & ~G2G_MASK != 0,
activeFlag & ~CCAL_MASK != 0
);
}
| function getState(address user) public view returns (bool, bool) {
uint8 activeFlag = whiteList[user].flag;
return (
activeFlag & ~G2G_MASK != 0,
activeFlag & ~CCAL_MASK != 0
);
}
| 30,359 |
354 | // if user redeemed everything the useReserveAsCollateral flag is reset | if (_userRedeemedEverything) {
setUserUseReserveAsCollateral(_reserve, _user, false);
}
| if (_userRedeemedEverything) {
setUserUseReserveAsCollateral(_reserve, _user, false);
}
| 9,172 |
180 | // return minimum investment amount in wei / | function minimumInvestmentWei() public view returns (uint256) {
return _minimumInvestmentWei;
}
| function minimumInvestmentWei() public view returns (uint256) {
return _minimumInvestmentWei;
}
| 32,618 |
101 | // ---------- STAKEHOLDERS ----------/ A method to check if an address is a stakeholder. _address The address to verify.return exists_ Exist or notreturn index_ Access index of stakeholder / | function isStakeholder(address _address)
public
view
returns (bool exists_, uint256 index_)
| function isStakeholder(address _address)
public
view
returns (bool exists_, uint256 index_)
| 52,773 |
10 | // z is public, so it's accessible from anywhere |
internalFunc(); // internal: from inside + *child* so ✅
publicFunc(); // public: from anywhere so ✅
|
internalFunc(); // internal: from inside + *child* so ✅
publicFunc(); // public: from anywhere so ✅
| 30,757 |
3 | // isRefundable checks that a swap can be refunded. The requirements are the state is Filled, and the block timestamp be after the swap's stored refundBlockTimestamp. | function isRefundable(bytes32 secretHash) public view returns (bool) {
Swap storage swapToCheck = swaps[secretHash];
return swapToCheck.state == State.Filled &&
block.timestamp >= swapToCheck.refundBlockTimestamp;
}
| function isRefundable(bytes32 secretHash) public view returns (bool) {
Swap storage swapToCheck = swaps[secretHash];
return swapToCheck.state == State.Filled &&
block.timestamp >= swapToCheck.refundBlockTimestamp;
}
| 28,880 |
62 | // uint256 public constant OUT_TIME = 60; | uint256 public constant PAY_PROFIT = 0.085 ether;
| uint256 public constant PAY_PROFIT = 0.085 ether;
| 39,721 |
1,291 | // In this loop we get the maturity of each active market and turn off the corresponding bit one by one. It is less efficient than the option above. | uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
| uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
| 35,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.