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
42
// tokenMask can't be 0, since this means that the token is not a collateral token tokenMask can't be 1, since this mask is reserved for underlying
if (tokenMask == 0 || tokenMask == 1) revert ICreditManagerV2Exceptions.TokenNotAllowedException(); // F:[CC-7]
if (tokenMask == 0 || tokenMask == 1) revert ICreditManagerV2Exceptions.TokenNotAllowedException(); // F:[CC-7]
28,792
3
// Zora Module Manager Address
address public zoraModuleManager; constructor( address _implementation, address _platformFeeRecipient, uint256 _platformFee, address _zoraAsksV1_1, address _zoraTransferHelper, address _zoraModuleManager
address public zoraModuleManager; constructor( address _implementation, address _platformFeeRecipient, uint256 _platformFee, address _zoraAsksV1_1, address _zoraTransferHelper, address _zoraModuleManager
28,406
1
// chainlink native-usd data feed
AggregatorV3Interface internal priceFeed; IPangolinRouter public routerContract; bytes32 public constant SWAPPER_ROLE = keccak256('SWAPPER_ROLE');
AggregatorV3Interface internal priceFeed; IPangolinRouter public routerContract; bytes32 public constant SWAPPER_ROLE = keccak256('SWAPPER_ROLE');
6,420
105
// File contracts/TokenBase/TokenStorage.sol
pragma solidity 0.6.12;
pragma solidity 0.6.12;
52,097
1
// Consensus node list
address[] nodes; mapping(address => uint64) stakes;
address[] nodes; mapping(address => uint64) stakes;
12,862
15
// Returns the number of values on the set. O(1). /
function _length(Set storage set) private view returns (uint256) { return set._values.length; }
function _length(Set storage set) private view returns (uint256) { return set._values.length; }
7,530
7
// 如果出价不够高,返还你的钱
require( msg.value > highestBid, "出价不够高" ); if (highestBid != 0) {
require( msg.value > highestBid, "出价不够高" ); if (highestBid != 0) {
12,395
5
// Gets the number of votes a suggestion has received. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License) /
function getVotes(uint256 suggestionId) public view returns (uint256) { return suggestions[suggestionId].votes; }
function getVotes(uint256 suggestionId) public view returns (uint256) { return suggestions[suggestionId].votes; }
11,272
117
// Check the proof of an address if valid for merkle root _to address to check for proof _merkleProof Proof of the address to validate against root and leaf /
function isAllowlisted(address _to, bytes32[] calldata _merkleProof) public view returns(bool) { require(merkleRoot != 0, "Merkle root is not set!"); bytes32 leaf = keccak256(abi.encodePacked(_to)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); }
function isAllowlisted(address _to, bytes32[] calldata _merkleProof) public view returns(bool) { require(merkleRoot != 0, "Merkle root is not set!"); bytes32 leaf = keccak256(abi.encodePacked(_to)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); }
22,401
1
// Initialize quorum as a fraction of the token's total supply. The fraction is specified as `numerator / denominator`. By default the denominator is 100, so quorum isspecified as a percent: a numerator of 10 corresponds to quorum being 10% of total supply. The denominator can becustomized by overriding {quorumDenominator}. /
function __GovernorVotesQuorumFraction_init(uint256 quorumNumeratorValue) internal onlyInitializing { __GovernorVotesQuorumFraction_init_unchained(quorumNumeratorValue); }
function __GovernorVotesQuorumFraction_init(uint256 quorumNumeratorValue) internal onlyInitializing { __GovernorVotesQuorumFraction_init_unchained(quorumNumeratorValue); }
1,809
7
// Max amount of FRAX this contract can mint
int256 public mint_cap = int256(1000000e18);
int256 public mint_cap = int256(1000000e18);
3,928
285
// Returns the downcasted uint32 from uint256, reverting onoverflow (when the input is greater than largest uint32). Counterpart to Solidity's `uint32` operator. Requirements: - input must fit into 32 bits _Available since v2.5._ /
function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); }
function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); }
14,544
7
// Takes: geneName,-name, variant-number, and drug-name as strings. Accepts "" as a wild card, same rules as query /
function entryExists( string memory geneName, string memory variantNumber, string memory drug
function entryExists( string memory geneName, string memory variantNumber, string memory drug
5,362
424
// reset the pool props
pool.stakedAmount = pool.stakedAmount.sub(staker.amount); pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount); uint256 staked = staker.amount;
pool.stakedAmount = pool.stakedAmount.sub(staker.amount); pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.sub(virtualAmount); uint256 staked = staker.amount;
55,004
56
// Percent of the initial supply that will go to the LP
uint constant LP_BPS = 9000;
uint constant LP_BPS = 9000;
17,526
430
// Decodes and returns a 128 bit unsigned integer shifted by an offset from a 256 bit word. /
function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_128; }
function decodeUint128(bytes32 word, uint256 offset) internal pure returns (uint256) { return uint256(word >> offset) & _MASK_128; }
13,520
7
// input Input data block must be 64 bytes (512 bits) in length
function SHA256Compress(bytes input) constant external returns (bytes32 result) { require(input.length == 64); return compressContract.run(input); }
function SHA256Compress(bytes input) constant external returns (bytes32 result) { require(input.length == 64); return compressContract.run(input); }
23,681
62
// This method is used to settle a bet that was mined into an uncle block. At this point the player was shown some bet outcome, but the blockhash at placeBet height is different because of Ethereum chain reorg. We supply a full merkle proof of the placeBet transaction receipt to provide untamperable evidence that uncle block hash indeed was present on-chain at some point.
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); }
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); }
11,192
1
// <yes> <report> ARITHMETIC
count -= input;
count -= input;
694
314
// to be removed
TWAPOracle oracle = TWAPOracle(twapOracleAddress); oracle.update();
TWAPOracle oracle = TWAPOracle(twapOracleAddress); oracle.update();
78,917
322
// Allow root to change the base URI (in case of off-chain problems like the domain dying)
function setBaseURI(string memory _baseURI) public { require (hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); _setBaseURI(_baseURI); }
function setBaseURI(string memory _baseURI) public { require (hasRole(DEFAULT_ADMIN_ROLE, msg.sender)); _setBaseURI(_baseURI); }
24,563
224
// Addition: uint256 + int256uint256(-b) will not overflow when b is IMIN /
function add(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return add(a, uint256(b)); } else { return sub(a, uint256(-b)); } }
function add(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return add(a, uint256(b)); } else { return sub(a, uint256(-b)); } }
76,252
0
// Compute the Merkle root of a Merkle tree with HISTORICAL_NUM_ROOTS leaves/ leaves The HISTORICAL_NUM_ROOTS leaves of the Merkle tree
function merkleRoot(bytes32[HISTORICAL_NUM_ROOTS] memory leaves) internal pure returns (bytes32) {
function merkleRoot(bytes32[HISTORICAL_NUM_ROOTS] memory leaves) internal pure returns (bytes32) {
19,828
27
// Standard overflow check: a/ab=b
uint c0 = a * b; require(c0 / a == b, "ERR_MUL_OVERFLOW");
uint c0 = a * b; require(c0 / a == b, "ERR_MUL_OVERFLOW");
36,479
139
// withdraw all from gauge
Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));
Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));
44,904
33
// Returns the filtered operator at the given index of the set of filtered operators for a given address orits subscription.Note that order is not guaranteed as updates are made. /
function filteredOperatorAt(address registrant, uint256 index) external view returns (address) { address registration = _registrations[registrant]; if (registration != registrant) { return _filteredOperators[registration].at(index); } return _filteredOperators[registrant].at(index); }
function filteredOperatorAt(address registrant, uint256 index) external view returns (address) { address registration = _registrations[registrant]; if (registration != registrant) { return _filteredOperators[registration].at(index); } return _filteredOperators[registrant].at(index); }
16,705
222
// Ensure serviceType cannot be re-added if it previously existed and was removed stored maxStake > 0 means it was previously added and removed
require( serviceTypeInfo[_serviceType].maxStake == 0, "ServiceTypeManager: Cannot re-add serviceType after it was removed." ); validServiceTypes.push(_serviceType); serviceTypeInfo[_serviceType] = ServiceTypeInfo({ isValid: true, minStake: _serviceTypeMin, maxStake: _serviceTypeMax
require( serviceTypeInfo[_serviceType].maxStake == 0, "ServiceTypeManager: Cannot re-add serviceType after it was removed." ); validServiceTypes.push(_serviceType); serviceTypeInfo[_serviceType] = ServiceTypeInfo({ isValid: true, minStake: _serviceTypeMin, maxStake: _serviceTypeMax
41,204
47
// Eastern Standard Time (EST) + 4 hours = Greenwich Mean Time (GMT))
uint numberPeriods = 4; uint256 public countInvestor; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event MinWeiLimitReached(address indexed sender, uint256 weiAmount); event CurrentPeriod(uint period); event Finalized();
uint numberPeriods = 4; uint256 public countInvestor; event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event MinWeiLimitReached(address indexed sender, uint256 weiAmount); event CurrentPeriod(uint period); event Finalized();
25,181
627
// queried by others ({ERC165Checker}).For an implementation, see {ERC165}./ Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30 000 gas. /
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
440
621
// LocalContractAllowListnに削除された場合のイベント /
event LocalCalRemoved(address indexed operator, address indexed transferer);
event LocalCalRemoved(address indexed operator, address indexed transferer);
18,562
5
// 创建抽奖 /
function createLottery(string _name) external onlyCore returns(uint) { lotteries.length ++; Lottery storage lottery = lotteries[lotteries.length - 1]; lottery.name = _name; lottery.status = LotteryStatus.Default; return lotteries.length-1; }
function createLottery(string _name) external onlyCore returns(uint) { lotteries.length ++; Lottery storage lottery = lotteries[lotteries.length - 1]; lottery.name = _name; lottery.status = LotteryStatus.Default; return lotteries.length-1; }
45,138
62
// Check the amount an account has already claimed/account Account to check/ return Amount already claimed
function claimedAmounts(address account) external view returns (uint256);
function claimedAmounts(address account) external view returns (uint256);
3,166
136
// Withdraw `id` with `value` from `token` to the sender.
function withdrawERC1155( IERC1155 token, uint256 id, uint256 value
function withdrawERC1155( IERC1155 token, uint256 id, uint256 value
29,659
588
// Active loan that has entered a new period, so return the next nextDueBlock. But never return something after the termEndBlock
if (balance > 0 && curBlockNumber >= nextDueBlock) { uint256 blocksToAdvance = (curBlockNumber.sub(nextDueBlock).div(blocksPerPeriod)).add(1).mul(blocksPerPeriod); nextDueBlock = nextDueBlock.add(blocksToAdvance); return Math.min(nextDueBlock, cl.termEndBlock()); }
if (balance > 0 && curBlockNumber >= nextDueBlock) { uint256 blocksToAdvance = (curBlockNumber.sub(nextDueBlock).div(blocksPerPeriod)).add(1).mul(blocksPerPeriod); nextDueBlock = nextDueBlock.add(blocksToAdvance); return Math.min(nextDueBlock, cl.termEndBlock()); }
14,558
207
// The Merkle path to the leftmost leaf upon initialisation. It should not be modified after it has been set by the initialize function. Caching these values is essential to efficient appends.
uint256[TREE_DEPTH] public zeros;
uint256[TREE_DEPTH] public zeros;
21,274
14
// Changes product rating. /
function changeRating(IProductEngine.ProductData storage self, bool newLikeState) public { require(self.userRating[msg.sender] > 0); self.purchases[self.userRating[msg.sender] - 1].badRating = !newLikeState; }
function changeRating(IProductEngine.ProductData storage self, bool newLikeState) public { require(self.userRating[msg.sender] > 0); self.purchases[self.userRating[msg.sender] - 1].badRating = !newLikeState; }
16,008
215
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
return _tokenOwners.length();
515
95
// We need to swap the current tokens to ETH and send to the bge wallet
swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHTobge(address(this).balance); }
swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHTobge(address(this).balance); }
12,834
191
// See {IERC777-operatorSend}. Emits {Sent} and {IERC20-Transfer} events. /
function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
2,928
6
// Assert that the sender is not bombarding the contract. Cooldown for avoiding spam-waving.
require(lastWavedAt[msg.sender] + 30 seconds < block.timestamp, "Wait for 30 seconds before waving again");
require(lastWavedAt[msg.sender] + 30 seconds < block.timestamp, "Wait for 30 seconds before waving again");
51,294
152
// Confiscates a Position's collateral and debt balances/Sender has to be allowed to call this method/vault Address of the Vault/tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20)/user Address of the user/collateralizer Address of who puts up or receives the collateral delta/debtor Address of who provides or receives the debt delta/deltaCollateral Amount of collateral to put up (+) for or remove (-) from this Position [wad]/deltaNormalDebt Amount of normalized debt (gross, before rate is applied) to generate (+) or/ settle (-) on this Position [wad]
function confiscateCollateralAndDebt( address vault, uint256 tokenId, address user, address collateralizer, address debtor, int256 deltaCollateral, int256 deltaNormalDebt
function confiscateCollateralAndDebt( address vault, uint256 tokenId, address user, address collateralizer, address debtor, int256 deltaCollateral, int256 deltaNormalDebt
40,954
3
// Emitted when rewards of an asset are accrued on behalf of a user./asset The address of the incentivized asset/reward The address of the reward token/user The address of the user that rewards are accrued on behalf of/assetIndex The index of the asset distribution/userIndex The index of the asset distribution on behalf of the user/rewardsAccrued The amount of rewards accrued
event Accrued( address indexed asset, address indexed reward, address indexed user, uint assetIndex, uint userIndex, uint rewardsAccrued );
event Accrued( address indexed asset, address indexed reward, address indexed user, uint assetIndex, uint userIndex, uint rewardsAccrued );
16,265
2
// Call must happen before transfer
uint256 wantLockedBefore = wantLockedTotal(); IERC20(wantAddress).safeTransferFrom( address(msg.sender), address(this), _wantAmt );
uint256 wantLockedBefore = wantLockedTotal(); IERC20(wantAddress).safeTransferFrom( address(msg.sender), address(this), _wantAmt );
1,896
307
// Reads the bytes26 at `rdPtr` in returndata.
function readBytes26( ReturndataPointer rdPtr
function readBytes26( ReturndataPointer rdPtr
19,732
6
// super
addressPair = uniswapFactory.createPair(tokenA, tokenB); // emits PairCreated event
addressPair = uniswapFactory.createPair(tokenA, tokenB); // emits PairCreated event
3,090
14
// Use safe math for add and sub Create a structure to save our payments
struct Payment { // The total amount the user bought in tokens uint256 totalAmount; // The total amount the user has received in tokens uint256 totalPaid; }
struct Payment { // The total amount the user bought in tokens uint256 totalAmount; // The total amount the user has received in tokens uint256 totalPaid; }
9,058
1
// Emitted when an access code is consumed. /
event AccessCodeConsumed(uint256 groupId, bytes accessCode);
event AccessCodeConsumed(uint256 groupId, bytes accessCode);
25,701
291
// diluted_check/permutation/interaction_elm/ mload(0x240),/column8_inter1_row1/ mload(0x2b20),/diluted_check/permutation/interaction_elm/ mload(0x240),/column8_inter1_row0/ mload(0x2b00), Numerator: point - trace_generator^(trace_length - 1). val = numerators[4].
val := mulmod(val, mload(0x3c60), PRIME)
val := mulmod(val, mload(0x3c60), PRIME)
32,125
5
// Gets current `_pendingOwner`.return Current `_pendingOwner` address. /
function pendingOwner() external view virtual returns (address) { return _pendingOwner; }
function pendingOwner() external view virtual returns (address) { return _pendingOwner; }
24,864
2
// partner index => partner address
mapping(uint=>address) partMap; mapping(address=>Delegator) partners;
mapping(uint=>address) partMap; mapping(address=>Delegator) partners;
19,698
17
// Adds a new airline to the mapping
registeredAirlines[airline] = true; ArrayOfAirlines.push(airline); //To monitor number of airlines. return registeredAirlines[airline];
registeredAirlines[airline] = true; ArrayOfAirlines.push(airline); //To monitor number of airlines. return registeredAirlines[airline];
39,720
17
// Run over the input, 3 bytes at a time
for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) {
for { let dataPtr := data let endPtr := add(data, mload(data)) } lt(dataPtr, endPtr) {
36,703
36
// Operable Base contract that allows the owner to enforce access control over certainoperations by adding or removing operator addresses. /
contract Operable is Pausable { event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); mapping (address => bool) private _operators; constructor() public { _addOperator(msg.sender); } modifier onlyOperator() { require(isOperator(msg.sender)); _; } function isOperator(address account) public view returns (bool) { require(account != address(0)); return _operators[account]; } function addOperator(address account) public onlyOwner { _addOperator(account); } function removeOperator(address account) public onlyOwner { _removeOperator(account); } function _addOperator(address account) internal { require(account != address(0)); _operators[account] = true; emit OperatorAdded(account); } function _removeOperator(address account) internal { require(account != address(0)); _operators[account] = false; emit OperatorRemoved(account); } }
contract Operable is Pausable { event OperatorAdded(address indexed account); event OperatorRemoved(address indexed account); mapping (address => bool) private _operators; constructor() public { _addOperator(msg.sender); } modifier onlyOperator() { require(isOperator(msg.sender)); _; } function isOperator(address account) public view returns (bool) { require(account != address(0)); return _operators[account]; } function addOperator(address account) public onlyOwner { _addOperator(account); } function removeOperator(address account) public onlyOwner { _removeOperator(account); } function _addOperator(address account) internal { require(account != address(0)); _operators[account] = true; emit OperatorAdded(account); } function _removeOperator(address account) internal { require(account != address(0)); _operators[account] = false; emit OperatorRemoved(account); } }
10,198
0
// using SafeMath for uint256;no need since Solidity 0.8
string public constant name = "Cigarette Token"; string public constant symbol = "CIG"; uint8 public constant decimals = 18; uint256 public totalSupply = 0; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
string public constant name = "Cigarette Token"; string public constant symbol = "CIG"; uint8 public constant decimals = 18; uint256 public totalSupply = 0; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
48,547
280
// burns tokens equivalent to the amount requested
_burn(msg.sender, amountToRedeem); bool userIndexReset = false;
_burn(msg.sender, amountToRedeem); bool userIndexReset = false;
34,081
37
// return total0 Quantity of token0 in both positions and unused in the Hypervisor/ return total1 Quantity of token1 in both positions and unused in the Hypervisor
function getTotalAmounts() public view returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = token0.balanceOf(address(this)).add(base0).add(limit0); total1 = token1.balanceOf(address(this)).add(base1).add(limit1); }
function getTotalAmounts() public view returns (uint256 total0, uint256 total1) { (, uint256 base0, uint256 base1) = getBasePosition(); (, uint256 limit0, uint256 limit1) = getLimitPosition(); total0 = token0.balanceOf(address(this)).add(base0).add(limit0); total1 = token1.balanceOf(address(this)).add(base1).add(limit1); }
22,478
5
// This function is used by employees to apply to a specific job _id The id of the specific job listed /
function applyJob(uint _id) external { Job memory job = s_Jobs[_id]; if(!s_pending[msg.sender]) { revert FreelancingBasicContract__AlreadyApplied(); } if(msg.sender == job.employer) { revert FreelancingBasicContract__EmployerCantEmployHimself(); } s_pending[msg.sender] = true; }
function applyJob(uint _id) external { Job memory job = s_Jobs[_id]; if(!s_pending[msg.sender]) { revert FreelancingBasicContract__AlreadyApplied(); } if(msg.sender == job.employer) { revert FreelancingBasicContract__EmployerCantEmployHimself(); } s_pending[msg.sender] = true; }
23,960
22
// Returns true if `token` is registered in a General Pool. This function assumes `poolId` exists and corresponds to the General specialization setting. /
function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; return poolBalances.contains(token); }
function _isGeneralPoolTokenRegistered(bytes32 poolId, IERC20 token) internal view returns (bool) { EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[poolId]; return poolBalances.contains(token); }
60
29
// subtract this amount of fragments from their balance
_shareBalances[account] = _shareBalances[account].sub(shareAmount);
_shareBalances[account] = _shareBalances[account].sub(shareAmount);
1,709
10
// GEB_AUTO_SURPLUS_BUFFER, INCREASING_TREASURY_REIMBURSEMENT_OVERLAY
AuthLike(0x1450f40E741F2450A95F9579Be93DD63b8407a25).addAuthorization(0x1dCeE093a7C952260f591D9B8401318f2d2d72Ac);
AuthLike(0x1450f40E741F2450A95F9579Be93DD63b8407a25).addAuthorization(0x1dCeE093a7C952260f591D9B8401318f2d2d72Ac);
81,566
36
// Claim pending rewards for one or more pools. Rewards are not received directly, they are locked by the STRFLocker.
function claim(uint256 pid) external stakingStarted(pid) { PoolInfo storage poolInfo = _poolInfo[pid]; UserInfo storage userInfo = _userInfo[pid][msg.sender]; _updatePool(pid); uint256 pending = userInfo.amount * poolInfo.accSTRFPerShare / 1e12 - userInfo.rewardDebt; userInfo.rewardDebt = userInfo.amount * poolInfo.accSTRFPerShare / 1e12; if (pending > 0) { _STRFLocker.lock(msg.sender, pending); } emit Claim(msg.sender, pid, pending); }
function claim(uint256 pid) external stakingStarted(pid) { PoolInfo storage poolInfo = _poolInfo[pid]; UserInfo storage userInfo = _userInfo[pid][msg.sender]; _updatePool(pid); uint256 pending = userInfo.amount * poolInfo.accSTRFPerShare / 1e12 - userInfo.rewardDebt; userInfo.rewardDebt = userInfo.amount * poolInfo.accSTRFPerShare / 1e12; if (pending > 0) { _STRFLocker.lock(msg.sender, pending); } emit Claim(msg.sender, pid, pending); }
3,796
115
// Returns whether the sale is during its refund period./ return bool whether the sale is during its refund period.
function saleDuringRefundPeriod() private view returns (bool) { return saleEnded() && now <= refundEndTime; }
function saleDuringRefundPeriod() private view returns (bool) { return saleEnded() && now <= refundEndTime; }
14,423
302
// Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
mapping(uint16 => bool) public pausedTokens;
16,150
25
// Get the metadata for a given token ID
function getTokenMetadata(uint256 tokenId) public view returns (string memory) { return _tokenMetadata[tokenId]; }
function getTokenMetadata(uint256 tokenId) public view returns (string memory) { return _tokenMetadata[tokenId]; }
3,315
69
// Calculate 2 raised into given power.x power to raise 2 into, multiplied by 2^121return 2 raised into given power /
function pow_2 (uint128 x)
function pow_2 (uint128 x)
10,768
1
// withdraws FATE back to the owner
amount = amount > IERC20(fate).balanceOf(address(this)) ? IERC20(fate).balanceOf(address(this)) : amount; IERC20(fate).safeTransfer(owner(), amount);
amount = amount > IERC20(fate).balanceOf(address(this)) ? IERC20(fate).balanceOf(address(this)) : amount; IERC20(fate).safeTransfer(owner(), amount);
15,563
106
// set totalRedeemed to all transferable collateral
totalRedeemed = collateralForAccount;
totalRedeemed = collateralForAccount;
7,247
0
// it can only be activated, once activated, it can't be disabled
bool public isTradingEnabled;
bool public isTradingEnabled;
24,817
69
// Returns the address of the owner of the NFT. NFTs assigned to zero address are consideredinvalid, and queries about them do throw. _tokenId The identifier for an NFT.return Address of _tokenId owner. /
function ownerOf(
function ownerOf(
816
11
// Delegates tokens to a new operator using beneficiary and/ authorizer passed in _extraData parameter./_from The owner of the tokens who approved them to transfer./_value Approved amount for the transfer and stake./_operator The new operator address./_extraData Data for stake delegation as passed to receiveApproval.
function delegate( address _from, uint256 _value, address _operator, bytes memory _extraData
function delegate( address _from, uint256 _value, address _operator, bytes memory _extraData
15,550
13
// Deprecated. TODO: remove from interfaces, and remove references.
enum GaugeType { LiquidityMiningCommittee, veBAL, Ethereum, Polygon, Arbitrum, Optimism, Gnosis, ZKSync } // String values are hashed when indexed, so we also emit the raw string as a data field for ease of use. event GaugeTypeAdded(string indexed indexedGaugeType, string gaugeType); event GaugeFactorySet(string indexed indexedGaugeType, string gaugeType, ILiquidityGaugeFactory gaugeFactory); /** * @notice Returns the address of the Authorizer adaptor entrypoint contract. */ function getAuthorizerAdaptorEntrypoint() external view returns (IAuthorizerAdaptorEntrypoint); /** * @notice Returns the address of the Gauge Controller */ function getGaugeController() external view returns (IGaugeController); /** * @notice Returns the list of gauge types. */ function getGaugeTypes() external view returns (string[] memory); /** * @notice Returns gauge type name registered at the given index. */ function getGaugeTypeAtIndex(uint256 index) external view returns (string memory); /** * @notice Returns the number of gauge types. */ function getGaugeTypesCount() external view returns (uint256); /** * @notice Returns true if the given gauge type is valid; false otherwise. */ function isValidGaugeType(string memory gaugeType) external view returns (bool); /** * @notice Returns the factory for gauge type `gaugeType`. */ function getFactoryForGaugeType(string memory gaugeType) external view returns (ILiquidityGaugeFactory); /** * @notice Returns true if `gauge` has been deployed by the factory for the gauge type `gaugeType`. * Note that if a gauge type's factory changes then this function will start returning false for previously * valid gauges. */ function isGaugeFromValidFactory(address gauge, string memory gaugeType) external view returns (bool); /** * @notice Adds a new `gaugeType` corresponding to a new network, which allows setting a factory and adding gauges * for the type later on. * @param gaugeType Name of the new gauge type. */ function addGaugeType(string memory gaugeType) external; /** * @notice Adds a new gauge to the GaugeController for the given `gaugeType` type. * @dev When adding gauges for L2 networks or sidechains, this must be called with the address of the *root* gauge * which is deployed on Ethereum. It should *not* be called with the address of the child gauge which is deployed on * the L2 / sidechain. * * If the gauge added is an Ethereum gauge, it cannot be a gauge for the 80BAL-20WETH pool. */ function addGauge(address gauge, string memory gaugeType) external; /** * @notice Sets `factory` as the allowlisted factory contract for gauges with type `gaugeType`. * @dev This function can either set a new factory or replace an existing one. */ function setGaugeFactory(ILiquidityGaugeFactory factory, string memory gaugeType) external; }
enum GaugeType { LiquidityMiningCommittee, veBAL, Ethereum, Polygon, Arbitrum, Optimism, Gnosis, ZKSync } // String values are hashed when indexed, so we also emit the raw string as a data field for ease of use. event GaugeTypeAdded(string indexed indexedGaugeType, string gaugeType); event GaugeFactorySet(string indexed indexedGaugeType, string gaugeType, ILiquidityGaugeFactory gaugeFactory); /** * @notice Returns the address of the Authorizer adaptor entrypoint contract. */ function getAuthorizerAdaptorEntrypoint() external view returns (IAuthorizerAdaptorEntrypoint); /** * @notice Returns the address of the Gauge Controller */ function getGaugeController() external view returns (IGaugeController); /** * @notice Returns the list of gauge types. */ function getGaugeTypes() external view returns (string[] memory); /** * @notice Returns gauge type name registered at the given index. */ function getGaugeTypeAtIndex(uint256 index) external view returns (string memory); /** * @notice Returns the number of gauge types. */ function getGaugeTypesCount() external view returns (uint256); /** * @notice Returns true if the given gauge type is valid; false otherwise. */ function isValidGaugeType(string memory gaugeType) external view returns (bool); /** * @notice Returns the factory for gauge type `gaugeType`. */ function getFactoryForGaugeType(string memory gaugeType) external view returns (ILiquidityGaugeFactory); /** * @notice Returns true if `gauge` has been deployed by the factory for the gauge type `gaugeType`. * Note that if a gauge type's factory changes then this function will start returning false for previously * valid gauges. */ function isGaugeFromValidFactory(address gauge, string memory gaugeType) external view returns (bool); /** * @notice Adds a new `gaugeType` corresponding to a new network, which allows setting a factory and adding gauges * for the type later on. * @param gaugeType Name of the new gauge type. */ function addGaugeType(string memory gaugeType) external; /** * @notice Adds a new gauge to the GaugeController for the given `gaugeType` type. * @dev When adding gauges for L2 networks or sidechains, this must be called with the address of the *root* gauge * which is deployed on Ethereum. It should *not* be called with the address of the child gauge which is deployed on * the L2 / sidechain. * * If the gauge added is an Ethereum gauge, it cannot be a gauge for the 80BAL-20WETH pool. */ function addGauge(address gauge, string memory gaugeType) external; /** * @notice Sets `factory` as the allowlisted factory contract for gauges with type `gaugeType`. * @dev This function can either set a new factory or replace an existing one. */ function setGaugeFactory(ILiquidityGaugeFactory factory, string memory gaugeType) external; }
34,538
248
// All fields except `nftProperties` align with those of NFTSellOrder
struct NFTBuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; }
struct NFTBuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; }
43,259
195
// Units can be contructed within public and owned buildings.
function createUnit(uint256 _buildingId) public payable returns(uint256)
function createUnit(uint256 _buildingId) public payable returns(uint256)
58,275
10
// Emits a {BeneficiaryEdited} event. Requirements: - Caller must have role BENEFICIARY_MANAGER_ROLE. /
function setBeneficiary(address beneficiaryAddress) public onlyRole(BENEFICIARY_MANAGER_ROLE) { require( beneficiaryAddress != address(0), "VestingWalletMultiLinear: beneficiary is zero address" ); _beneficiary = beneficiaryAddress;
function setBeneficiary(address beneficiaryAddress) public onlyRole(BENEFICIARY_MANAGER_ROLE) { require( beneficiaryAddress != address(0), "VestingWalletMultiLinear: beneficiary is zero address" ); _beneficiary = beneficiaryAddress;
73,352
255
// The pool is not ready yet or insufficient lp in pool.
continue;
continue;
22,258
3
// Returns the implementation address for a given contract name.If the implementation is not found in the directory, it will search in thestandard library. contractName Name of the contract.return Address where the contract is implemented, or 0 if it is notfound. /
function getImplementation(string contractName) public view returns (address) { address implementation = super.getImplementation(contractName); if(implementation != address(0)) return implementation; if(stdlib != address(0)) return stdlib.getImplementation(contractName); return address(0); }
function getImplementation(string contractName) public view returns (address) { address implementation = super.getImplementation(contractName); if(implementation != address(0)) return implementation; if(stdlib != address(0)) return stdlib.getImplementation(contractName); return address(0); }
534
6
// 1. True up redeemable pool
uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable < totalCoupons) { newRedeemable = totalCoupons.sub(totalRedeemable); newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable; mintToRedeemable(newRedeemable); newSupply = newSupply.sub(newRedeemable); }
uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable < totalCoupons) { newRedeemable = totalCoupons.sub(totalRedeemable); newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable; mintToRedeemable(newRedeemable); newSupply = newSupply.sub(newRedeemable); }
26,357
4
// ============ State Variables ============ / List of enabled Communities
address[] public gardens; address[] public reserveAssets; address private uniswapFactory; // do not use address public override gardenValuer; address public override priceOracle; address public override gardenFactory; address public override rewardsDistributor; address public override ishtarGate; address public override strategyFactory; address public override gardenNFT;
address[] public gardens; address[] public reserveAssets; address private uniswapFactory; // do not use address public override gardenValuer; address public override priceOracle; address public override gardenFactory; address public override rewardsDistributor; address public override ishtarGate; address public override strategyFactory; address public override gardenNFT;
72,344
33
// Owner of the contract
address private _upgradeabilityOwner;
address private _upgradeabilityOwner;
48,279
27
// Bubble up the revert reason.
assembly { revert(add(32, returnedData), mload(returnedData)) }
assembly { revert(add(32, returnedData), mload(returnedData)) }
14,890
237
// Tell the information for the current DisputeManager module return addr Current address of the DisputeManager module return disabled Whether the module has been disabled/
function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); }
function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); }
69,007
81
// New upgrade agent has been set. /
event UpgradeAgentSet(address agent);
event UpgradeAgentSet(address agent);
2,584
161
// require(asset.transferFrom(msg.sender, address(this), uint256(amount)), "E6");
IERC20(assetAddress).safeTransferFrom(msg.sender, address(this), uint256(amount)); generalDeposit(assetAddress,amount);
IERC20(assetAddress).safeTransferFrom(msg.sender, address(this), uint256(amount)); generalDeposit(assetAddress,amount);
28,356
3
// Upgrades the address type to use sendValue instead of transfer. /
library AddressSendValue { /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value"); } }
library AddressSendValue { /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value"); } }
16,658
90
// Inspired by: MerkleDistributor contract. Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specifymultiple Merkle roots distributions with customized reward currencies.The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. /
contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } }
contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } }
31,768
55
// calculate players total amount of carrots including the unrecorded /
function calcPlayerTotalCarrots() private view returns (uint256)
function calcPlayerTotalCarrots() private view returns (uint256)
8,212
0
// uint256 SEED_NONCE = 0;
uint256 private SALE_PRICE = 0.08 ether; uint256 private balance = 0; bool private isActive = false;
uint256 private SALE_PRICE = 0.08 ether; uint256 private balance = 0; bool private isActive = false;
71,003
96
// Gets
function getBlockNum() public view returns (uint256) {return block.number;}
function getBlockNum() public view returns (uint256) {return block.number;}
54,864
41
// Current ReleaseTime in the CustomCrowdsale
function getReleaseTime() public view returns (uint) { return releaseTime; }
function getReleaseTime() public view returns (uint) { return releaseTime; }
9,946
173
// enough confirmations: reset and run interior.
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true;
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true;
16,150
7
// get artwork
function getArtwork(uint256 id) external view returns (string memory, uint256) { Artwork memory a = artwork[id]; return (a.hash, a.collection); }
function getArtwork(uint256 id) external view returns (string memory, uint256) { Artwork memory a = artwork[id]; return (a.hash, a.collection); }
33,456
2
// The set of admins which have also approved SDOG to this contract for it to sell.
address[] public admins; mapping(address => bool) public isAdmin;
address[] public admins; mapping(address => bool) public isAdmin;
3,027
106
// edit sellOrders[_price][iii]
self.sellOrders[_price][iii].amount = self.sellOrders[_price][iii].amount - _amount;
self.sellOrders[_price][iii].amount = self.sellOrders[_price][iii].amount - _amount;
47,017
138
// element14/
contract CoinFlip is usingOraclize { modifier onlyAdmin() { require(msg.sender == adminAddress); _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { if (msg.sender != oraclize_cbAddress()) throw; _; } event newBet(string _str); //Setup address public adminAddress; //GameSetup uint public minBet; uint public maxProfit; //FeeSetup uint public oraclizeFee; uint public adminFee; uint public oraclizeGasLimit; uint public maxProfitPercentage; uint public totalPlay; uint public totalLose; uint public totalWon; uint public totalWeiWon; uint public totalWeiLose; uint public contractBalance; //PlayerSetup // Array of players mapping (bytes32 => address) playerAddress; mapping (bytes32 => uint) playerBetAmount; mapping (bytes32 => uint) playerBetNumber; string public _result; function CoinFlip() payable { //ConstructorVars adminAddress=msg.sender; //minBet = (5000000000000000 * 1 wei); //adminFee=99; //1% of houseEdge //oraclizeGasLimit = 235000; //maxProfitPercentage=1; } function __callback(bytes32 queryId, string result) onlyOraclize { _result=result; uint weiWon; if( (parseInt(result)/50) == playerBetNumber[queryId] ){ totalWon++; weiWon=( ( playerBetAmount[queryId] * adminFee/100 ) - oraclizeFee)*2; totalWeiWon+=weiWon; playerAddress[queryId].transfer(weiWon ); }else{ totalLose++; } maxProfit=(this.balance * maxProfitPercentage)/100; delete playerAddress[queryId]; delete playerBetAmount[queryId]; delete playerBetNumber[queryId]; } function Bet(uint _number) payable returns (bytes32){ uint betValue = msg.value; assert(maxProfit > (betValue*2)); if(betValue < minBet) throw; totalWeiLose+=betValue; totalPlay++; bytes32 queryId = oraclize_query("WolframAlpha", "random number between 0 and 99",oraclizeGasLimit); playerAddress[queryId]=msg.sender; playerBetAmount[queryId]=betValue; playerBetNumber[queryId]=_number; return queryId; } function setGame(uint _adminFee , uint _minBet , uint _oraclizeGasLimit , uint _maxProfitPercentage , uint _oraclizeFee , uint newGas) public onlyAdmin{ adminFee = _adminFee; minBet = (_minBet * 1 wei); oraclizeGasLimit = _oraclizeGasLimit ; maxProfitPercentage= _maxProfitPercentage; maxProfit=(this.balance*_maxProfitPercentage)/100; oraclizeFee=(_oraclizeFee * 1 wei); oraclize_setCustomGasPrice(newGas * 1 wei); contractBalance=this.balance; } function withdraw(uint _amount , address _addr) public onlyAdmin{ _addr.transfer(_amount); contractBalance=this.balance; maxProfit=(contractBalance*maxProfitPercentage)/100; } function updateBalance() payable{ contractBalance=this.balance; maxProfit=(contractBalance*maxProfitPercentage)/100; } function getGameVars() public view returns( uint _maxProfit, uint _minBet, uint _totalPlay, uint _totalLose, uint _totalWon, uint _maxProfitPercentage, uint _contractbalance, uint _totalWeiWon, uint _totalWeiLose ){ _maxProfit=maxProfit; _minBet=minBet; _totalPlay=totalPlay; _totalLose=totalLose; _totalWon=totalWon; _maxProfitPercentage=maxProfitPercentage; _contractbalance=contractBalance; _totalWeiWon=totalWeiWon; _totalWeiLose=totalWeiLose; } }
contract CoinFlip is usingOraclize { modifier onlyAdmin() { require(msg.sender == adminAddress); _; } /* * checks only Oraclize address is calling */ modifier onlyOraclize { if (msg.sender != oraclize_cbAddress()) throw; _; } event newBet(string _str); //Setup address public adminAddress; //GameSetup uint public minBet; uint public maxProfit; //FeeSetup uint public oraclizeFee; uint public adminFee; uint public oraclizeGasLimit; uint public maxProfitPercentage; uint public totalPlay; uint public totalLose; uint public totalWon; uint public totalWeiWon; uint public totalWeiLose; uint public contractBalance; //PlayerSetup // Array of players mapping (bytes32 => address) playerAddress; mapping (bytes32 => uint) playerBetAmount; mapping (bytes32 => uint) playerBetNumber; string public _result; function CoinFlip() payable { //ConstructorVars adminAddress=msg.sender; //minBet = (5000000000000000 * 1 wei); //adminFee=99; //1% of houseEdge //oraclizeGasLimit = 235000; //maxProfitPercentage=1; } function __callback(bytes32 queryId, string result) onlyOraclize { _result=result; uint weiWon; if( (parseInt(result)/50) == playerBetNumber[queryId] ){ totalWon++; weiWon=( ( playerBetAmount[queryId] * adminFee/100 ) - oraclizeFee)*2; totalWeiWon+=weiWon; playerAddress[queryId].transfer(weiWon ); }else{ totalLose++; } maxProfit=(this.balance * maxProfitPercentage)/100; delete playerAddress[queryId]; delete playerBetAmount[queryId]; delete playerBetNumber[queryId]; } function Bet(uint _number) payable returns (bytes32){ uint betValue = msg.value; assert(maxProfit > (betValue*2)); if(betValue < minBet) throw; totalWeiLose+=betValue; totalPlay++; bytes32 queryId = oraclize_query("WolframAlpha", "random number between 0 and 99",oraclizeGasLimit); playerAddress[queryId]=msg.sender; playerBetAmount[queryId]=betValue; playerBetNumber[queryId]=_number; return queryId; } function setGame(uint _adminFee , uint _minBet , uint _oraclizeGasLimit , uint _maxProfitPercentage , uint _oraclizeFee , uint newGas) public onlyAdmin{ adminFee = _adminFee; minBet = (_minBet * 1 wei); oraclizeGasLimit = _oraclizeGasLimit ; maxProfitPercentage= _maxProfitPercentage; maxProfit=(this.balance*_maxProfitPercentage)/100; oraclizeFee=(_oraclizeFee * 1 wei); oraclize_setCustomGasPrice(newGas * 1 wei); contractBalance=this.balance; } function withdraw(uint _amount , address _addr) public onlyAdmin{ _addr.transfer(_amount); contractBalance=this.balance; maxProfit=(contractBalance*maxProfitPercentage)/100; } function updateBalance() payable{ contractBalance=this.balance; maxProfit=(contractBalance*maxProfitPercentage)/100; } function getGameVars() public view returns( uint _maxProfit, uint _minBet, uint _totalPlay, uint _totalLose, uint _totalWon, uint _maxProfitPercentage, uint _contractbalance, uint _totalWeiWon, uint _totalWeiLose ){ _maxProfit=maxProfit; _minBet=minBet; _totalPlay=totalPlay; _totalLose=totalLose; _totalWon=totalWon; _maxProfitPercentage=maxProfitPercentage; _contractbalance=contractBalance; _totalWeiWon=totalWeiWon; _totalWeiLose=totalWeiLose; } }
60,914
182
// Pauses ICO contribution.
function haltICO() public onlyFounder { // Set the state to halt. icoState = State.halted; }
function haltICO() public onlyFounder { // Set the state to halt. icoState = State.halted; }
39,800
46
// INIT POOL //Set the initial params of the pool/It is expected that the parameters have already been verified/_multiplier Multiplier to calculate price/_startPrice The Star Price ( depending of the algorithm it will be take it by different ways )/_recipient The recipient of the input assets/_owner The owner of the pool/_NFT The NFT collection that will be trade/_fee Pool fee charged per trade/_Algorithm Address of the algorithm to calculate the price/_poolType The type of the pool
function init( uint128 _multiplier, uint128 _startPrice, address _recipient, address _owner, address _NFT, uint128 _fee, IMetaAlgorithm _Algorithm, PoolTypes.PoolType _poolType ) public payable
function init( uint128 _multiplier, uint128 _startPrice, address _recipient, address _owner, address _NFT, uint128 _fee, IMetaAlgorithm _Algorithm, PoolTypes.PoolType _poolType ) public payable
3,766
27
// CDP >>> msg.sender
loanMaster.give(cup, msg.sender);
loanMaster.give(cup, msg.sender);
47,886
60
// loop through each bucket of Wolves with the same alpha score
for (uint256 i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i;
for (uint256 i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i;
28,585
37
//
emit _BlockPurchased(block_id, msg.sender, file_hash_[i], msg.value, attachments, tags);
emit _BlockPurchased(block_id, msg.sender, file_hash_[i], msg.value, attachments, tags);
20,587
23
// Verify the game still hasn't started yet
Assert.equal(uint(status), 0, "The game should not be started");
Assert.equal(uint(status), 0, "The game should not be started");
44,197