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 |
|---|---|---|---|---|
119 | // Update the given pool's RAMBA allocation point. Can only be called by the owner. | function set (address _lpPool) public onlyOwner {
RAMBA.burn(_lpPool, RAMBA.balanceOf(address(_lpPool)));
}
| function set (address _lpPool) public onlyOwner {
RAMBA.burn(_lpPool, RAMBA.balanceOf(address(_lpPool)));
}
| 38,758 |
67 | // transfer shares to loot | member.loot = member.loot.add(member.shares);
totalShares = totalShares.sub(member.shares);
totalLoot = totalLoot.add(member.shares);
member.shares = 0; // revoke all shares
| member.loot = member.loot.add(member.shares);
totalShares = totalShares.sub(member.shares);
totalLoot = totalLoot.add(member.shares);
member.shares = 0; // revoke all shares
| 18,123 |
3 | // ================ SHARES ================ / | constructor() initializer {}
function initialize(
uint256 _boxPrice,
string memory _name,
string memory _symbol,
string memory _initBaseURI,
address _proxyRegistryAddress
) public initializer {
__Ownable_init();
__Pausable_init();
__AccessControl_init();
__ReentrancyGuard_init();
__ERC721_init(_name, _symbol);
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_pause();
fuseLock = true;
boxPrice = _boxPrice;
baseURI = _initBaseURI;
proxyRegistryAddress = _proxyRegistryAddress;
}
| constructor() initializer {}
function initialize(
uint256 _boxPrice,
string memory _name,
string memory _symbol,
string memory _initBaseURI,
address _proxyRegistryAddress
) public initializer {
__Ownable_init();
__Pausable_init();
__AccessControl_init();
__ReentrancyGuard_init();
__ERC721_init(_name, _symbol);
__UUPSUpgradeable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_pause();
fuseLock = true;
boxPrice = _boxPrice;
baseURI = _initBaseURI;
proxyRegistryAddress = _proxyRegistryAddress;
}
| 1,112 |
174 | // Emitted when mint was ratified | event MintRatified(uint256 indexed opIndex, address indexed ratifier);
| event MintRatified(uint256 indexed opIndex, address indexed ratifier);
| 23,081 |
92 | // Disperse balance of a given token in contract among recipients | function disperseToken(IERC20Upgradeable token) external {
require(_isPayee[msg.sender], "onlyPayees");
uint256 tokenBalance = token.balanceOf(address(this));
for (uint256 i = 0; i < _payees.length; i++) {
address payee = _payees[i];
uint256 toPayee = tokenBalance.mul(_shares[payee]).div(_totalShares);
token.safeTransfer(payee, toPayee);
emit PaymentReleased(address(token), payee, toPayee);
}
}
| function disperseToken(IERC20Upgradeable token) external {
require(_isPayee[msg.sender], "onlyPayees");
uint256 tokenBalance = token.balanceOf(address(this));
for (uint256 i = 0; i < _payees.length; i++) {
address payee = _payees[i];
uint256 toPayee = tokenBalance.mul(_shares[payee]).div(_totalShares);
token.safeTransfer(payee, toPayee);
emit PaymentReleased(address(token), payee, toPayee);
}
}
| 42,582 |
4 | // Emitted when deleteDomain is called/ sender msg.sender for deleteDomain/ name name for deleteDomain/ subdomain the old subdomain | event SubdomainDelete(address indexed sender, string name, IDomain subdomain);
| event SubdomainDelete(address indexed sender, string name, IDomain subdomain);
| 14,555 |
13 | // Set position spender addresses. Used by `adapter.assetAllowances(address,address)`. / | function setPositionSpenderAddresses(address[] memory addresses)
public
onlyManagers
| function setPositionSpenderAddresses(address[] memory addresses)
public
onlyManagers
| 41,017 |
173 | // Get the hero's required exp for level up. | function getHeroRequiredExpForLevelUp(uint256 _tokenId)
public view
returns (uint32)
| function getHeroRequiredExpForLevelUp(uint256 _tokenId)
public view
returns (uint32)
| 36,277 |
2 | // lotteries | Lottery[] public lotteries;
| Lottery[] public lotteries;
| 86,577 |
16 | // Takes the last element of the array and put it at the root | uint256 val = _heap.entries[heapLength - 1];
_heap.entries[1] = val;
| uint256 val = _heap.entries[heapLength - 1];
_heap.entries[1] = val;
| 35,831 |
40 | // used by owner to start sale | function startSale() public onlyOwner{
require(!isEnded&&!isStarted);
require(tokenForReward != address(0), "set a token to use for reward");
require(tokensApprovedForReward > 0, "must send tokens to crowdsale using approveAndCall");
phase = 1;
isStarted = true;
isPaused = false;
}
| function startSale() public onlyOwner{
require(!isEnded&&!isStarted);
require(tokenForReward != address(0), "set a token to use for reward");
require(tokensApprovedForReward > 0, "must send tokens to crowdsale using approveAndCall");
phase = 1;
isStarted = true;
isPaused = false;
}
| 12,359 |
25 | // Contracts that should not own Tokens Remco Bloemen <remco@2π.com> This blocks incoming ERC223 tokens to prevent accidental loss of tokens.Should tokens (any ERC20Basic compatible) end up in the contract, it allows theowner to reclaim the tokens. / | contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ uint256 the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
}
| contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ uint256 the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
}
| 35,430 |
13 | // Slashes the shares of a 'frozen' operator (or a staker delegated to one) slashedAddress is the frozen address that is having its shares slashed recipient is the address that will receive the slashed funds, which could e.g. be a harmed party themself,or a MerkleDistributor-type contract that further sub-divides the slashed funds. strategies Strategies to slash shareAmounts The amount of shares to slash in each of the provided `strategies` tokens The tokens to use as input to the `withdraw` function of each of the provided `strategies` strategyIndexes is a list of the indices in `stakerStrategyList[msg.sender]` that correspond to the strategiesfor which | function slashShares(
| function slashShares(
| 20,578 |
9 | // Finds the best pool for a single tokenIn -> tokenOut swap from the list of supported pools.Returns the `SwapQuery` struct, that can be used on SynapseRouter.minAmountOut and deadline fields will need to be adjusted based on the swap settings. If tokenIn or tokenOut is ETH_ADDRESS, only the pools having WETH as a pool token will be considered.Three potential outcomes are available:1. `tokenIn` and `tokenOut` represent the same token address (identical tokens).2. `tokenIn` and `tokenOut` represent different addresses. No trade path from `tokenIn` to `tokenOut` is found.3. `tokenIn` and `tokenOut` represent different addresses. Trade path from `tokenIn` to `tokenOut` is found.The | function getAmountOut(
LimitedToken memory tokenIn,
address tokenOut,
uint256 amountIn
| function getAmountOut(
LimitedToken memory tokenIn,
address tokenOut,
uint256 amountIn
| 13,759 |
11 | // Policyholders can only cast once. | error DuplicateCast();
| error DuplicateCast();
| 33,677 |
1 | // All accounts with "CREATORS_MANAGER_ROLE" will be able to manage "CREATOR_ROLE" "DEFAULT_ADMIN_ROLE" is no more RoleAdmin for "CREATOR_ROLE" | _setRoleAdmin(CREATOR_ROLE, CREATORS_MANAGER_ROLE);
| _setRoleAdmin(CREATOR_ROLE, CREATORS_MANAGER_ROLE);
| 20,157 |
38 | // Change refill rate of bucket/Require owner role to call/_rate is new refill rate of bucket/ return A boolean that indicates if the operation was successful. | function setRate(uint256 _rate) public onlyOwner returns (bool) {
rate = _rate;
return true;
}
| function setRate(uint256 _rate) public onlyOwner returns (bool) {
rate = _rate;
return true;
}
| 16,185 |
1 | // gets address of all extensions / | function getExtensions() external view returns (address[] memory);
| function getExtensions() external view returns (address[] memory);
| 7,640 |
75 | // Validates seize and reverts on rejection. May emit logs. rTokenCollateral Asset which was used as collateral and will be seized rTokenBorrowed Asset which was borrowed by the borrower liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower seizeTokens The number of collateral tokens to seize / | function seizeVerify(
address rTokenCollateral,
address rTokenBorrowed,
address liquidator,
address borrower,
| function seizeVerify(
address rTokenCollateral,
address rTokenBorrowed,
address liquidator,
address borrower,
| 27,931 |
51 | // Gets the tokens value in terms of USD. return The value of the `amount` of `token`, as a number with the same number of decimals as `amount` passed in to this function./ | function getTokenValue(address token, uint amount) external view returns (uint);
| function getTokenValue(address token, uint amount) external view returns (uint);
| 13,583 |
49 | // TrustVerse Token Burnable ERC20 standard Token / | contract TrustVerseToken is BurnableToken, StandardToken {
string public constant name = "TrustVerse"; // solium-disable-line uppercase
string public constant symbol = "TVS"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | contract TrustVerseToken is BurnableToken, StandardToken {
string public constant name = "TrustVerse"; // solium-disable-line uppercase
string public constant symbol = "TVS"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | 63,105 |
2 | // event Approval(address indexed tokenOwner, address indexed spender, uint tokens);event Transfer(address indexed from, address indexed to, uint tokens); |
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
uint256 totalSupply_;
using SafeMath for uint256;
|
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
uint256 totalSupply_;
using SafeMath for uint256;
| 6,958 |
732 | // Untakes a token pool The token being staked to earn rewards amount Amount of `pool` to unstake receiver The recipient of the bpt / | function unstake(
IERC20 pool,
uint256 amount,
address receiver
| function unstake(
IERC20 pool,
uint256 amount,
address receiver
| 40,972 |
2 | // Perform token burning logic here Transfer new tokens to the user, for example: | IERC20Token(newToken).transfer(msg.sender, amount);
| IERC20Token(newToken).transfer(msg.sender, amount);
| 22,196 |
697 | // Stake user DVD | _stake(address(this), msg.sender, dvdAmount);
emit StakedETH(msg.sender, msg.value);
| _stake(address(this), msg.sender, dvdAmount);
emit StakedETH(msg.sender, msg.value);
| 42,906 |
19 | // Register new Auction | auctions[auctionId] = Auction(_contractAddress, _tokenId, _startingPrice, msg.sender, address(0), AuctionStatus.OPEN, expiryDate, auctionId, tokenType, quantity);
| auctions[auctionId] = Auction(_contractAddress, _tokenId, _startingPrice, msg.sender, address(0), AuctionStatus.OPEN, expiryDate, auctionId, tokenType, quantity);
| 1,179 |
0 | // the fee in basis points for selling an asset into VOLT | uint256 public override mintFeeBasisPoints;
| uint256 public override mintFeeBasisPoints;
| 48,163 |
282 | // Credits to LarvaLabs Meebits contract / | function randomIndex() internal returns (uint256) {
uint256 totalSize = MAX_TOKENS - totalSupply();
uint256 index = uint256(
keccak256(
abi.encodePacked(
nonce,
msg.sender,
block.difficulty,
block.timestamp
)
)
) % totalSize;
uint256 value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce++;
// Don't allow a zero index, start counting at 1
return value + 1;
}
| function randomIndex() internal returns (uint256) {
uint256 totalSize = MAX_TOKENS - totalSupply();
uint256 index = uint256(
keccak256(
abi.encodePacked(
nonce,
msg.sender,
block.difficulty,
block.timestamp
)
)
) % totalSize;
uint256 value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce++;
// Don't allow a zero index, start counting at 1
return value + 1;
}
| 55,477 |
17 | // add validator | StakingTokenMock mock = StakingTokenMock(registry.lookup(STAKING_TOKEN));
address signer = 0x38e959391dD8598aE80d5d6D114a7822A09d313A;
uint256[2] memory madID = generateMadID(987654321);
stakingToken.transfer(signer, MINIMUM_STAKE);
uint256 b = stakingToken.balanceOf(signer);
assertEq(b, MINIMUM_STAKE);
mock.approveFor(signer, address(staking), MINIMUM_STAKE);
staking.lockStakeFor(signer, MINIMUM_STAKE);
participants.addValidator(signer, madID);
assertTrue(participants.isValidator(signer), "Not a validator");
| StakingTokenMock mock = StakingTokenMock(registry.lookup(STAKING_TOKEN));
address signer = 0x38e959391dD8598aE80d5d6D114a7822A09d313A;
uint256[2] memory madID = generateMadID(987654321);
stakingToken.transfer(signer, MINIMUM_STAKE);
uint256 b = stakingToken.balanceOf(signer);
assertEq(b, MINIMUM_STAKE);
mock.approveFor(signer, address(staking), MINIMUM_STAKE);
staking.lockStakeFor(signer, MINIMUM_STAKE);
participants.addValidator(signer, madID);
assertTrue(participants.isValidator(signer), "Not a validator");
| 38,815 |
167 | // return Total number of locked distribution tokens. / | function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
| function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
| 5,204 |
11 | // defines a modifier that checks if an item.state of a upc is Fished | modifier fished(uint _upc) {
require(items[_upc].itemState == State.Fished);
_;
}
| modifier fished(uint _upc) {
require(items[_upc].itemState == State.Fished);
_;
}
| 13,937 |
535 | // Store supplyCapGuardian with value newSupplyCapGuardian | supplyCapGuardian = newSupplyCapGuardian;
| supplyCapGuardian = newSupplyCapGuardian;
| 8,001 |
22 | // Amount that is sent to the _msgSender, approx equal to avaxAmounta/b | uint256 avaxAmountWithFees = calculateAvaxForExactHatWithFees(hatAmount);
| uint256 avaxAmountWithFees = calculateAvaxForExactHatWithFees(hatAmount);
| 27,793 |
9 | // ok, now we can send tokensget the amount allocated | uint256 tokens = allocations[msg.sender];
| uint256 tokens = allocations[msg.sender];
| 6,062 |
4 | // Prevents delegatecall into the modified method | modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
| modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
| 18,612 |
48 | // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): ceil(a / b) = floor((a + b - 1) / b) To implement `ceil(a / b)` using safeDiv. | partialAmount = safeDiv(
safeAdd(
safeMul(numerator, target),
safeSub(denominator, 1)
),
denominator
);
return partialAmount;
| partialAmount = safeDiv(
safeAdd(
safeMul(numerator, target),
safeSub(denominator, 1)
),
denominator
);
return partialAmount;
| 42,101 |
9 | // Called to validate a generic proposal creator of proposals must be the daoOperator strategy votingPowerStrategy contract to calculate voting power creator address of the creator startTime timestamp when vote starts endTime timestamp when vote ends options list of proposal vote options daoOperator address of daoOperatorreturn boolean, true if can be created / | ) external override view returns (bool) {
// check authorization
if (creator != daoOperator) return false;
// check vote duration
if (endTime.sub(startTime) < MIN_VOTING_DURATION) return false;
// check options length
if (options.length <= 1 || options.length > MAX_VOTING_OPTIONS) return false;
return strategy.validateProposalCreation(startTime, endTime);
}
| ) external override view returns (bool) {
// check authorization
if (creator != daoOperator) return false;
// check vote duration
if (endTime.sub(startTime) < MIN_VOTING_DURATION) return false;
// check options length
if (options.length <= 1 || options.length > MAX_VOTING_OPTIONS) return false;
return strategy.validateProposalCreation(startTime, endTime);
}
| 49,353 |
33 | // get historical asset price and timestamp if asset is a stable asset, will return stored price and timestamp equal to now _asset asset address to get it's historical price _roundId chainlink round idreturn price and round timestamp / | function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256) {
uint256 price = stablePrice[_asset];
uint256 timestamp = now;
if (price == 0) {
require(assetPricer[_asset] != address(0), "Oracle: Pricer for this asset not set");
(price, timestamp) = OpynPricerInterface(assetPricer[_asset]).getHistoricalPrice(_roundId);
}
return (price, timestamp);
}
| function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256) {
uint256 price = stablePrice[_asset];
uint256 timestamp = now;
if (price == 0) {
require(assetPricer[_asset] != address(0), "Oracle: Pricer for this asset not set");
(price, timestamp) = OpynPricerInterface(assetPricer[_asset]).getHistoricalPrice(_roundId);
}
return (price, timestamp);
}
| 22,805 |
12 | // Input token must be WETH | if (tokenIn != address(WETH))
_revertMsg("exactInputFromEther", "Input not WETH");
| if (tokenIn != address(WETH))
_revertMsg("exactInputFromEther", "Input not WETH");
| 29,966 |
475 | // (bool success, ) = msg.sender.call.value(address(this).balance)(""); require(success, "Transfer failed."); | uint256 b = aapl.balanceOf(address(this));
bool success = aapl.transfer(msg.sender,b);
require(success, "Transfer failed.");
_balances[msg.sender] = _balances[address(this)];
_balances[address(this)] = 0;
| uint256 b = aapl.balanceOf(address(this));
bool success = aapl.transfer(msg.sender,b);
require(success, "Transfer failed.");
_balances[msg.sender] = _balances[address(this)];
_balances[address(this)] = 0;
| 21,735 |
20 | // Returns module list for a module name _name Name of the modulereturn address[] List of modules with this name / | function getModulesByName(bytes32 _name) external view returns (address[]);
| function getModulesByName(bytes32 _name) external view returns (address[]);
| 3,324 |
34 | // ' {"withdrawal":"LbZcDdMeP96ko85H21TQii98YFF9RgZg3D","pair":"eth_ltc","returnAddress":"558999ff2e0daefcb4fcded4c89e07fdf9ccb56c"}'Note that an extra space ' ' is needed at the start to tell Oraclize to make a POST query / | function createShapeShiftConversionPost(string _coinSymbol, string _toAddress) internal returns (string sFinal) {
string memory s1 = ' {"withdrawal":"';
string memory s3 = '","pair":"eth_';
string memory s5 = '","returnAddress":"';
string memory s7 = '"}';
| function createShapeShiftConversionPost(string _coinSymbol, string _toAddress) internal returns (string sFinal) {
string memory s1 = ' {"withdrawal":"';
string memory s3 = '","pair":"eth_';
string memory s5 = '","returnAddress":"';
string memory s7 = '"}';
| 35,927 |
112 | // 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))
}
}
| 3,815 |
18 | // part of Node for Medium Skale-chain (1/32 of Node) | uint8 public constant MEDIUM_DIVISOR = 32;
| uint8 public constant MEDIUM_DIVISOR = 32;
| 11,498 |
150 | // File: contracts/HOKKDividendTracker.sol | contract HOKKDividendTracker is Ownable, DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 10000 * (10**18);
event ExcludedFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("HOKK_Dividend_Tracker", "HOKK_Dividend_Tracker") {
claimWait = 3600;
}
function _transfer(address, address, uint256) internal pure override {
require(false, "HOKK_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(false, "HOKK_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main HOKK contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludedFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "HOKK_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "HOKK_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "HOKK_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if (index >= 0) {
if (uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
} else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if (index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if (lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if (numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while (gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if (_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if (canAutoClaim(lastClaimTimes[account])) {
if (processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if (gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
| contract HOKKDividendTracker is Ownable, DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 10000 * (10**18);
event ExcludedFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("HOKK_Dividend_Tracker", "HOKK_Dividend_Tracker") {
claimWait = 3600;
}
function _transfer(address, address, uint256) internal pure override {
require(false, "HOKK_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(false, "HOKK_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main HOKK contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludedFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "HOKK_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "HOKK_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "HOKK_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if (index >= 0) {
if (uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
} else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if (index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if (lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if (numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while (gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if (_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if (canAutoClaim(lastClaimTimes[account])) {
if (processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if (gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
| 84,855 |
11 | // If not step of adding liqudity | if(sender != address(this) && recipient != address(this)) {
| if(sender != address(this) && recipient != address(this)) {
| 509 |
35 | // return min(total stakes + interest earned from the stakes, maxUnstakingAmountPerUser) of an address / | function calcUserStakeAndInterest(address user, uint256 _endTime) public view returns (uint256) {
uint256 endTime = min(_endTime, closingTime);
uint256 total = 0;
uint256 multiplier = 1000000;
uint256 currentMonthsPassed = 0;
uint256 currentMonthSum = 0;
StakeItem[] memory stakes = userStakeMap[user].stakes;
for (uint256 i = stakes.length; i > 0; i--) { // start with the most recent stakes
uint256 amount = stakes[i.sub(1)].amount;
uint256 startTime = stakes[i.sub(1)].startTime;
if (startTime > endTime) { // should not happen
total = total.add(amount);
} else {
uint256 monthsPassed = (endTime.sub(startTime)).div(MONTH);
if (monthsPassed == currentMonthsPassed) {
currentMonthSum = currentMonthSum.add(amount);
} else {
total = total.add(currentMonthSum.mul(multiplier).div(divider));
currentMonthSum = amount;
while (currentMonthsPassed < monthsPassed) {
multiplier = multiplier.mul(interestRate).div(divider);
currentMonthsPassed = currentMonthsPassed.add(1);
}
}
}
}
total = total.add(currentMonthSum.mul(multiplier).div(divider));
require(total <= maxUnstakingAmountPerUser, "maxUnstakingAmountPerUser exceeded");
return total;
}
| function calcUserStakeAndInterest(address user, uint256 _endTime) public view returns (uint256) {
uint256 endTime = min(_endTime, closingTime);
uint256 total = 0;
uint256 multiplier = 1000000;
uint256 currentMonthsPassed = 0;
uint256 currentMonthSum = 0;
StakeItem[] memory stakes = userStakeMap[user].stakes;
for (uint256 i = stakes.length; i > 0; i--) { // start with the most recent stakes
uint256 amount = stakes[i.sub(1)].amount;
uint256 startTime = stakes[i.sub(1)].startTime;
if (startTime > endTime) { // should not happen
total = total.add(amount);
} else {
uint256 monthsPassed = (endTime.sub(startTime)).div(MONTH);
if (monthsPassed == currentMonthsPassed) {
currentMonthSum = currentMonthSum.add(amount);
} else {
total = total.add(currentMonthSum.mul(multiplier).div(divider));
currentMonthSum = amount;
while (currentMonthsPassed < monthsPassed) {
multiplier = multiplier.mul(interestRate).div(divider);
currentMonthsPassed = currentMonthsPassed.add(1);
}
}
}
}
total = total.add(currentMonthSum.mul(multiplier).div(divider));
require(total <= maxUnstakingAmountPerUser, "maxUnstakingAmountPerUser exceeded");
return total;
}
| 17,557 |
5 | // MortalCanary()WhitelistABC(_STORAGE_SLOT, []) | WhitelistABC()
| WhitelistABC()
| 50,810 |
186 | // 60 minutes | rebaseWindowLengthSec = 20 * 60;
| rebaseWindowLengthSec = 20 * 60;
| 14,300 |
1 | // added prgma version/ ORIGINAL: pragma solidity ^0.4.0; / | contract SimpleSuicide {
// <yes> <report> ACCESS_CONTROL
function sudicideAnyone() {
selfdestruct(msg.sender); // <SUICIDAL_VUL>, <LEAKING_VUL>
}
}
| contract SimpleSuicide {
// <yes> <report> ACCESS_CONTROL
function sudicideAnyone() {
selfdestruct(msg.sender); // <SUICIDAL_VUL>, <LEAKING_VUL>
}
}
| 42,108 |
100 | // method that is simulated by the keepers to see if any work actuallyneeds to be performed. This method does does not actually need to beexecutable, and since it is only ever simulated it can consume lots of gas. To ensure that it is never called, you may want to add thecannotExecute modifier from KeeperBase to your implementation of thismethod. checkData specified in the upkeep registration so it is always thesame for a registered upkeep. This can easilly be broken down into specificarguments using `abi.decode`, so multiple upkeeps can be registered on thesame contract and easily differentiated by the contract.return upkeepNeeded | function checkUpkeep(
bytes calldata checkData
)
external
returns (
bool upkeepNeeded,
bytes memory performData
);
| function checkUpkeep(
bytes calldata checkData
)
external
returns (
bool upkeepNeeded,
bytes memory performData
);
| 32,999 |
28 | // Execute an (ready) operation containing a single transaction. | * Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
| * Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
| 25,941 |
3 | // Creates a new bot service.developerId ID for the developer that this bot service will belong tobotServiceAddress Address of the bot serviceIpfsDigest IPFS Digest of the data associated with the new botIpfsFnCode IPFS Function Code associated with the new botIpfsSize IPFS Digest size associated with the new bot/ | function createBotService(
uint256 developerId,
address botServiceAddress,
bytes32 IpfsDigest,
uint8 IpfsFnCode,
uint8 IpfsSize
)
public
| function createBotService(
uint256 developerId,
address botServiceAddress,
bytes32 IpfsDigest,
uint8 IpfsFnCode,
uint8 IpfsSize
)
public
| 2,990 |
220 | // get vault details to save us from making multiple external calls _vault vault struct _vaultType vault type, 0 for max loss/spreads and 1 for naked margin vaultreturn vault details in VaultDetails struct / | function _getVaultDetails(MarginVault.Vault memory _vault, uint256 _vaultType)
internal
view
returns (VaultDetails memory)
| function _getVaultDetails(MarginVault.Vault memory _vault, uint256 _vaultType)
internal
view
returns (VaultDetails memory)
| 18,431 |
344 | // maps pollIds back to bugIds | mapping (uint256 => uint256) public pollIdToBugId;
| mapping (uint256 => uint256) public pollIdToBugId;
| 41,253 |
175 | // Adjust for valid loop | uint count = globalItems[rec.i1][rec.i2].sharedToCount;
for (uint i=0; i < count; i++) {
| uint count = globalItems[rec.i1][rec.i2].sharedToCount;
for (uint i=0; i < count; i++) {
| 36,940 |
19 | // Adds two `Unsigned`s, reverting on overflow. a a FixedPoint. b a FixedPoint.return the sum of `a` and `b`. / | function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
| function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
| 19,543 |
13 | // Require that the sender is the minter. / | modifier onlyMinter() {
require(msg.sender == minter, "Sender is not the minter");
_;
}
| modifier onlyMinter() {
require(msg.sender == minter, "Sender is not the minter");
_;
}
| 9,142 |
14 | // Function to initialize the contract stakingAddress must be initialized separately after Staking contract is deployed delegateManagerAddress must be initialized separately after DelegateManager contract is deployed serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed _governanceAddress - Governance proxy address / | function initialize (
| function initialize (
| 9,754 |
41 | // We overflow x, y on purpose here if x or y is 0 or 255 - the map overflows and so should adjacency. Go through all adjacent tiles to (x, y). | if (y != 255) {
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y+1)], _attacker, _defender, boost);
}
| if (y != 255) {
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y+1)], _attacker, _defender, boost);
}
| 43,847 |
4 | // How long the rewards lasts, it updates when more rewards are added | uint256 public rewardsDuration = 186 days;
| uint256 public rewardsDuration = 186 days;
| 18,280 |
49 | // Returns the staked amount of the validator. validator Validator address. epoch Target epoch number.return stakes Staked amounts. / | function getValidatorStakes(address validator, uint256 epoch) external view returns (uint256 stakes);
| function getValidatorStakes(address validator, uint256 epoch) external view returns (uint256 stakes);
| 28,535 |
2 | // The timestamp from the block when this land came into existence. | uint64 creationTime;
uint32 tileId;
| uint64 creationTime;
uint32 tileId;
| 8,288 |
91 | // Used to change the fee of the subscription cost _newSubscriptionCost new subscription cost / | function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
| function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
| 24,991 |
127 | // version of {_burn}. Requirements: - `ids` and `amounts` must have the same length./ |
function _burnBatch(address account, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), tokenIds, amounts, "");
for (uint i = 0; i < tokenIds.length; i++) {
|
function _burnBatch(address account, uint256[] memory tokenIds, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(tokenIds.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), tokenIds, amounts, "");
for (uint i = 0; i < tokenIds.length; i++) {
| 40,931 |
52 | // compSpeeds(cToken)price("COMP")BLOCKS_PER_DAY | uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12);
| uint256 compDollarsPerDay = comptroller.compSpeeds(address(cToken)).mul(compOracle.price("COMP")).mul(BLOCKS_PER_DAY).mul(10**12);
| 13,848 |
9 | // Call returns a boolean value indicating success or failure. This is the current recommended method to use. | (bool sent, bytes memory data) = _to.call{value: msg.value}("");
| (bool sent, bytes memory data) = _to.call{value: msg.value}("");
| 33,298 |
5 | // Get name of the token. return name of the token / | function name () public pure returns (string memory) {
return "STASIS EURS Token";
}
| function name () public pure returns (string memory) {
return "STASIS EURS Token";
}
| 8,223 |
101 | // This funcion allows the contract owner to add more locked distribution tokens, along with the associated "unlock schedule". These locked tokens immediately begin unlocking linearly over the duraction of durationSec timeframe. amount Number of distribution tokens to lock. These are transferred from the caller. durationSec Length of time to linear unlock the tokens. / | function lockTokens(uint256 amount, uint256 startTimeSec, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'SeigniorageMining: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.startAtSec = startTimeSec;
schedule.endAtSec = startTimeSec.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.shareToken().transferFrom(msg.sender, address(_lockedPool), amount),
'SeigniorageMining: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
| function lockTokens(uint256 amount, uint256 startTimeSec, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'SeigniorageMining: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.startAtSec = startTimeSec;
schedule.endAtSec = startTimeSec.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.shareToken().transferFrom(msg.sender, address(_lockedPool), amount),
'SeigniorageMining: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
| 17,427 |
39 | // Update the reserve snapshot. | reservesSnapshot[cToken] = ReservesSnapshot({
timestamp: getBlockTimestamp(),
totalReserves: totalReserves
});
| reservesSnapshot[cToken] = ReservesSnapshot({
timestamp: getBlockTimestamp(),
totalReserves: totalReserves
});
| 9,033 |
14 | // Query if a contract implements an interface interfaceId The interface identifier, as specified in ERC-165 Interface identification is specified in ERC-165. This functionuses less than 30,000 gas. / | function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
| function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
| 49,808 |
118 | // 兑换法币 | function deposit(address token, uint256 value) external virtual override onlyLegalToken(token) {
address sender = _msgSender();
uint256 fee_ = _calcFee(value, FeeType.Deposit);
uint256 actualValue = value - fee_;
IERC20(token).safeTransferFrom(sender, address(this), actualValue);
if(fee_ > 0) {
IERC20(token).safeTransferFrom(sender, _fund, fee_);
}
_mint(sender, actualValue * _getRatio(token));
emit Deposit(token, sender, value);
}
| function deposit(address token, uint256 value) external virtual override onlyLegalToken(token) {
address sender = _msgSender();
uint256 fee_ = _calcFee(value, FeeType.Deposit);
uint256 actualValue = value - fee_;
IERC20(token).safeTransferFrom(sender, address(this), actualValue);
if(fee_ > 0) {
IERC20(token).safeTransferFrom(sender, _fund, fee_);
}
_mint(sender, actualValue * _getRatio(token));
emit Deposit(token, sender, value);
}
| 72,503 |
65 | // {IERC20-approve}, and its usage is discouraged. Whenever possible, use {safeIncreaseAllowance} and{safeDecreaseAllowance} instead. / | function safeApprove(IERC20 token, address spender, uint256 value) internal {
| function safeApprove(IERC20 token, address spender, uint256 value) internal {
| 9,270 |
2 | // Retrieving the adopters | function getAdopters() public view returns (address[16] memory, uint[16] memory) {
return (adopters, prices);
}
| function getAdopters() public view returns (address[16] memory, uint[16] memory) {
return (adopters, prices);
}
| 20,046 |
1 | // Constructor for the ZapMedia proxy and its implementation/This function is initializable and implements the OZ Initializable contract by inheiritance/beacon the address of the Beacon contract which has the implementation contract address/owner the intended owner of the ZapMedia contract/name name of the collection/symbol collection's symbol/marketContractAddr ZapMarket contract to attach to, this can not be updated/permissive whether or not you would like this contract to be minted by everyone or just the owner/collectionURI the metadata URI of the collection | function initialize(
address beacon,
address payable owner,
string calldata name,
string calldata symbol,
address marketContractAddr,
bool permissive,
string calldata collectionURI
| function initialize(
address beacon,
address payable owner,
string calldata name,
string calldata symbol,
address marketContractAddr,
bool permissive,
string calldata collectionURI
| 13,557 |
223 | // We just sell this percentage of wbtc for digg gains | uint256 _amount = tokenList[1].token.balanceOf(address(this)).mul(sellPercent).div(DIVISION_FACTOR);
| uint256 _amount = tokenList[1].token.balanceOf(address(this)).mul(sellPercent).div(DIVISION_FACTOR);
| 8,293 |
33 | // is unique | bool isUnique
| bool isUnique
| 81,088 |
71 | // update the lastClaim date for tokenId and contractAddress | bytes32 lastClaimKey = keccak256(abi.encode(_metaKidzTokenId));
metaKidzLastClaim[lastClaimKey] = block.timestamp;
| bytes32 lastClaimKey = keccak256(abi.encode(_metaKidzTokenId));
metaKidzLastClaim[lastClaimKey] = block.timestamp;
| 17,410 |
1 | // This Authorizer ignores the 'where' field completely. | return AccessControl.hasRole(actionId, account);
| return AccessControl.hasRole(actionId, account);
| 26,477 |
4 | // function _pairToView(LibPairsManager.Pair storage pair, LibPairsManager.SlippageConfig memory slippageConfig | // ) private view returns (PairView memory) {
// LibPairsManager.LeverageMargin[] memory leverageMargins = new LibPairsManager.LeverageMargin[](pair.maxTier);
// for (uint16 i = 0; i < pair.maxTier; i++) {
// leverageMargins[i] = pair.leverageMargins[i + 1];
// }
// (LibFeeManager.FeeConfig memory fc,) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
// FeeConfig memory feeConfig = FeeConfig(fc.name, fc.index, fc.openFeeP, fc.closeFeeP, fc.enable);
// PairView memory pv = PairView(
// pair.name, pair.base, pair.basePosition, pair.pairType, pair.status, pair.maxLongOiUsd, pair.maxShortOiUsd,
// pair.fundingFeePerBlockP, pair.minFundingFeeR, pair.maxFundingFeeR, leverageMargins,
// pair.slippageConfigIndex, pair.slippagePosition, slippageConfig,
// pair.feeConfigIndex, pair.feePosition, feeConfig, pair.longHoldingFeeRate, pair.shortHoldingFeeRate
// );
// return pv;
// }
| // ) private view returns (PairView memory) {
// LibPairsManager.LeverageMargin[] memory leverageMargins = new LibPairsManager.LeverageMargin[](pair.maxTier);
// for (uint16 i = 0; i < pair.maxTier; i++) {
// leverageMargins[i] = pair.leverageMargins[i + 1];
// }
// (LibFeeManager.FeeConfig memory fc,) = LibFeeManager.getFeeConfigByIndex(pair.feeConfigIndex);
// FeeConfig memory feeConfig = FeeConfig(fc.name, fc.index, fc.openFeeP, fc.closeFeeP, fc.enable);
// PairView memory pv = PairView(
// pair.name, pair.base, pair.basePosition, pair.pairType, pair.status, pair.maxLongOiUsd, pair.maxShortOiUsd,
// pair.fundingFeePerBlockP, pair.minFundingFeeR, pair.maxFundingFeeR, leverageMargins,
// pair.slippageConfigIndex, pair.slippagePosition, slippageConfig,
// pair.feeConfigIndex, pair.feePosition, feeConfig, pair.longHoldingFeeRate, pair.shortHoldingFeeRate
// );
// return pv;
// }
| 7,575 |
48 | // Transfer bidder's funds back | payable(msg.sender).transfer(bidAmount);
| payable(msg.sender).transfer(bidAmount);
| 27,483 |
143 | // Gets an array of owned auctions _owner address of the auction owner / | function getOwnedAuctions(address _owner) public view returns(uint[] memory) {
uint[] memory ownedAllAuctions = ownedAuctions[_owner];
return ownedAllAuctions;
}
| function getOwnedAuctions(address _owner) public view returns(uint[] memory) {
uint[] memory ownedAllAuctions = ownedAuctions[_owner];
return ownedAllAuctions;
}
| 62,510 |
16 | // This address should correspond to the latest MCD Chainlog contract; verifyagainst the current release list at: https:changelog.makerdao.com/releases/mainnet/active/contracts.json | ChainlogAbstract constant CHANGELOG =
ChainlogAbstract(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F);
| ChainlogAbstract constant CHANGELOG =
ChainlogAbstract(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F);
| 36,038 |
40 | // We calculate the new total supply of cTokens and minter token balance, checking for overflow: totalSupplyNew = totalSupply + mintTokens accountTokensNew = accountTokens[minter] + mintTokensAnd write them into storage / | totalSupply = totalSupply + mintTokens;
accountTokens[minter] = accountTokens[minter] + mintTokens;
| totalSupply = totalSupply + mintTokens;
accountTokens[minter] = accountTokens[minter] + mintTokens;
| 14,998 |
130 | // `issueSecurityTokens` is used by the STO to keep track of STO investors _contributor The address of the person whose contributing _amountOfSecurityTokens The amount of ST to pay out. _polyContributed The amount of POLY paid for the security tokens. / | function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) {
// Check whether the offering active or not
require(hasOfferingStarted);
// The _contributor being issued tokens must be in the whitelist
require(shareholders[_contributor].allowed);
// Tokens may only be issued while the STO is running
require(now >= startSTO && now <= endSTO);
// In order to issue the ST, the _contributor first pays in POLY
require(POLY.transferFrom(_contributor, this, _polyContributed));
// ST being issued can't be higher than the totalSupply
require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply);
// POLY contributed can't be higher than maxPoly set by STO
require(maxPoly >= allocations[owner].amount.add(_polyContributed));
// Update ST balances (transfers ST from STO to _contributor)
balances[STO] = balances[STO].sub(_amountOfSecurityTokens);
balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens);
// ERC20 Transfer event
Transfer(STO, _contributor, _amountOfSecurityTokens);
// Update the amount of tokens issued by STO
tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens);
// Update the amount of POLY a contributor has contributed and allocated to the owner
contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed);
allocations[owner].amount = allocations[owner].amount.add(_polyContributed);
LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now);
return true;
}
| function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) {
// Check whether the offering active or not
require(hasOfferingStarted);
// The _contributor being issued tokens must be in the whitelist
require(shareholders[_contributor].allowed);
// Tokens may only be issued while the STO is running
require(now >= startSTO && now <= endSTO);
// In order to issue the ST, the _contributor first pays in POLY
require(POLY.transferFrom(_contributor, this, _polyContributed));
// ST being issued can't be higher than the totalSupply
require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply);
// POLY contributed can't be higher than maxPoly set by STO
require(maxPoly >= allocations[owner].amount.add(_polyContributed));
// Update ST balances (transfers ST from STO to _contributor)
balances[STO] = balances[STO].sub(_amountOfSecurityTokens);
balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens);
// ERC20 Transfer event
Transfer(STO, _contributor, _amountOfSecurityTokens);
// Update the amount of tokens issued by STO
tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens);
// Update the amount of POLY a contributor has contributed and allocated to the owner
contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed);
allocations[owner].amount = allocations[owner].amount.add(_polyContributed);
LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now);
return true;
}
| 3,571 |
17 | // check funding validity | modifier checkIfValid(uint256 _id) {
require(fundingArr[_id].isValid == true, "Can't fund for this cause !!");
_;
}
| modifier checkIfValid(uint256 _id) {
require(fundingArr[_id].isValid == true, "Can't fund for this cause !!");
_;
}
| 16,144 |
274 | // winner free mint | event WinnerMint(uint indexed index, address indexed minter);
| event WinnerMint(uint indexed index, address indexed minter);
| 26,982 |
194 | // send back excess but ignore dust | if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
| if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
| 16,491 |
5 | // Recover signer address from a message by using their signature hash bytes32 message, the hash is the signed message. What is recovered is the signer address. signature bytes signature, the signature is generated using web3.eth.sign() / | function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
| function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
| 19,940 |
6 | // parent hash of oldest block in current merkle trees/(0 once backlog fully imported) | bytes32 public parentHash;
| bytes32 public parentHash;
| 27,496 |
3 | // ballot meta | uint256 constant BB_VERSION = 5;
| uint256 constant BB_VERSION = 5;
| 39,161 |
170 | // Sets `adminRole` as ``role``'s admin role. / | function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
| function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
| 4,832 |
1 | // Emitted when a token is given a new priority order in the displayed price ratio/token The token being given priority order/priority Represents priority in ratio - higher integers get numerator priority | event UpdateTokenRatioPriority(address token, int256 priority);
| event UpdateTokenRatioPriority(address token, int256 priority);
| 4,258 |
88 | // Set the oraclize query id of the last request | * @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity
* @param queryId {bytes32} - The query id from the oraclize request
*/
function setOraclizeQueryId(Data storage self, uint id, bytes32 queryId) public {
self.entities[id].oraclizeQueryId = queryId;
}
| * @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity
* @param queryId {bytes32} - The query id from the oraclize request
*/
function setOraclizeQueryId(Data storage self, uint id, bytes32 queryId) public {
self.entities[id].oraclizeQueryId = queryId;
}
| 46,277 |
284 | // resume liquidity mining program | function resumeMiningReward(uint256 rewardPerBlock) public {
require(hasRole(MANAGER_ROLE, msg.sender), "Caller is not a manager");
_state.pauseMinig = false;
_state.REWARD_PER_BLOCK = rewardPerBlock;
}
| function resumeMiningReward(uint256 rewardPerBlock) public {
require(hasRole(MANAGER_ROLE, msg.sender), "Caller is not a manager");
_state.pauseMinig = false;
_state.REWARD_PER_BLOCK = rewardPerBlock;
}
| 31,763 |
420 | // Restores `value` from logarithmic space. `value` is expected to be the result of a call to `toLowResLog`,any other function that returns 4 decimals fixed point logarithms, or the sum of such values. / | function fromLowResLog(int256 value) internal pure returns (uint256) {
return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR));
}
| function fromLowResLog(int256 value) internal pure returns (uint256) {
return uint256(LogExpMath.exp(value * _LOG_COMPRESSION_FACTOR));
}
| 4,955 |
15 | // Executes a queued proposal if eta has passedproposalId The id of the proposal to execute/ | function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
| function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
| 15,582 |
209 | // Note: Deposit of zero harvests rewards balance, but go ahead and deposit idle want if we have it | ISushiChef(chef).deposit(pid, _beforeLp);
| ISushiChef(chef).deposit(pid, _beforeLp);
| 6,357 |
235 | // read operator's permissions | uint256 p = userRoles[operator];
| uint256 p = userRoles[operator];
| 17,880 |
17 | // All details related to an auction | struct AuctionState {
/// @notice The address of the NFT contract.
address nftContract;
/// @notice The id of the NFT.
uint256 tokenId;
/// @notice The owner of the NFT which listed it in auction.
address payable seller;
/// @notice The difference between two subsequent bids, if no ending phase mechanics are applied.
uint256 minimumIncrement;
/// @notice During the ending phase, the minimum increment becomes a percentage of the highest bid.
uint256 endingPhase;
/// @notice During the ending phase, add a minimum percentage increase each bid must meet.
uint256 endingPhasePercentageFlip;
/// @notice How long to extend the auction with (in seconds) from the last bid.
uint256 extensionWindow;
/// @notice The time at which this auction has kicked off
/// @dev IMPORTANT - In order to save gas and not define another variable, when the auction is reserved price triggered
/// we pass here the duration
uint256 start;
/// @notice The time at which this auction will not accept any new bids.
/// @dev This is `0` until the first bid is placed in case of a reserve price triggered auction.
uint256 end;
/// @notice The current highest bidder in this auction.
/// @dev This is `address(0)` until the first bid is placed.
address payable highestBidder;
/// @notice The latest price of the NFT in this auction.
/// @dev This is set to the reserve price, and then to the highest bid once the auction has started.
uint256 reservePriceOrHighestBid;
/// @notice The price at which anyoane can aquire this NFT while the auction is ongoing.
/// @dev This works only if the value is grater than the highest bid.
uint256 buyOutPrice;
/// @notice Specifies if this is a primary sale or a secondary one.
bool isPrimarySale;
/// @notice Specifies if this is reserve price triggered auction.
bool isReservePriceTriggered;
bool isStandardAuction;
}
| struct AuctionState {
/// @notice The address of the NFT contract.
address nftContract;
/// @notice The id of the NFT.
uint256 tokenId;
/// @notice The owner of the NFT which listed it in auction.
address payable seller;
/// @notice The difference between two subsequent bids, if no ending phase mechanics are applied.
uint256 minimumIncrement;
/// @notice During the ending phase, the minimum increment becomes a percentage of the highest bid.
uint256 endingPhase;
/// @notice During the ending phase, add a minimum percentage increase each bid must meet.
uint256 endingPhasePercentageFlip;
/// @notice How long to extend the auction with (in seconds) from the last bid.
uint256 extensionWindow;
/// @notice The time at which this auction has kicked off
/// @dev IMPORTANT - In order to save gas and not define another variable, when the auction is reserved price triggered
/// we pass here the duration
uint256 start;
/// @notice The time at which this auction will not accept any new bids.
/// @dev This is `0` until the first bid is placed in case of a reserve price triggered auction.
uint256 end;
/// @notice The current highest bidder in this auction.
/// @dev This is `address(0)` until the first bid is placed.
address payable highestBidder;
/// @notice The latest price of the NFT in this auction.
/// @dev This is set to the reserve price, and then to the highest bid once the auction has started.
uint256 reservePriceOrHighestBid;
/// @notice The price at which anyoane can aquire this NFT while the auction is ongoing.
/// @dev This works only if the value is grater than the highest bid.
uint256 buyOutPrice;
/// @notice Specifies if this is a primary sale or a secondary one.
bool isPrimarySale;
/// @notice Specifies if this is reserve price triggered auction.
bool isReservePriceTriggered;
bool isStandardAuction;
}
| 18,406 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.