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
22
// buy 11 of each item
for (uint8 i = 0; i < 9; i++) { for (uint8 j = 0; j < 11; j++) { CornFarm(shop[i]).buyObject(this); }
for (uint8 i = 0; i < 9; i++) { for (uint8 j = 0; j < 11; j++) { CornFarm(shop[i]).buyObject(this); }
36,745
10
// 项目方
uint256 platReward = feeAmount.mul(platformFee).div(persent);
uint256 platReward = feeAmount.mul(platformFee).div(persent);
40,170
0
// map token ID to
uint256 buyNowPrice; uint256 amountSupply; uint256 amount; uint256 auctionEnd; address nftSeller; address whitelistedBuyer; //The seller can specify a whitelisted address for a sale (this is effectively a direct sale). address ERC20Token; // The seller can specify an ERC20 token that can be used to bid or purchase the NFT. address recipient;
uint256 buyNowPrice; uint256 amountSupply; uint256 amount; uint256 auctionEnd; address nftSeller; address whitelistedBuyer; //The seller can specify a whitelisted address for a sale (this is effectively a direct sale). address ERC20Token; // The seller can specify an ERC20 token that can be used to bid or purchase the NFT. address recipient;
27,493
2
// Mapping from owner to token ids
mapping(address => uint256[]) private _indexedTokenIds;
mapping(address => uint256[]) private _indexedTokenIds;
3,495
18
// amount = vestingAmount(state.total, 0, TOTAL_LOCK_SECONDS_STRATEGY, 0); without first release
amount = vestingAmountFunding(state.total, FIRST_RELEASE_PERCENT_STRATEGY, TOTAL_LOCK_SECONDS_STRATEGY, FIRST_LOCK_SECONDS_FUND); // with first release
amount = vestingAmountFunding(state.total, FIRST_RELEASE_PERCENT_STRATEGY, TOTAL_LOCK_SECONDS_STRATEGY, FIRST_LOCK_SECONDS_FUND); // with first release
48,555
2
// allow for third party metatx account to make transactions through this contract like an identity but make sure the owner has whitelisted the tx
mapping(address => bool) public whitelist;
mapping(address => bool) public whitelist;
34,703
160
// Revert immediately if x2 would overflow. Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) { revert(0, 0) }
if shr(128, x) { revert(0, 0) }
6,838
76
// Creates a campaign for a certain package name with a defined price and budget/
function createCampaign ( string packageName, uint[3] countries, uint[] vercodes, uint price, uint budget, uint startDate, uint endDate)
function createCampaign ( string packageName, uint[3] countries, uint[] vercodes, uint price, uint budget, uint startDate, uint endDate)
29,833
801
// Verify all of the test logs.
for (uint256 i = 0; i < testLogs.length; i++) { // Verify the logged data. verifyTestLog( testLogs[i], expectedAvailableBalance, // expectedAvailableBalance i % 2 == 0 ? makerAddress1 : makerAddress2, // expectedMakerAddress address(this), // expectedPayerAddress expectedProtocolFeePaid // expectedProtocolFeePaid ); // Set the expected available balance for the next log. expectedAvailableBalance = expectedAvailableBalance >= expectedProtocolFeePaid ? expectedAvailableBalance - expectedProtocolFeePaid : expectedAvailableBalance; }
for (uint256 i = 0; i < testLogs.length; i++) { // Verify the logged data. verifyTestLog( testLogs[i], expectedAvailableBalance, // expectedAvailableBalance i % 2 == 0 ? makerAddress1 : makerAddress2, // expectedMakerAddress address(this), // expectedPayerAddress expectedProtocolFeePaid // expectedProtocolFeePaid ); // Set the expected available balance for the next log. expectedAvailableBalance = expectedAvailableBalance >= expectedProtocolFeePaid ? expectedAvailableBalance - expectedProtocolFeePaid : expectedAvailableBalance; }
12,555
41
// use interface that not return value (USDT case)
Ierc20(token).transfer(owner(), val);
Ierc20(token).transfer(owner(), val);
6,030
20
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore( 0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3) ) instance := create(0, 0x09, 0x37)
mstore( 0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3) ) instance := create(0, 0x09, 0x37)
24,667
34
// Constructor function to initialize the initial supply of token to the creator of the contract /
constructor(address wallet) public
constructor(address wallet) public
37,363
36
// Retrieves the distribution fee percentagesreturn The owner, level, and creator fee percentages /
function getDistributionFeePercentage() external view override returns (uint256, uint256, uint256)
function getDistributionFeePercentage() external view override returns (uint256, uint256, uint256)
36,298
53
// refresh the data of roundInfo and roundAddressToBid
roundInfo[round].biddersThisRound.push(msg.sender); roundAddressToBid[msg.sender][round] = Bid({ blindedBid: _blindedBid, escrow: _escrow, trueValue: 0, alreadyRevealed: false, seasonable: false });
roundInfo[round].biddersThisRound.push(msg.sender); roundAddressToBid[msg.sender][round] = Bid({ blindedBid: _blindedBid, escrow: _escrow, trueValue: 0, alreadyRevealed: false, seasonable: false });
23,421
276
// Emergency: can be changed to account for large fluctuations in ETH price
function emergencyChangePrice(uint256 newPrice) public onlyOwner { pawZeesPrice = newPrice; }
function emergencyChangePrice(uint256 newPrice) public onlyOwner { pawZeesPrice = newPrice; }
39,206
49
// token purchase function _beneficiary Address performing the token purchase /
function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); bool isPresale = block.timestamp >= PRESALE_OPENING_TIME && block.timestamp <= PRESALE_CLOSING_TIME && presaleWeiRaised.add(weiAmount) <= PRESALE_WEI_CAP; bool isCrowdsale = block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME && presaleGoalReached() && crowdsaleWeiRaised.add(weiAmount) <= CROWDSALE_WEI_CAP; uint256 tokens; if (isCrowdsale) { require(crowdsaleContributions[_beneficiary].add(weiAmount) <= getCrowdsaleUserCap()); if (weiAmount > CROWDSALE_UNVERIFIED_USER_CAP) require(verifiedList[_beneficiary]); // calculate token amount to be created tokens = _getCrowdsaleTokenAmount(weiAmount); require(tokens != 0); // update state crowdsaleWeiRaised = crowdsaleWeiRaised.add(weiAmount); } else if (isPresale) { require(presaleWhitelist[_beneficiary]); // calculate token amount to be created tokens = weiAmount.mul(PRESALE_RATE).div(1 ether); require(tokens != 0); // update state presaleWeiRaised = presaleWeiRaised.add(weiAmount); } else { revert(); } _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); if (isCrowdsale) { crowdsaleContributions[_beneficiary] = crowdsaleContributions[_beneficiary].add(weiAmount); crowdsaleDeposited[_beneficiary] = crowdsaleDeposited[_beneficiary].add(msg.value); } else if (isPresale) { presaleDeposited[_beneficiary] = presaleDeposited[_beneficiary].add(msg.value); } }
function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; require(_beneficiary != address(0)); require(weiAmount != 0); bool isPresale = block.timestamp >= PRESALE_OPENING_TIME && block.timestamp <= PRESALE_CLOSING_TIME && presaleWeiRaised.add(weiAmount) <= PRESALE_WEI_CAP; bool isCrowdsale = block.timestamp >= CROWDSALE_OPENING_TIME && block.timestamp <= CROWDSALE_CLOSING_TIME && presaleGoalReached() && crowdsaleWeiRaised.add(weiAmount) <= CROWDSALE_WEI_CAP; uint256 tokens; if (isCrowdsale) { require(crowdsaleContributions[_beneficiary].add(weiAmount) <= getCrowdsaleUserCap()); if (weiAmount > CROWDSALE_UNVERIFIED_USER_CAP) require(verifiedList[_beneficiary]); // calculate token amount to be created tokens = _getCrowdsaleTokenAmount(weiAmount); require(tokens != 0); // update state crowdsaleWeiRaised = crowdsaleWeiRaised.add(weiAmount); } else if (isPresale) { require(presaleWhitelist[_beneficiary]); // calculate token amount to be created tokens = weiAmount.mul(PRESALE_RATE).div(1 ether); require(tokens != 0); // update state presaleWeiRaised = presaleWeiRaised.add(weiAmount); } else { revert(); } _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); if (isCrowdsale) { crowdsaleContributions[_beneficiary] = crowdsaleContributions[_beneficiary].add(weiAmount); crowdsaleDeposited[_beneficiary] = crowdsaleDeposited[_beneficiary].add(msg.value); } else if (isPresale) { presaleDeposited[_beneficiary] = presaleDeposited[_beneficiary].add(msg.value); } }
44,601
8
// this mock is used when only simple actions are required. no reserves are involved.
contract MockKyberNetwork { uint constant public REVERT_HINT = 123454321; mapping(bytes32=>uint) public pairRate; //rate in precision units. i.e. if rate is 10**18 its same as 1:1 uint constant PRECISION = 10 ** 18; ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); function() external payable {} function setPairRate(ERC20 src, ERC20 dest, uint rate) public { pairRate[keccak256(abi.encodePacked(src, dest))] = rate; } // @dev trade function with same prototype as KyberNetwork // will be used only to trade token to Ether, // will work only when set pair worked. function trade( ERC20 src, uint srcAmount, ERC20 dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { uint rate = pairRate[keccak256(abi.encodePacked(src, dest))]; walletId; require(rate > 0, "RATE_ZERO"); require(rate > minConversionRate, "RATE_TOO_LOW"); // require(dest == ETH_TOKEN_ADDRESS, "ONLY_ETH_SUPPORTED"); uint destAmount = srcAmount * rate / PRECISION; uint actualSrcAmount = srcAmount; if (destAmount > maxDestAmount) { destAmount = maxDestAmount; actualSrcAmount = maxDestAmount * PRECISION / rate; } require(src.transferFrom(msg.sender, address(this), actualSrcAmount), "TRANSFER_FAILED"); if(dest == ETH_TOKEN_ADDRESS) { destAddress.transfer(destAmount); } else { MockToken(address(dest)).mintTo(destAddress, destAmount); } return destAmount; } function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint expectedRate, uint slippageRate) { srcQty; expectedRate = pairRate[keccak256(abi.encodePacked(src, dest))]; slippageRate = expectedRate * 97 / 100; } function findBestRate(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) { srcAmount; require (srcAmount != REVERT_HINT); rate = pairRate[keccak256(abi.encodePacked(src, dest))]; return(0, rate); } function findBestRateOnlyPermission(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) { srcAmount; require (srcAmount != REVERT_HINT); rate = pairRate[keccak256(abi.encodePacked(src, dest))]; return(0, rate); } function searchBestRate(ERC20 src, ERC20 dest, uint srcAmount, bool usePermissionLess) public view returns(uint obsolete, uint rate) { srcAmount; usePermissionLess; rate = pairRate[keccak256(abi.encodePacked(src, dest))]; return(0, rate); } }
contract MockKyberNetwork { uint constant public REVERT_HINT = 123454321; mapping(bytes32=>uint) public pairRate; //rate in precision units. i.e. if rate is 10**18 its same as 1:1 uint constant PRECISION = 10 ** 18; ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); function() external payable {} function setPairRate(ERC20 src, ERC20 dest, uint rate) public { pairRate[keccak256(abi.encodePacked(src, dest))] = rate; } // @dev trade function with same prototype as KyberNetwork // will be used only to trade token to Ether, // will work only when set pair worked. function trade( ERC20 src, uint srcAmount, ERC20 dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId ) public payable returns(uint) { uint rate = pairRate[keccak256(abi.encodePacked(src, dest))]; walletId; require(rate > 0, "RATE_ZERO"); require(rate > minConversionRate, "RATE_TOO_LOW"); // require(dest == ETH_TOKEN_ADDRESS, "ONLY_ETH_SUPPORTED"); uint destAmount = srcAmount * rate / PRECISION; uint actualSrcAmount = srcAmount; if (destAmount > maxDestAmount) { destAmount = maxDestAmount; actualSrcAmount = maxDestAmount * PRECISION / rate; } require(src.transferFrom(msg.sender, address(this), actualSrcAmount), "TRANSFER_FAILED"); if(dest == ETH_TOKEN_ADDRESS) { destAddress.transfer(destAmount); } else { MockToken(address(dest)).mintTo(destAddress, destAmount); } return destAmount; } function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint expectedRate, uint slippageRate) { srcQty; expectedRate = pairRate[keccak256(abi.encodePacked(src, dest))]; slippageRate = expectedRate * 97 / 100; } function findBestRate(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) { srcAmount; require (srcAmount != REVERT_HINT); rate = pairRate[keccak256(abi.encodePacked(src, dest))]; return(0, rate); } function findBestRateOnlyPermission(ERC20 src, ERC20 dest, uint srcAmount) public view returns(uint obsolete, uint rate) { srcAmount; require (srcAmount != REVERT_HINT); rate = pairRate[keccak256(abi.encodePacked(src, dest))]; return(0, rate); } function searchBestRate(ERC20 src, ERC20 dest, uint srcAmount, bool usePermissionLess) public view returns(uint obsolete, uint rate) { srcAmount; usePermissionLess; rate = pairRate[keccak256(abi.encodePacked(src, dest))]; return(0, rate); } }
21,296
32
// sets the rewards settings requirements: - the caller must be the admin of the contract /
function setRewards( Rewards calldata newRewards
function setRewards( Rewards calldata newRewards
7,278
249
// number of tokens left to create
uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) {
uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) {
26,972
12
// transfers the current VALOR balance to the owner. the factory is not supposed to receive/hold VALOR, however in case of mistakenly sent tokens, the owner can pull these tokens and make it available to external wallets./
function withdraw() external onlyOwner{ uint256 balance = token.balanceOf(address(this)); require(balance > 0); require(token.transfer(owner, balance)); }
function withdraw() external onlyOwner{ uint256 balance = token.balanceOf(address(this)); require(balance > 0); require(token.transfer(owner, balance)); }
33,223
6
// Constructs the Testable contract. Called by child contracts. _timerAddress Contract that stores the current time in a testing environment.Must be set to 0x0 for production environments that use live time. /
constructor(address _timerAddress) internal { timerAddress = _timerAddress; }
constructor(address _timerAddress) internal { timerAddress = _timerAddress; }
4,356
3
// it will remove whitelisted user
// @param _contributor {address} of user to unwhitelist function removeFromWhiteList(address _user) external onlyOwner() returns (bool) { require(whiteList[_user] == true); whiteList[_user] = false; totalWhiteListed--; emit LogRemoveWhiteListed(_user); return true; }
// @param _contributor {address} of user to unwhitelist function removeFromWhiteList(address _user) external onlyOwner() returns (bool) { require(whiteList[_user] == true); whiteList[_user] = false; totalWhiteListed--; emit LogRemoveWhiteListed(_user); return true; }
17,727
10
// mother index
uint256 nextMotherIndex = ebibleIndexMax + 1; uint256 motherIndexMin = ebibleIndexMax + 1; uint256 motherIndexMax = ebibleIndexMax + 30;
uint256 nextMotherIndex = ebibleIndexMax + 1; uint256 motherIndexMin = ebibleIndexMax + 1; uint256 motherIndexMax = ebibleIndexMax + 30;
25,586
241
// If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0
if (twab.timestamp == 0) { index = 0; twab = _twabs[0]; }
if (twab.timestamp == 0) { index = 0; twab = _twabs[0]; }
69,855
12
// similar to take(), but with the block height joined to calculate return./for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interests./ return amount of interests and the block height.
function takeWithBlock() external view returns (uint, uint);
function takeWithBlock() external view returns (uint, uint);
28,974
942
// Checks If the proposal voting time is up and it's ready to closei.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!_proposalId Proposal id to which closing value is being checked/
function canCloseProposal(uint _proposalId) public view returns (uint)
function canCloseProposal(uint _proposalId) public view returns (uint)
2,315
5
// Team addresses for withdrawals
address public a1;
address public a1;
40,035
23
// Without position flags, the position 0x000000 would be treated as empty
flaggedLeafPosition[operator] = position.setFlag();
flaggedLeafPosition[operator] = position.setFlag();
19,089
5
// The min setable voting delay
uint256 public constant MIN_VOTING_DELAY = 0;
uint256 public constant MIN_VOTING_DELAY = 0;
34,535
3
// Returns the next initialized tick in tree to the right (gte) of the given tick or `MAX_TICK`/leafs The words with ticks/secondLayer The words with info about active leafs/treeRoot The word with info about active subtrees/tick The starting tick/ return nextTick The next initialized tick or `MAX_TICK`
function getNextTick( mapping(int16 => uint256) storage leafs, mapping(int16 => uint256) storage secondLayer, uint32 treeRoot, int24 tick
function getNextTick( mapping(int16 => uint256) storage leafs, mapping(int16 => uint256) storage secondLayer, uint32 treeRoot, int24 tick
24,343
138
// Exposes isInitialized bool var to child contracts with read-only access /
function _isInitialized() internal view returns (bool) { return isInitialized; }
function _isInitialized() internal view returns (bool) { return isInitialized; }
25,833
6
// 1 July 2019
} else if (unlockStep == 4 && now >= 1561939200) {
} else if (unlockStep == 4 && now >= 1561939200) {
41,675
2
// Mapping of all users
mapping(address => bytes32) public users;
mapping(address => bytes32) public users;
9,846
115
// Calculate token sell value.It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. /
function tokensToEthereum_(uint256 _tokens) internal view returns(uint256)
function tokensToEthereum_(uint256 _tokens) internal view returns(uint256)
2,960
455
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
9,980
34
// Gets all members' length/_memberRoleId Member role id/ return memberRoleData[_memberRoleId].memberAddress.length Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint);
function numberOfMembers(uint _memberRoleId) public view returns(uint);
53,928
127
// if sender is owner, but not keeper, keeper has to be this contract
|| (msg.sender != keeper && msg.sender == owner() && address(this) != keeper) ) { revert NotPermitted(); }
|| (msg.sender != keeper && msg.sender == owner() && address(this) != keeper) ) { revert NotPermitted(); }
18,832
169
// Emits events {DelegateChanged} and {DelegateVotesChanged}. /
function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); }
function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); }
293
47
// Allows the current owner to relinquish control of the contract. Renouncing to ownership will leave the contract without an owner.It will not be possible to call the functions with the `onlyOwner`modifier anymore. /
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); }
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); }
37,913
146
// aggregated_g1s = inner recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid;
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part); valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x); return valid;
7,693
127
// calculate the minConversionRate and maxDestAmount keeping in mind the fee
uint256 adaptedMinRate = minConversionRate.mul(spreadUnit).div(spreadUnit - spread); uint256 adaptedMaxDestAmount = maxDestAmount.mul(spreadUnit).div(spreadUnit - spread); uint256 destTradedAmount = doNetworkTrade(src, srcAmount, dest, adaptedMaxDestAmount, adaptedMinRate); uint256 notTraded = _myBalance(src); uint256 srcTradedAmount = srcAmount.sub(notTraded); require(srcTradedAmount > 0, "no traded tokens"); require( _myBalance(dest) >= destTradedAmount, "No enough dest tokens after trade"
uint256 adaptedMinRate = minConversionRate.mul(spreadUnit).div(spreadUnit - spread); uint256 adaptedMaxDestAmount = maxDestAmount.mul(spreadUnit).div(spreadUnit - spread); uint256 destTradedAmount = doNetworkTrade(src, srcAmount, dest, adaptedMaxDestAmount, adaptedMinRate); uint256 notTraded = _myBalance(src); uint256 srcTradedAmount = srcAmount.sub(notTraded); require(srcTradedAmount > 0, "no traded tokens"); require( _myBalance(dest) >= destTradedAmount, "No enough dest tokens after trade"
45,980
7
// this checks if a person has already voted
require(!voters[msg.sender]);
require(!voters[msg.sender]);
39,337
2
// Update this interface by bumping the version then updating in-place. Previous versions will be immortalised in manifest but do not need to be kept around to clutter solidity code
interface ICedarDeployerV10 is ICedarDeployerOwnEventsV1, ICedarVersionedV2 { function deployCedarERC1155DropV4( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, string memory _userAgreement, uint128 _platformFeeBps, address _platformFeeRecipient ) external payable returns (ICedarERC1155DropV5); function deployCedarERC721DropV5( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, string memory _userAgreement, uint128 _platformFeeBps, address _platformFeeRecipient ) external payable returns (ICedarERC721DropV7); function deployCedarPaymentSplitterV2(address[] memory payees, uint256[] memory shares) external returns (ICedarPaymentSplitterV2); /// Versions function cedarERC721DropVersion() external view returns ( uint256 major, uint256 minor, uint256 patch ); function cedarERC1155DropVersion() external view returns ( uint256 major, uint256 minor, uint256 patch ); function cedarPaymentSplitterVersion() external view returns ( uint256 major, uint256 minor, uint256 patch ); /// Features function cedarERC721DropFeatures() external view returns (string[] memory features); function cedarERC1155DropFeatures() external view returns (string[] memory features); function cedarPaymentSplitterFeatures() external view returns (string[] memory features); }
interface ICedarDeployerV10 is ICedarDeployerOwnEventsV1, ICedarVersionedV2 { function deployCedarERC1155DropV4( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, string memory _userAgreement, uint128 _platformFeeBps, address _platformFeeRecipient ) external payable returns (ICedarERC1155DropV5); function deployCedarERC721DropV5( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, string memory _userAgreement, uint128 _platformFeeBps, address _platformFeeRecipient ) external payable returns (ICedarERC721DropV7); function deployCedarPaymentSplitterV2(address[] memory payees, uint256[] memory shares) external returns (ICedarPaymentSplitterV2); /// Versions function cedarERC721DropVersion() external view returns ( uint256 major, uint256 minor, uint256 patch ); function cedarERC1155DropVersion() external view returns ( uint256 major, uint256 minor, uint256 patch ); function cedarPaymentSplitterVersion() external view returns ( uint256 major, uint256 minor, uint256 patch ); /// Features function cedarERC721DropFeatures() external view returns (string[] memory features); function cedarERC1155DropFeatures() external view returns (string[] memory features); function cedarPaymentSplitterFeatures() external view returns (string[] memory features); }
14,393
1
// mapping containing info about the token contracts corresponding to salt already used for CREATE2 deployments
mapping(string => address) public tokenDeployed;
mapping(string => address) public tokenDeployed;
7,399
90
// validate destination address is set
require(_to != address(0), "zero address");
require(_to != address(0), "zero address");
9,468
30
// HOLDER SETTERS[.√.] sets: email for a given `_tokenId`
function setEmail(uint _tokenId, string memory _email) public onlyHolder(_tokenId) { // checks: tokenId exists // require(_exists(_tokenId), 'URI query for non-existent holder.'); // gets: `holderInfo` from claim by tokenId // Holders storage holder = holderInfo[_tokenId]; require(!holder.signed, 'already signed, must request update.'); // sets: `email` to _email // holder.email = _email; }
function setEmail(uint _tokenId, string memory _email) public onlyHolder(_tokenId) { // checks: tokenId exists // require(_exists(_tokenId), 'URI query for non-existent holder.'); // gets: `holderInfo` from claim by tokenId // Holders storage holder = holderInfo[_tokenId]; require(!holder.signed, 'already signed, must request update.'); // sets: `email` to _email // holder.email = _email; }
32,873
55
// This hook may be overriden in inheritor contracts for extendbase functionality._wNFTAddress -wrapped token address _wNFTTokenId -wrapped token idmust returns true for success unwrapping enable/
function _beforeUnWrapHook( address _wNFTAddress, uint256 _wNFTTokenId, bool _emergency ) internal virtual returns (bool)
function _beforeUnWrapHook( address _wNFTAddress, uint256 _wNFTTokenId, bool _emergency ) internal virtual returns (bool)
8,939
7
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); }
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash ))))); }
28,360
62
//
{ uint256 payAmt = flightInsurancePayments[flightKey].customerInsPurchase[customerId]; if (payAmt > 0) return true; else return false; }
{ uint256 payAmt = flightInsurancePayments[flightKey].customerInsPurchase[customerId]; if (payAmt > 0) return true; else return false; }
5,332
273
// if treasury address mint 18
mint(18);
mint(18);
3,221
29
// REMOVE LIQUIDITY (supporting fee-on-transfer tokens)
function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline
function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline
4,168
168
// Allows the new owner to claim control of the contract/
function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; }
function claimOwnership(TellorStorage.TellorStorageStruct storage self) public { require(msg.sender == self.addressVars[pending_owner], "Sender is not pending owner"); emit OwnershipTransferred(self.addressVars[_owner], self.addressVars[pending_owner]); self.addressVars[_owner] = self.addressVars[pending_owner]; }
55,451
2
// Interface of the IMintableBurnableTokenUpgradeable standard /
interface IMintableBurnableTokenUpgradeable is IMintableTokenUpgradeable, IGenericBurnableFrom { }
interface IMintableBurnableTokenUpgradeable is IMintableTokenUpgradeable, IGenericBurnableFrom { }
43,188
142
// Take capacity from tranche S utilized first and give virtual utilized balance to AA
bv.utilized_consumed = bv.consumed;
bv.utilized_consumed = bv.consumed;
27,464
49
// Step 3. Pay down the amount borrowed by the unsafe account -- Enter the market for the token to be liquidated
Comptroller ctroll = Comptroller(kUnitroller); address[] memory cTokens = new address[](1); cTokens[0] = targetToken; uint[] memory Errors = ctroll.enterMarkets(cTokens); if (Errors[0] != 0) { revert("01 Comptroller enter Markets for target token failed. "); }
Comptroller ctroll = Comptroller(kUnitroller); address[] memory cTokens = new address[](1); cTokens[0] = targetToken; uint[] memory Errors = ctroll.enterMarkets(cTokens); if (Errors[0] != 0) { revert("01 Comptroller enter Markets for target token failed. "); }
6,546
38
// check if manager has already voted on contract this round
bool hasVoted; for(uint32 i; i < whitelistContract[_contract].managers.length; i++) { if (whitelistContract[_contract].managers[i] == msg.sender) { hasVoted = true; }
bool hasVoted; for(uint32 i; i < whitelistContract[_contract].managers.length; i++) { if (whitelistContract[_contract].managers[i] == msg.sender) { hasVoted = true; }
11,982
16
// Queues a proposal of state succeededproposalId The id of the proposal to queue/
function queue(uint256 proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "queue: proposal can only be queued if it is succeeded."); Proposal storage proposal = proposals[proposalId]; uint256 eta = block.timestamp.add(timelock.delay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); }
function queue(uint256 proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "queue: proposal can only be queued if it is succeeded."); Proposal storage proposal = proposals[proposalId]; uint256 eta = block.timestamp.add(timelock.delay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); }
36,065
63
// disbelievers
mapping(address => uint256) private _holderFirstBuyTimestamp;
mapping(address => uint256) private _holderFirstBuyTimestamp;
21,373
2
// verifies if backend signature is valid/orderBack order to be validated/signature signature of order/ return boolean comparison between the recover signature and signing wallet
function isPurchaseValid(LibOrder.OrderBack memory orderBack, bytes memory signature) external view returns (bool);
function isPurchaseValid(LibOrder.OrderBack memory orderBack, bytes memory signature) external view returns (bool);
16,435
88
// The total amount is the amount desired plus the blockchain fee to destination, in the token unit
uint256 totalAmount = amount + transactionFee[0];
uint256 totalAmount = amount + transactionFee[0];
60,624
80
// from address
address(0),
address(0),
39,104
130
// this can be called by anyone on the short contract to claim the rewards.
function getReward(address account) external onlyShortContract nonReentrant updateReward(account) { uint256 reward = rewards[account]; if (reward > 0) { rewards[account] = 0; rewardsToken.safeTransfer(account, reward); emit RewardPaid(account, reward); } }
function getReward(address account) external onlyShortContract nonReentrant updateReward(account) { uint256 reward = rewards[account]; if (reward > 0) { rewards[account] = 0; rewardsToken.safeTransfer(account, reward); emit RewardPaid(account, reward); } }
1,772
27
// todo check limit (2) for queue requests with tests
for (uint8 k = 0; k < limitQueueReq; k++) {
for (uint8 k = 0; k < limitQueueReq; k++) {
32,409
26
// Allows to recover accidentally sent tokensinto the farm except stake and reward tokens /
function recoverToken( IERC20 tokenAddress, uint256 tokenAmount ) external
function recoverToken( IERC20 tokenAddress, uint256 tokenAmount ) external
29,561
18
// CONSTRUCTOR /
function ExoToken(uint256 initialSupply, uint256 initialPriceOfToken) public { // set initialSupply to e.g. 82,250,000 require(initialPriceOfToken > 0); ceoAddress = msg.sender; marketplaceAddress = msg.sender; priceOfToken = initialPriceOfToken; balances[msg.sender] = initialSupply; totalSupply_ = initialSupply; }
function ExoToken(uint256 initialSupply, uint256 initialPriceOfToken) public { // set initialSupply to e.g. 82,250,000 require(initialPriceOfToken > 0); ceoAddress = msg.sender; marketplaceAddress = msg.sender; priceOfToken = initialPriceOfToken; balances[msg.sender] = initialSupply; totalSupply_ = initialSupply; }
11,998
33
// manually set the confirmation period as complete early, optional/
function finalizeConfirmationPeriod() public onlyOwner onlyConfirmPayment { confirmationPeriodOver = true; }
function finalizeConfirmationPeriod() public onlyOwner onlyConfirmPayment { confirmationPeriodOver = true; }
13,128
8
// A convenience function a seller can use to revoke their offer.
function revokeOffer() external { delete offerBySeller[msg.sender]; emit OfferSet(msg.sender, address(0), 0, 0, 0); }
function revokeOffer() external { delete offerBySeller[msg.sender]; emit OfferSet(msg.sender, address(0), 0, 0, 0); }
33,690
35
// Removes the ClaimIssuer contract of a trusted claim issuer.Requires that the claim issuer contract to be registered first _trustedIssuer the claim issuer to remove.This function can only be called by the owner of the Trusted Issuers Registry contractemits a `TrustedIssuerRemoved` event/
function removeTrustedIssuer(IClaimIssuer _trustedIssuer) external;
function removeTrustedIssuer(IClaimIssuer _trustedIssuer) external;
40,175
138
// |/Gas ReceiptfeeTokenData : (bool, address, ?unit256)1st element should be the address of the token2nd argument (if ERC-1155) should be the ID of the tokenLast element should be a 0x0 if ERC-20 and 0x1 for ERC-1155 /
struct GasReceipt { uint256 gasFee; // Fixed cost for the tx uint256 gasLimitCallback; // Maximum amount of gas the callback in transfer functions can use address feeRecipient; // Address to send payment to bytes feeTokenData; // Data for token to pay for gas }
struct GasReceipt { uint256 gasFee; // Fixed cost for the tx uint256 gasLimitCallback; // Maximum amount of gas the callback in transfer functions can use address feeRecipient; // Address to send payment to bytes feeTokenData; // Data for token to pay for gas }
13,195
62
// Goes to the next stage if posible (if the next stage is valid)
function goToNextStage(State storage self) internal { Stage storage current = self.stages[self.currentStageId]; require(self.validStage[current.nextId]); self.currentStageId = current.nextId; self.onTransition(current.nextId); }
function goToNextStage(State storage self) internal { Stage storage current = self.stages[self.currentStageId]; require(self.validStage[current.nextId]); self.currentStageId = current.nextId; self.onTransition(current.nextId); }
37,763
19
// The price must be divided by 1000 on each use case to get the correct amount, because the price was previously multiplied by 1000
require( IERC20(daiContractAddress).balanceOf(msg.sender) >= price / 1000, "Not enough balance to pay the token" ); require( IERC20(daiContractAddress).allowance( msg.sender, address(this) ) >= price / 1000,
require( IERC20(daiContractAddress).balanceOf(msg.sender) >= price / 1000, "Not enough balance to pay the token" ); require( IERC20(daiContractAddress).allowance( msg.sender, address(this) ) >= price / 1000,
41,344
5
// strike price is not reached so premium is entiled to 0
premiumVault.setClaimTVL(_epochId, 0);
premiumVault.setClaimTVL(_epochId, 0);
20,249
197
// https:docs.synthetix.io/contracts/SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor(address _owner, uint _lastMintEvent, uint _currentWeek) public Owned(_owner) { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; if (currentWeek < SUPPLY_DECAY_START) { // If current week is before supply decay we add initial supply to mintableSupply totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } else if (currentWeek <= SUPPLY_DECAY_END) { // if current week before supply decay ends we add the new supply for the week // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START - 1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } else { // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require( msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action" ); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor(address _owner, uint _lastMintEvent, uint _currentWeek) public Owned(_owner) { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; if (currentWeek < SUPPLY_DECAY_START) { // If current week is before supply decay we add initial supply to mintableSupply totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } else if (currentWeek <= SUPPLY_DECAY_END) { // if current week before supply decay ends we add the new supply for the week // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START - 1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } else { // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require( msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action" ); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
5,750
132
// only owner address can set treasury address /
function ownerSetTreasury(address newTreasury) public onlyOwner { treasury = newTreasury; }
function ownerSetTreasury(address newTreasury) public onlyOwner { treasury = newTreasury; }
19,678
88
// See {IERC165-supportsInterface}. /
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); }
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); }
211
284
// Allow havven to issue a certain number ofnomins from an account. /
{ tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); }
{ tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); }
26,393
12
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
14,239
197
// Base URI
string private _baseURI;
string private _baseURI;
2,119
174
// Info of each pool.
struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HONEYs to distribute per block. uint256 lastRewardBlock; // Last block number that HONEYs distribution occurs. uint256 accHoneyPerShare; // Accumulated HONEYs per share, times 1e12. See below. }
struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HONEYs to distribute per block. uint256 lastRewardBlock; // Last block number that HONEYs distribution occurs. uint256 accHoneyPerShare; // Accumulated HONEYs per share, times 1e12. See below. }
54,310
40
// -----------------------------------------Mappings
mapping(address => mapping(uint256 => uint256)) public stakingTime; mapping(address => userInfo ) public User; mapping(uint256=>bool) public alreadyAwarded; mapping(address=>mapping(uint256=>uint256)) public depositTime; mapping(uint256=>Stake) public vault; uint256 time= 1 days; uint256 public totalSupply=3981; uint256 lockingtime= 1 days; uint256 public firstReward =300 ether;
mapping(address => mapping(uint256 => uint256)) public stakingTime; mapping(address => userInfo ) public User; mapping(uint256=>bool) public alreadyAwarded; mapping(address=>mapping(uint256=>uint256)) public depositTime; mapping(uint256=>Stake) public vault; uint256 time= 1 days; uint256 public totalSupply=3981; uint256 lockingtime= 1 days; uint256 public firstReward =300 ether;
64,481
122
// Returns DAI to decrease debt and attempts to unlock any amount of collateral Adapted from https:github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.solL758
function wipeAndFreeGem( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToRepay
function wipeAndFreeGem( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToRepay
3,313
19
//
struct GameInfo{ //int256[][] gameAnsOptions; //uint gameWindowEndTime; //uint gameParticipateEndTime; //int256 numOfParticipants; }
struct GameInfo{ //int256[][] gameAnsOptions; //uint gameWindowEndTime; //uint gameParticipateEndTime; //int256 numOfParticipants; }
7,253
124
// Set connectors configs. Items should have `newConnector` variable to create connectors and `connectorIndex`to update existing connectors. _connectorList Array of connector items. /
function setConnectorList(ConnectorInput[] memory _connectorList) external onlyOwner { require(_connectorList.length != 0, "CONNECTORS_LENGTH_CANT_BE_NULL"); for (uint256 i = 0; i < _connectorList.length; i++) { ConnectorInput memory c = _connectorList[i]; if (c.newConnector) { connectors.push( Connector( c.connector, c.share, c.callBeforeAfterPoke, 0, 0, new bytes(0), new bytes(0), new bytes(0), new bytes(0) ) ); c.connectorIndex = connectors.length - 1; } else { connectors[c.connectorIndex].connector = c.connector; connectors[c.connectorIndex].share = c.share; connectors[c.connectorIndex].callBeforeAfterPoke = c.callBeforeAfterPoke; } emit SetConnector(c.connector, c.share, c.callBeforeAfterPoke, c.connectorIndex, c.newConnector); } _checkConnectorsTotalShare(); }
function setConnectorList(ConnectorInput[] memory _connectorList) external onlyOwner { require(_connectorList.length != 0, "CONNECTORS_LENGTH_CANT_BE_NULL"); for (uint256 i = 0; i < _connectorList.length; i++) { ConnectorInput memory c = _connectorList[i]; if (c.newConnector) { connectors.push( Connector( c.connector, c.share, c.callBeforeAfterPoke, 0, 0, new bytes(0), new bytes(0), new bytes(0), new bytes(0) ) ); c.connectorIndex = connectors.length - 1; } else { connectors[c.connectorIndex].connector = c.connector; connectors[c.connectorIndex].share = c.share; connectors[c.connectorIndex].callBeforeAfterPoke = c.callBeforeAfterPoke; } emit SetConnector(c.connector, c.share, c.callBeforeAfterPoke, c.connectorIndex, c.newConnector); } _checkConnectorsTotalShare(); }
44,005
3,438
// 1721
entry "suppliantly" : ENG_ADVERB
entry "suppliantly" : ENG_ADVERB
22,557
26
// only test!!!!!!!! REMOVE FOR MAINNET
function destroy() external
function destroy() external
2,889
313
// Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium _vaultId to liquidate _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault Resulting ratio must be above or equal minimun ratio A fee of exactly burnFee must be sent as value on ETH The fee goes to the treasury contract /
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP) external payable nonReentrant whenNotPaused
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP) external payable nonReentrant whenNotPaused
36,811
12
// Hash of the deal information.
bytes32 metadata;
bytes32 metadata;
5,467
135
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
mapping(uint256 => uint256) private _allTokensIndex;
217
30
// Check to see if we can issue tokens to them. Advisors can redeem every 30 days for 10 months
if (advisorsTokensIssuedOn[msg.sender] == 0 || ((now - advisorsTokensIssuedOn[msg.sender]) >= 30 days)) {
if (advisorsTokensIssuedOn[msg.sender] == 0 || ((now - advisorsTokensIssuedOn[msg.sender]) >= 30 days)) {
13,053
37
// Caches the total supply of vetoken at the beginning of each week.This function will be called automatically before claiming tokens to ensure the contract is properly updated. /
function checkpoint() external override nonReentrant { _checkpointTotalSupply(); }
function checkpoint() external override nonReentrant { _checkpointTotalSupply(); }
20,244
3
// User Rewards
mapping(address => uint256) public points; mapping(address => uint256) public lastUpdateTime;
mapping(address => uint256) public points; mapping(address => uint256) public lastUpdateTime;
77,372
1
// checks if an agent has submitted his reviews/map scores data structure/reviewer index of the reviewer in the proposals set/ return if the agent submitted the reviews
function checkSubmitted(ScoreMap storage map, uint reviewer) view external returns (bool){ return (map.reviewsTo[reviewer].length != 0); }
function checkSubmitted(ScoreMap storage map, uint reviewer) view external returns (bool){ return (map.reviewsTo[reviewer].length != 0); }
2,806
114
// removeLiquidity
(q.tokenRemoved,q.currencyRemoved,q.liquidityRemoved) = _removeLiquidity(uniswapRouter, _pair, _token, _currency,_lpp);
(q.tokenRemoved,q.currencyRemoved,q.liquidityRemoved) = _removeLiquidity(uniswapRouter, _pair, _token, _currency,_lpp);
17,790
6
// Get the underlying price of a token asset_token The _token to get the price of return The underlying asset price mantissa (scaled by 1e8).Zero means the price is unavailable./
function getPrice(address _token) public override view returns (int) { address feed = priceFeeds[_token]; if(feed != address(0)) { return ITokenOracle(feed).getPrice(_token); } require(int(store[_token].price) >= 0, 'price to lower'); return int(store[_token].price); }
function getPrice(address _token) public override view returns (int) { address feed = priceFeeds[_token]; if(feed != address(0)) { return ITokenOracle(feed).getPrice(_token); } require(int(store[_token].price) >= 0, 'price to lower'); return int(store[_token].price); }
50,303
0
// ---------------- struct ------------
struct Candidate { string name; uint256 point; }
struct Candidate { string name; uint256 point; }
7,966
314
// Approves tokens for the smart contract./
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } }
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } }
44,295
168
// delete the admins votes & log. i know for loops are terrible.but we have to do this for our data stored in mappings.simply deleting the proposal itself wouldn&39;t accomplish this.
for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; }
for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; }
19,299
13
// Emitted when the price is updated. /
event PriceUpdate(uint256 price);
event PriceUpdate(uint256 price);
25,268
2
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER421() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; }
function _MSGSENDER421() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; }
3,562
7
// withdraw reward tokens owned by staking contract to the token ids to unstakeamount the amount of tokens to withdraw/
function withdraw(address to, uint256 amount) external onlyOwner { require( rewardToken.balanceOf(address(this)) >= amount, "Withdraw: balance exceeded"); rewardToken.transfer(to, amount); }
function withdraw(address to, uint256 amount) external onlyOwner { require( rewardToken.balanceOf(address(this)) >= amount, "Withdraw: balance exceeded"); rewardToken.transfer(to, amount); }
73,242