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
98
// Returns address of token correspond to collateral token
function token() external view override returns (address) { return receiptToken; }
function token() external view override returns (address) { return receiptToken; }
61,453
4
// "OffchainAggTCD" is a TCD that curates a list of trusted addresses. Data points from all reporters are aggregated/ off-chain and reported using `report` function with ECDSA signatures. Data providers are responsible for combining/ data points into one aggregated value together with timestamp and status, which will be reported to this contract.
contract OffchainAggTCD is TCDBase { using SafeMath for uint256; event DataUpdated( bytes key, uint256 value, uint64 timestamp, QueryStatus status ); struct DataPoint { uint256 value; uint64 timestamp; QueryStatus status; } mapping(bytes => DataPoint) private aggData; constructor( bytes8 _prefix, BondingCurve _bondingCurve, Parameters _params, BandRegistry _registry ) public TCDBase(_prefix, _bondingCurve, _params, _registry) {} function queryPrice() public view returns (uint256) { return params.get(prefix, "query_price"); } function report( bytes calldata key, uint256 value, uint64 timestamp, QueryStatus status, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s ) external { require(v.length == r.length && v.length == s.length); uint256 validSignatures = 0; bytes32 message = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked(key, value, timestamp, status, address(this)) ) ) ); address lastSigner = address(0); for (uint256 i = 0; i < v.length; ++i) { address recovered = ecrecover(message, v[i], r[i], s[i]); require(recovered > lastSigner); lastSigner = recovered; if (activeList[recovered] != NOT_FOUND) { validSignatures++; } } require(validSignatures.mul(3) > activeCount.mul(2)); require(timestamp > aggData[key].timestamp && uint256(timestamp) <= now); aggData[key] = DataPoint({ value: value, timestamp: timestamp, status: status }); emit DataUpdated(key, value, timestamp, status); } function queryImpl(bytes memory input) internal returns ( bytes32 output, uint256 updatedAt, QueryStatus status ) { DataPoint storage data = aggData[input]; if (data.timestamp == 0) return ("", 0, QueryStatus.NOT_AVAILABLE); if (data.status != QueryStatus.OK) return ("", data.timestamp, data.status); return (bytes32(data.value), data.timestamp, QueryStatus.OK); } }
contract OffchainAggTCD is TCDBase { using SafeMath for uint256; event DataUpdated( bytes key, uint256 value, uint64 timestamp, QueryStatus status ); struct DataPoint { uint256 value; uint64 timestamp; QueryStatus status; } mapping(bytes => DataPoint) private aggData; constructor( bytes8 _prefix, BondingCurve _bondingCurve, Parameters _params, BandRegistry _registry ) public TCDBase(_prefix, _bondingCurve, _params, _registry) {} function queryPrice() public view returns (uint256) { return params.get(prefix, "query_price"); } function report( bytes calldata key, uint256 value, uint64 timestamp, QueryStatus status, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s ) external { require(v.length == r.length && v.length == s.length); uint256 validSignatures = 0; bytes32 message = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked(key, value, timestamp, status, address(this)) ) ) ); address lastSigner = address(0); for (uint256 i = 0; i < v.length; ++i) { address recovered = ecrecover(message, v[i], r[i], s[i]); require(recovered > lastSigner); lastSigner = recovered; if (activeList[recovered] != NOT_FOUND) { validSignatures++; } } require(validSignatures.mul(3) > activeCount.mul(2)); require(timestamp > aggData[key].timestamp && uint256(timestamp) <= now); aggData[key] = DataPoint({ value: value, timestamp: timestamp, status: status }); emit DataUpdated(key, value, timestamp, status); } function queryImpl(bytes memory input) internal returns ( bytes32 output, uint256 updatedAt, QueryStatus status ) { DataPoint storage data = aggData[input]; if (data.timestamp == 0) return ("", 0, QueryStatus.NOT_AVAILABLE); if (data.status != QueryStatus.OK) return ("", data.timestamp, data.status); return (bytes32(data.value), data.timestamp, QueryStatus.OK); } }
21,196
6
// The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.
result = (x >> 1) + (y >> 1) + (x & y & 1);
result = (x >> 1) + (y >> 1) + (x & y & 1);
16,992
239
// Build the requested set of owners into a new temporary array:
for (uint i = _startIndex; i < endOfPageIndex; i++) { ownersByPage[pageIndex] = owners[i]; pageIndex++; }
for (uint i = _startIndex; i < endOfPageIndex; i++) { ownersByPage[pageIndex] = owners[i]; pageIndex++; }
32,303
6
// Initializes the contract with immutable variables _share is the erc1155 contract that issues shares _marginEngine is the margin engine used for Grappa (options protocol) /
constructor(address _share, address _marginEngine) BaseOptionsVault(_share) { if (_marginEngine == address(0)) revert BadAddress(); marginEngine = IMarginEnginePhysical(_marginEngine); }
constructor(address _share, address _marginEngine) BaseOptionsVault(_share) { if (_marginEngine == address(0)) revert BadAddress(); marginEngine = IMarginEnginePhysical(_marginEngine); }
15,374
100
// Counter underflow is impossible as _burnCounter cannot be incremented more than `_currentIndex - _startTokenId()` times.
unchecked { return _currentIndex - _burnCounter - _startTokenId(); }
unchecked { return _currentIndex - _burnCounter - _startTokenId(); }
5,021
2
// Allows for multiple option votes.Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by thecontract. /
struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; }
struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; }
18,928
56
// _owner The owner whose celebrity tokens we are interested in./This method MUST NEVER be called by smart contract code. First, it's fairly/expensive (it walks the entire tokens array looking for tokens belonging to owner),/but it also returns a dynamic array, which is only supported for web3 calls, and/not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = getTotalSupply(); uint256 resultIndex = 0; uint256 tokenIndex; uint256 tokenId; for (tokenIndex = 0; tokenIndex < totalTokens; tokenIndex++) { tokenId = tokens[tokenIndex]; if (collectibleIdx[tokenId].owner == _owner) { result[resultIndex] = tokenId; resultIndex = resultIndex.add(1); } } return result; } }
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = getTotalSupply(); uint256 resultIndex = 0; uint256 tokenIndex; uint256 tokenId; for (tokenIndex = 0; tokenIndex < totalTokens; tokenIndex++) { tokenId = tokens[tokenIndex]; if (collectibleIdx[tokenId].owner == _owner) { result[resultIndex] = tokenId; resultIndex = resultIndex.add(1); } } return result; } }
32,985
114
// capable of setting FEI Minters within global rate limits and caps
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
48,407
506
// The account is fully vaporizable using excess funds
if (excessWei.value >= maxRefundWei.value) { state.setPar( args.vaporAccount, args.owedMarket, Types.zeroPar() ); return (true, maxRefundWei); }
if (excessWei.value >= maxRefundWei.value) { state.setPar( args.vaporAccount, args.owedMarket, Types.zeroPar() ); return (true, maxRefundWei); }
35,791
116
// global state fields
uint256 public totalLockedShares; uint256 public totalStakingShares; uint256 public totalRewards; uint256 public totalGysrRewards; uint256 public totalStakingShareSeconds; uint256 public lastUpdated;
uint256 public totalLockedShares; uint256 public totalStakingShares; uint256 public totalRewards; uint256 public totalGysrRewards; uint256 public totalStakingShareSeconds; uint256 public lastUpdated;
71,767
38
// Transfer tokens from vault to account if sales agent is correct
function transferTokensFromVault(address _from, address _to, uint256 _amount) public { require(salesAgent == msg.sender); balances[vault] = balances[vault].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); }
function transferTokensFromVault(address _from, address _to, uint256 _amount) public { require(salesAgent == msg.sender); balances[vault] = balances[vault].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); }
20,812
10
// register user function. can only be called by the owner when a user registers on the web app./ puts their address in the registered mapping and increments the numRegistered/self Stored crowdsale from crowdsale contract/_registrant address to be registered for the sale
function registerUser(EvenDistroCrowdsaleStorage storage self, address _registrant) public returns (bool)
function registerUser(EvenDistroCrowdsaleStorage storage self, address _registrant) public returns (bool)
30,018
69
// get block timestamp when an answer was last updated _roundId the answer number to retrieve the updated timestamp for overridden function to add the checkAccess() modifier[deprecated] Use getRoundData instead. This does not error if noanswer has been reached, it will simply return 0. Either wait to point toan already answered Aggregator or use the recommended getRoundDatainstead which includes better verification information. /
function getTimestamp(uint256 _roundId) public view override checkAccess() returns (uint256)
function getTimestamp(uint256 _roundId) public view override checkAccess() returns (uint256)
33,729
96
// solhint-enable var-name-mixedcase //Initializes the domain separator and parameter caches. The meaning of `name` and `version` is specified in - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. - `version`: the current major version of the signing domain. NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart contract upgrade]./
constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name));
constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name));
11,040
189
// MLBNFT constructor. /
constructor() public { // Starts paused. paused = true; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "LucidSight-MLB-NFT"; symbol_ = "MLBCB"; }
constructor() public { // Starts paused. paused = true; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "LucidSight-MLB-NFT"; symbol_ = "MLBCB"; }
38,235
84
// Calculate baseline number of tokens
uint numTokens = safeMul(_amount, rate);
uint numTokens = safeMul(_amount, rate);
2,657
237
// Convert shares to amount of debt tokens
debtTokenValue = _convertToDebt(shares, startingYieldToken, startingParams.underlyingToken); mintable = debtTokenValue * FIXED_POINT_SCALAR / alchemist.minimumCollateralization();
debtTokenValue = _convertToDebt(shares, startingYieldToken, startingParams.underlyingToken); mintable = debtTokenValue * FIXED_POINT_SCALAR / alchemist.minimumCollateralization();
26,543
16
// Generate UserOneChangeId for new user.
bytes32 _newUserOneChangeId = generateOneChangeId(_userAadharNumber);
bytes32 _newUserOneChangeId = generateOneChangeId(_userAadharNumber);
22,356
61
// loop through the collections token indexes and check additional requirements
uint64[] storage collection = collectionTokens[_collectionIndex]; require(collection.length > 0, "Collection has been cleared"); for (uint i = 0; i < collection.length; i++) { PixelCon storage pixelcon = pixelcons[collection[i]]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); }
uint64[] storage collection = collectionTokens[_collectionIndex]; require(collection.length > 0, "Collection has been cleared"); for (uint i = 0; i < collection.length; i++) { PixelCon storage pixelcon = pixelcons[collection[i]]; require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons"); }
30,339
0
// Mints LONG and SHORT position tokens/_buyer address Address of LONG position receiver/_seller address Address of SHORT position receiver/_derivativeHash bytes32 Hash of derivative (ticker) of position/_quantity uint256 Quantity of positions to mint
function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); }
function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); }
38,963
21
// Reward per token stored
uint256 public rewardPerTokenStored;
uint256 public rewardPerTokenStored;
61,384
89
// overriding PresaleisValidInvestment to add extra cap logic return true if beneficiary can buy at the moment
function isValidInvestment(address _beneficiary, uint256 _amount) public view returns (bool isValid) { bool withinCap = raisedFunds.add(_amount) <= maxCap; return super.isValidInvestment(_beneficiary, _amount) && withinCap; }
function isValidInvestment(address _beneficiary, uint256 _amount) public view returns (bool isValid) { bool withinCap = raisedFunds.add(_amount) <= maxCap; return super.isValidInvestment(_beneficiary, _amount) && withinCap; }
4,914
33
// This emits when schedules are removed /
event SchedulesRemoved(uint _cid, uint256[] _sids);
event SchedulesRemoved(uint _cid, uint256[] _sids);
18,710
188
// Add ether collateral sETH
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(sETH); uint ethIssuedDebt = etherCollateral().totalIssuedSynths().multiplyDecimalRound(ethRate); debt = debt.add(ethIssuedDebt); anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
(uint ethRate, bool ethRateInvalid) = exRates.rateAndInvalid(sETH); uint ethIssuedDebt = etherCollateral().totalIssuedSynths().multiplyDecimalRound(ethRate); debt = debt.add(ethIssuedDebt); anyRateIsInvalid = anyRateIsInvalid || ethRateInvalid;
3,360
334
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender); uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
this.validateAccountStakeBalance(msg.sender); uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
38,456
2
// whether an addres can contribute to that cap
mapping(address => bool) public canUpdate;
mapping(address => bool) public canUpdate;
34,489
43
// 1 - wait for the next month
uint64 oneMonth = lastWithdrawTime + 30 days; require(uint(now) >= oneMonth);
uint64 oneMonth = lastWithdrawTime + 30 days; require(uint(now) >= oneMonth);
57,306
14
// INTERACTIONS: pass off to _withdrawToken for transfers
_withdrawToken(token, balance);
_withdrawToken(token, balance);
38,498
74
// {See ICreatorCore-royaltyInfo}. /
function royaltyInfo(uint256 tokenId, uint256 value) external view virtual override returns (address, uint256) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); }
function royaltyInfo(uint256 tokenId, uint256 value) external view virtual override returns (address, uint256) { require(_exists(tokenId), "Nonexistent token"); return _getRoyaltyInfo(tokenId, value); }
15,654
79
// import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
contract FirstContract is ERC20Pausable, ERC20Mintable, ERC20Burnable { string public constant name = "Hannan Chain"; string public constant symbol = "AHB"; uint8 public constant decimals = 2; // uint256 public _totalSupply = 0; uint256 public totalSupply = 1000000; constructor () public { } }
contract FirstContract is ERC20Pausable, ERC20Mintable, ERC20Burnable { string public constant name = "Hannan Chain"; string public constant symbol = "AHB"; uint8 public constant decimals = 2; // uint256 public _totalSupply = 0; uint256 public totalSupply = 1000000; constructor () public { } }
37,352
462
// solium-disable-next-line security/no-block-members
uint _now = now; if ((proposal.state == ProposalState.QuietEndingPeriod) || ((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) {
uint _now = now; if ((proposal.state == ProposalState.QuietEndingPeriod) || ((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) {
35,532
11
// USER FUNCTIONS/Create tokens when funding is active./By using this function you accept the terms of DXF/Required state: Funding Active/State transition: -> Funding Success (only if cap reached)
function acceptTermsAndJoinDXF() payable external
function acceptTermsAndJoinDXF() payable external
3,797
6
// 竞标函数 不需要入参,因为竞标人地址和出价都在msg中
function bid() external payable { // 拍卖结束不能接受竞标 if (block.timestamp > auctionEndTime) { revert AuctionAlreadyEnded(); } // 竞标价需要比当前最高价高 if (msg.value <= highestBid) { revert BidNotHighEnough(highestBid); } // 最高价不为0,代表之前已发生过竞标 // 当程序再次走到这里,意味着最新的出价一定比之前的最高价要高 // 即之前的出价最高者,马上被替代,那么他的钱应当被累加到可赎回的数量上 // 而当最价格为0,意味着本函数第一次被调用,不需要进行赎回数量的累加操作 if (highestBid != 0) { // 这里的 highestBidder 依然是之前的最高者 pendingReturns[highestBidder] += highestBid; } // 累加可赎回数量之后,这里再更改最价格信息 highestBidder = msg.sender; highestBid = msg.value; emit HighestBidIncreased(msg.sender, msg.value); }
function bid() external payable { // 拍卖结束不能接受竞标 if (block.timestamp > auctionEndTime) { revert AuctionAlreadyEnded(); } // 竞标价需要比当前最高价高 if (msg.value <= highestBid) { revert BidNotHighEnough(highestBid); } // 最高价不为0,代表之前已发生过竞标 // 当程序再次走到这里,意味着最新的出价一定比之前的最高价要高 // 即之前的出价最高者,马上被替代,那么他的钱应当被累加到可赎回的数量上 // 而当最价格为0,意味着本函数第一次被调用,不需要进行赎回数量的累加操作 if (highestBid != 0) { // 这里的 highestBidder 依然是之前的最高者 pendingReturns[highestBidder] += highestBid; } // 累加可赎回数量之后,这里再更改最价格信息 highestBidder = msg.sender; highestBid = msg.value; emit HighestBidIncreased(msg.sender, msg.value); }
22,430
40
// Pay validators
for (uint i = 0; i < model.validators.length; i++) { address payable validator = address(uint160(model.validators[i])); executePayForValidation(modelId, validator); }
for (uint i = 0; i < model.validators.length; i++) { address payable validator = address(uint160(model.validators[i])); executePayForValidation(modelId, validator); }
1,960
39
// add stake token to staking pool requires the token to be approved for transfer we assume that (our) stake token is not malicious, so no special checks _amount of token to be staked /
function _stake(uint256 _amount) internal returns (uint256) { require(_amount > 0, "stake amount must be > 0"); User storage user = _updateRewards(msg.sender); // update rewards and return reference to user user.stakeAmount = toUint160(user.stakeAmount + _amount); tokenTotalStaked += _amount; user.unlockTime = toUint48(block.timestamp + lockTimePeriod); // using SafeERC20 for IERC20 => will revert in case of error IERC20(stakingToken).safeTransferFrom(msg.sender, address(this), _amount); emit Stake(msg.sender, _amount, toUint48(block.timestamp)); // = user.stakeTime return _amount; }
function _stake(uint256 _amount) internal returns (uint256) { require(_amount > 0, "stake amount must be > 0"); User storage user = _updateRewards(msg.sender); // update rewards and return reference to user user.stakeAmount = toUint160(user.stakeAmount + _amount); tokenTotalStaked += _amount; user.unlockTime = toUint48(block.timestamp + lockTimePeriod); // using SafeERC20 for IERC20 => will revert in case of error IERC20(stakingToken).safeTransferFrom(msg.sender, address(this), _amount); emit Stake(msg.sender, _amount, toUint48(block.timestamp)); // = user.stakeTime return _amount; }
47,995
9
// create new sale
Sale memory newSale = Sale(msg.sender, _erc1155, _tokenId, _amount, _tokenWant, _pricePerUnit); sales[newSaleId] = newSale; emit NewSale(msg.sender, _erc1155, _tokenId, _amount, _tokenWant, _pricePerUnit, newSaleId); newSaleId = newSaleId + 1;
Sale memory newSale = Sale(msg.sender, _erc1155, _tokenId, _amount, _tokenWant, _pricePerUnit); sales[newSaleId] = newSale; emit NewSale(msg.sender, _erc1155, _tokenId, _amount, _tokenWant, _pricePerUnit, newSaleId); newSaleId = newSaleId + 1;
34,320
15
// binance
constructor() VRFConsumerBase( 0xa555fC018435bef5A13C6c6870a9d4C11DEC329C, // VRF Coordinator 0x84b9B910527Ad5C03A9Ca831909E21e236EA7b06 // LINK Token ) { MIN_BET = 0.01 ether; MAX_BET = 2 ether; HOUSE_EDGE_MINIMUM_AMOUNT = 0.003 ether; keyHash = 0xcaf3c3727e033261d383b315559476f48034c13b18f8cafed4d871abe5049186;
constructor() VRFConsumerBase( 0xa555fC018435bef5A13C6c6870a9d4C11DEC329C, // VRF Coordinator 0x84b9B910527Ad5C03A9Ca831909E21e236EA7b06 // LINK Token ) { MIN_BET = 0.01 ether; MAX_BET = 2 ether; HOUSE_EDGE_MINIMUM_AMOUNT = 0.003 ether; keyHash = 0xcaf3c3727e033261d383b315559476f48034c13b18f8cafed4d871abe5049186;
9,191
11
// NMT
giftContract[_nmtContractAddress]=-1;
giftContract[_nmtContractAddress]=-1;
22,432
125
// Date and time are correct
require(now <= _startTime); require(_startTime < _endTime); startTime = _startTime; endTime = _endTime;
require(now <= _startTime); require(_startTime < _endTime); startTime = _startTime; endTime = _endTime;
32,553
8
// Cancel an already published order registry - address of the erc721 registry assetId - ID of the published NFT priceInWei - Price in Wei for the supported coin. /
function createOrder(address registry, uint256 assetId, uint256 priceInWei) public whenNotPaused { IERC721Base dar = IERC721Base(registry); address assetOwner = dar.ownerOf(assetId); require(msg.sender == assetOwner); require(dar.isAuthorized(address(this), assetId)); require(priceInWei > 0); bytes32 auctionId = keccak256(registry, assetId); auctionsById[auctionId] = Auction({ assetId: assetId, registry: registry, seller: assetOwner, price: priceInWei }); // Check if there's a publication fee and // transfer the amount to marketplace owner. if (publicationFeeInWei > 0) { owner.transfer(publicationFeeInWei); } totalAuctions++; emit AuctionCreated(auctionId, registry, assetId, assetOwner, priceInWei); }
function createOrder(address registry, uint256 assetId, uint256 priceInWei) public whenNotPaused { IERC721Base dar = IERC721Base(registry); address assetOwner = dar.ownerOf(assetId); require(msg.sender == assetOwner); require(dar.isAuthorized(address(this), assetId)); require(priceInWei > 0); bytes32 auctionId = keccak256(registry, assetId); auctionsById[auctionId] = Auction({ assetId: assetId, registry: registry, seller: assetOwner, price: priceInWei }); // Check if there's a publication fee and // transfer the amount to marketplace owner. if (publicationFeeInWei > 0) { owner.transfer(publicationFeeInWei); } totalAuctions++; emit AuctionCreated(auctionId, registry, assetId, assetOwner, priceInWei); }
37,421
3
// Get number of forwarders created
uint public forwarders_count = 0;
uint public forwarders_count = 0;
18,119
6
// Total erc20 token ever supplied to this stream by claim token address
function streamTotalSupply(address claimToken) external view returns (uint256);
function streamTotalSupply(address claimToken) external view returns (uint256);
22,256
22
// By default wallet == owner
function setWallet(address _wallet) public onlyOwner { wallet = _wallet; }
function setWallet(address _wallet) public onlyOwner { wallet = _wallet; }
35,512
26
// Restore the previous memory.
mstore(s, sLength) mstore(sub(s, 0x20), m1) mstore(sub(s, 0x40), m2) mstore(sub(s, 0x60), m3)
mstore(s, sLength) mstore(sub(s, 0x20), m1) mstore(sub(s, 0x40), m2) mstore(sub(s, 0x60), m3)
40,064
329
// ========== VIEWS ========== / Returns dollar value of collateral held in this dusd pool
function collatDollarBalance() public view returns (uint256) { uint256 eth_usd_price = dUSD.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); }
function collatDollarBalance() public view returns (uint256) { uint256 eth_usd_price = dUSD.eth_usd_price(); uint256 eth_collat_price = collatEthOracle.consult(weth_address, (PRICE_PRECISION * (10 ** missing_decimals))); uint256 collat_usd_price = eth_usd_price.mul(PRICE_PRECISION).div(eth_collat_price); return (collateral_token.balanceOf(address(this)).sub(unclaimedPoolCollateral)).mul(10 ** missing_decimals).mul(collat_usd_price).div(PRICE_PRECISION); //.mul(getCollateralPrice()).div(1e6); }
23,484
0
// This keeps track of allowed minters of token
mapping (address => bool) public minters;
mapping (address => bool) public minters;
9,588
19
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20) cc := add(cc, 0x20)
mc := add(mc, 0x20) cc := add(cc, 0x20)
5,508
30
// Referral Program
function setReferer(address referer) external returns (bool) { require(refererOf[msg.sender] != address(0), "You had set referer already."); refererOf[msg.sender] = referer; return true; }
function setReferer(address referer) external returns (bool) { require(refererOf[msg.sender] != address(0), "You had set referer already."); refererOf[msg.sender] = referer; return true; }
38,712
132
// Creates a Chainlink request for each oracle in the oracles array. This example does not include request parameters. Reference any documentationassociated with the Job IDs used to determine the required parameters per-request. /
function requestRateUpdate() external ensureAuthorizedRequester()
function requestRateUpdate() external ensureAuthorizedRequester()
8,665
309
// Snake
USDC.transfer( 0xce1559448e21981911fAC70D4eC0C02cA1EFF39C, yearlyToMonthlyUSD(28800, 1) ); uint256 usdcBalance = USDC.balanceOf(address(this)); USDC.approve(address(yUSDC), usdcBalance); yUSDC.deposit(usdcBalance, RESERVES);
USDC.transfer( 0xce1559448e21981911fAC70D4eC0C02cA1EFF39C, yearlyToMonthlyUSD(28800, 1) ); uint256 usdcBalance = USDC.balanceOf(address(this)); USDC.approve(address(yUSDC), usdcBalance); yUSDC.deposit(usdcBalance, RESERVES);
37,810
86
// Calculate 5% fee for PartyDAONOTE: Remove this fee causes a critical vulnerabilityallowing anyone to exploit a PartyBid via price manipulation.See Security Review in README for more info.return _fee 5% of the given amount /
function _getFee(uint256 _amount) internal pure returns (uint256 _fee) { _fee = (_amount * FEE_PERCENT) / 100; }
function _getFee(uint256 _amount) internal pure returns (uint256 _fee) { _fee = (_amount * FEE_PERCENT) / 100; }
23,196
29
// execute raw order on registered marketplace solhint-disable-next-line avoid-low-level-calls
(bool success, ) = marketplace.call(tradeData); if (!success) { revert Errors.MartketplaceFailedToTrade(); }
(bool success, ) = marketplace.call(tradeData); if (!success) { revert Errors.MartketplaceFailedToTrade(); }
30,116
52
// Expect: 138 +
$$(sum(concat(VALS, [10]))) +
$$(sum(concat(VALS, [10]))) +
54,690
7
// Deploy RaisingToken smart contract, issue one token and sell it tomessage sender for ether provided. /
function RaisingToken () public payable { // Make sure some ether was provided require (msg.value > 0); // Issue one token... totalSupply = 1; // ... and give it to message sender balanceOf [msg.sender] = 1; // Log token creation Transfer (address (0), msg.sender, 1); }
function RaisingToken () public payable { // Make sure some ether was provided require (msg.value > 0); // Issue one token... totalSupply = 1; // ... and give it to message sender balanceOf [msg.sender] = 1; // Log token creation Transfer (address (0), msg.sender, 1); }
3,419
31
// Calculates all the token available for withdrawal, belonging to a knight.knightAddress belonging to that knight.totalClaimableTokensTotal claimable tokens available for withdrawal from the vesting contract. /
function calculateAllPendingTokens( address knight
function calculateAllPendingTokens( address knight
30,830
11
// The sender adds to reserves. addAmount The amount fo underlying token to add as reservesreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount, false); }
function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount, false); }
7,220
1
// Properties // Events // Modifiers // Constructor // /
constructor(address storageAddress, address aCompoundSettings) public PostActionBase(storageAddress)
constructor(address storageAddress, address aCompoundSettings) public PostActionBase(storageAddress)
51,609
113
// Conflict handling implementation. Stores game data and timestamp if gameis active. If server has already marked conflict for game session the conflictresolution contract is used (compare conflictRes). _roundId Round id of bet. _gameType Game type of bet. _num Number of bet. _value Value of bet. _balance Balance before this bet. _playerHash Hash of player's seed for this bet. _playerSeed Player's seed for this bet. _gameId game Game session id. _playerAddress Player's address. /
function playerEndGameConflictImpl( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _playerHash, bytes32 _playerSeed, uint _gameId, address _playerAddress
function playerEndGameConflictImpl( uint32 _roundId, uint8 _gameType, uint16 _num, uint _value, int _balance, bytes32 _playerHash, bytes32 _playerSeed, uint _gameId, address _playerAddress
35,226
6
// ensure that only HomeFi admins can arbitrate disputes
require(homeFi.admin() == _msgSender(), "Dispute::!Admin"); _;
require(homeFi.admin() == _msgSender(), "Dispute::!Admin"); _;
29,565
10
// ICreatorNFT.ModelInfo memory modelInfo = creatorNFT().modelInfo( _tokenId );
if (factory().getShareNFTAddr(_tokenId) != address(0)) { address _shareNFTAddr = factory().getShareNFTAddr(_tokenId); IShareERC721InDetail _shareNFT = IShareERC721InDetail(_shareNFTAddr); IERC721Metadata _shareMetadataNFT = IERC721Metadata(_shareNFTAddr); return MyCreatorNFTCollection( _tokenId, // token id creatorNFT().modelIdByTokenId(_tokenId), // model id
if (factory().getShareNFTAddr(_tokenId) != address(0)) { address _shareNFTAddr = factory().getShareNFTAddr(_tokenId); IShareERC721InDetail _shareNFT = IShareERC721InDetail(_shareNFTAddr); IERC721Metadata _shareMetadataNFT = IERC721Metadata(_shareNFTAddr); return MyCreatorNFTCollection( _tokenId, // token id creatorNFT().modelIdByTokenId(_tokenId), // model id
22,611
117
// HollywoodToken with Governance.
contract HollywoodToken is ERC20("HollywoodToken", "HOLLY"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "HOLLY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HOLLY::delegateBySig: invalid nonce"); require(now <= expiry, "HOLLY::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HOLLY::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying HOLLYs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "HOLLY::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract HollywoodToken is ERC20("HollywoodToken", "HOLLY"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "HOLLY::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HOLLY::delegateBySig: invalid nonce"); require(now <= expiry, "HOLLY::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "HOLLY::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying HOLLYs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "HOLLY::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
24,266
231
// return the price as number of tokens released for each etherreturn amount in sphi for 1 ether /
function price() public view returns(uint) { return getTokenAmount(1 ether); }
function price() public view returns(uint) { return getTokenAmount(1 ether); }
17,795
56
// Oracle returns prices as 6 decimals, so multiply by claimable amount and divide by token decimals
return (claimableProfits() * underlyingPrice) / (10**yVault.decimals());
return (claimableProfits() * underlyingPrice) / (10**yVault.decimals());
8,809
12
// Wrong Send Various Tokens
function returnVariousTokenFromContract(address tokenAddress) public returns (bool success) { require(msg.sender == owner); ERC20 tempToken = ERC20(tokenAddress); tempToken.transfer(msg.sender, tempToken.balanceOf(address(this))); return true; }
function returnVariousTokenFromContract(address tokenAddress) public returns (bool success) { require(msg.sender == owner); ERC20 tempToken = ERC20(tokenAddress); tempToken.transfer(msg.sender, tempToken.balanceOf(address(this))); return true; }
24,401
5
// ==========Events========== //Emitted when a new category is created. //Emitted when a category is sorted. //Emitted when a token is added to a category. // ==========Storage========== / Number of categories that exist.
uint256 public categoryIndex;
uint256 public categoryIndex;
8,964
62
// Get the account balances of each team, NOT the in game balance.
uint256 htpBalance = 0; for (index = 0; index < theMatch.homeTeamPlayersCount; index++) { htpBalance += theMatch.homeTeamPlayers[index].account.balance; }
uint256 htpBalance = 0; for (index = 0; index < theMatch.homeTeamPlayersCount; index++) { htpBalance += theMatch.homeTeamPlayers[index].account.balance; }
22,583
94
// Building an array without duplicates
bytes32[] memory dataFeedIdsWithoutDuplicates = new bytes32[](dataFeedIdsWithDuplicates.length); bool alreadyIncluded; uint256 uniqueDataFeedIdsCount = 0; for (uint256 indexWithDup = 0; indexWithDup < dataFeedIdsWithDuplicates.length; indexWithDup++) {
bytes32[] memory dataFeedIdsWithoutDuplicates = new bytes32[](dataFeedIdsWithDuplicates.length); bool alreadyIncluded; uint256 uniqueDataFeedIdsCount = 0; for (uint256 indexWithDup = 0; indexWithDup < dataFeedIdsWithDuplicates.length; indexWithDup++) {
33,093
25
// View function to see pending HBTs on frontend.查询接口,查询当前阶段指定地址_user在_pid池中赚取的YMIparam:_pid,pool id (即通过pool id 可以找到对应池的的地址)param:_user, 用户地址
function pendingHbt(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHbtPerShare = pool.accHbtPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 hbtReward = multiplier.mul(hbtPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHbtPerShare = accHbtPerShare.add(hbtReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHbtPerShare).div(1e12).sub(user.rewardDebt); }
function pendingHbt(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHbtPerShare = pool.accHbtPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 hbtReward = multiplier.mul(hbtPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accHbtPerShare = accHbtPerShare.add(hbtReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accHbtPerShare).div(1e12).sub(user.rewardDebt); }
7,793
24
// royaltyInfo function to get royalty proxy contract address and percentage of royalties _salePrice contains the token's pricereturn obejct (address, uint256) with royalty address and amount to send/
function royaltyInfo( uint256, uint256 _salePrice
function royaltyInfo( uint256, uint256 _salePrice
17,082
28
// ambassador F
ambassadors_[0x11756491343b18cb3db47e9734f20096b4f64234] = true;
ambassadors_[0x11756491343b18cb3db47e9734f20096b4f64234] = true;
77,676
13
// emit throwTotalAmount(totalAmount);
return ords;
return ords;
31,540
36
// Approve `spender` to transfer up to `amount` from `src` This will overwrite the approval amount for `spender` spender The address of the account which may transfer tokens amount The number of tokens that are approved (-1 means infinite)return Whether or not the approval succeeded /
function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; }
function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; }
5,390
21
// God may set the ETH exchange contract's address/_ethExchangeContract The new address
function godSetEthExchangeContract(address _ethExchangeContract) public onlyGod
function godSetEthExchangeContract(address _ethExchangeContract) public onlyGod
39,774
140
// Returns a new slice containing the same data as the current slice. self The slice to copy.return A new slice containing the same data as `self`. /
function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); }
function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); }
12,593
55
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
19,185
26
// Return OracleHub Module address from the Nexusreturn Address of the OracleHub Module contract /
function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); }
function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); }
26,534
29
// The hint was successful --> we find a better allocation than the current one
if (_totalApr < estimatedAprHint) { uint256 deltaWithdraw; for (uint256 i; i < lendersListLength; ++i) { if (lenderAdjustedAmounts[i] < 0) { deltaWithdraw += uint256(-lenderAdjustedAmounts[i]) - lendersList[i].withdraw(uint256(-lenderAdjustedAmounts[i])); }
if (_totalApr < estimatedAprHint) { uint256 deltaWithdraw; for (uint256 i; i < lendersListLength; ++i) { if (lenderAdjustedAmounts[i] < 0) { deltaWithdraw += uint256(-lenderAdjustedAmounts[i]) - lendersList[i].withdraw(uint256(-lenderAdjustedAmounts[i])); }
17,958
6
// Returns the address of the current owner. /
function owner() public view returns (address) { return _owner; }
function owner() public view returns (address) { return _owner; }
146
66
// Allow the user to withdraw remaining balance upon connection termination
function withdrawBalance() internal { uint amount = pendingWithdrawl[msg.sender]; pendingWithdrawl[msg.sender] = 0; msg.sender.transfer(amount); }
function withdrawBalance() internal { uint amount = pendingWithdrawl[msg.sender]; pendingWithdrawl[msg.sender] = 0; msg.sender.transfer(amount); }
48,054
110
// mapping that returns true if the strategy is set as a vault.
function strategyExists(IStrategy strategy) external view returns(bool);
function strategyExists(IStrategy strategy) external view returns(bool);
45,418
44
// delete lockup type
delete(lockups[_lockupName]); uint256 i = 0; for (i = 0; i < lockupArray.length; i++) { if (lockupArray[i] == _lockupName) { break; }
delete(lockups[_lockupName]); uint256 i = 0; for (i = 0; i < lockupArray.length; i++) { if (lockupArray[i] == _lockupName) { break; }
26,477
25
// All interfaces need to support `supportsInterface`. This functionchecks if the provided interface ID is supported.interfaceId The interface ID to check. return True if the interface is supported (AccessControlEnumerable,ERC721, ERC721Enumerable), false otherwise. /
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721A) returns (bool)
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerable, ERC721A) returns (bool)
36,974
11
// add an admin _adminAddress the address of the admin to be added /
function addAdmin(address _adminAddress) external onlyOwner { adminMap[_adminAddress] = Admin(numCurrentAdmins, _adminAddress, true); numCurrentAdmins++; }
function addAdmin(address _adminAddress) external onlyOwner { adminMap[_adminAddress] = Admin(numCurrentAdmins, _adminAddress, true); numCurrentAdmins++; }
3,102
41
// Calculates the square root of x, rounding down./Uses the Babylonian method https:en.wikipedia.org/wiki/Methods_of_computing_square_rootsBabylonian_method.// Caveats:/ - This function does not work with fixed-point numbers.//x The uint256 number for which to calculate the square root./ return result The result as an uint256.
function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } }
function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } }
53,725
177
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
_prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
2,474
7
// Returns the amount of tokens owned by `account`. /
function balanceOf(address account) external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
37,144
81
// /
function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); }
function assetToKashi(IKashiBridge kashiPair, address to, uint256 amount) external returns (uint256 fraction) { IERC20 asset = kashiPair.asset(); asset.safeTransferFrom(msg.sender, address(bento), amount); IBentoBridge(bento).deposit(asset, address(bento), address(kashiPair), amount, 0); fraction = kashiPair.addAsset(to, true, amount); }
27,547
200
// IProxy - Helper interface to access masterCopy of the Proxy on-chain/Richard Meissner - <[email protected]>
interface IProxy { function masterCopy() external view returns (address); }
interface IProxy { function masterCopy() external view returns (address); }
71,164
151
// Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender);
24,956
1
// Presale
uint256 public whitelistAllowance = 5; uint256 public whitelistCost = 0.015 ether; mapping (address => uint256) public presaleWhitelist;
uint256 public whitelistAllowance = 5; uint256 public whitelistCost = 0.015 ether; mapping (address => uint256) public presaleWhitelist;
21,008
60
// Validate an ExchangeSettings struct when adding or updating an exchange. Does not validate that twapMaxTradeSize < incentivizedMaxTradeSize sinceit may be useful to disable exchanges for ripcord by setting incentivizedMaxTradeSize to 0. /
function _validateExchangeSettings(ExchangeSettings memory _settings) internal pure { require(_settings.twapMaxTradeSize != 0, "Max TWAP trade size must not be 0"); }
function _validateExchangeSettings(ExchangeSettings memory _settings) internal pure { require(_settings.twapMaxTradeSize != 0, "Max TWAP trade size must not be 0"); }
15,352
42
// Updates BatchNFT after Serialnumber has been verified/ Data is usually inserted by the user (NFT owner) via the UI/tokenId the Batch-NFT/serialNumber the serial number received from the registry/credit cancellation/quantity quantity in tCO2e/uri optional tokenURI with additional information
function updateBatchWithData( uint256 tokenId, string memory serialNumber, uint256 quantity, string memory uri
function updateBatchWithData( uint256 tokenId, string memory serialNumber, uint256 quantity, string memory uri
16,077
3
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) { return prices[asset]; }
function assetPrices(address asset) external view returns (uint) { return prices[asset]; }
35,273
52
// This ensure that only the two whitelisted auction contract are allowed to send funds to this contract. /
receive() external payable { require(msg.sender == address(saleAuction) || msg.sender == address(siringAuction) , "You cannot send funds here."); }
receive() external payable { require(msg.sender == address(saleAuction) || msg.sender == address(siringAuction) , "You cannot send funds here."); }
51,180
28
// Deposits the want token into Curve in exchange for lp token. _want Amount of want token to deposit. _minAmount Minimum LP token to receive. /
function _depositToCurve(uint256 _want, uint256 _minAmount) internal virtual {} /** * @dev Withdraws the want token from Curve by burning lp token. * @param _lp Amount of LP token to burn. * @param _minAmount Minimum want token to receive. */ function _withdrawFromCurve(uint256 _lp, uint256 _minAmount) internal virtual {} }
function _depositToCurve(uint256 _want, uint256 _minAmount) internal virtual {} /** * @dev Withdraws the want token from Curve by burning lp token. * @param _lp Amount of LP token to burn. * @param _minAmount Minimum want token to receive. */ function _withdrawFromCurve(uint256 _lp, uint256 _minAmount) internal virtual {} }
17,473
5
// multicall implemenation to check ERC721 balances of multiple addresses in a single call/nft address of ERC721 contract/addresses array of addresses to check/ return balances array of ERC721 balances
function getERC721Balance(IERC721 nft, address[] calldata addresses) external view returns (uint256[] memory balances)
function getERC721Balance(IERC721 nft, address[] calldata addresses) external view returns (uint256[] memory balances)
18,696
723
// Allows wallet to redeem KEEPER
function redeem( uint _amount ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); KEEPER.safeTransfer(msg.sender, _amount); terms[ msg.sender ].claimed = info.claimed.add( _amount ); totalRedeemed = totalRedeemed.add(_amount); emit KeeperRedeemed(msg.sender, _amount); return true; }
function redeem( uint _amount ) external returns ( bool ) { Term memory info = terms[ msg.sender ]; require( redeemable( info ) >= _amount, 'Not enough vested' ); KEEPER.safeTransfer(msg.sender, _amount); terms[ msg.sender ].claimed = info.claimed.add( _amount ); totalRedeemed = totalRedeemed.add(_amount); emit KeeperRedeemed(msg.sender, _amount); return true; }
32,928
80
// send 1 wei - external call to an untrusted contract/ if (!payable(playerTempAddress[requestId]).send(1)) { send 1 wei / if send failed let player withdraw via playerWithdrawPendingTransactions / playerPendingWithdrawals[playerTempAddress[requestId]] = ( playerPendingWithdrawals[playerTempAddress[requestId]] + 1 ); }
return;
return;
19,658
7
// from uniswap SDK helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeApprove: approve failed"); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed"); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); } }
library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeApprove: approve failed"); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed"); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed"); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, "TransferHelper::safeTransferETH: ETH transfer failed"); } }
36,430