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
82
// This approves _approved to get ownership of _tokenId.Note: that since this is used for both purchase and transfer approvalsthe approved token may not exist. /
function approve( address _approved, uint _tokenId ) public
function approve( address _approved, uint _tokenId ) public
15,656
42
// Unlock the contractIdentifier.
migrationLocks[contractIdentifier] = false;
migrationLocks[contractIdentifier] = false;
767
39
// Burns `_amount` tokens from `_owner`/_owner The address that will lose the tokens/_amount The quantity of tokens to burn/ return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) public returns (bool);
function destroyTokens(address _owner, uint _amount) public returns (bool);
23,400
15
// Transfer tokens Send `_value` tokens to `_to` from your account_to The address of the recipient_value the amount to send/
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
81,891
17
// Encodes `data` using the base64 encoding described in RFC 4648./ Equivalent to `encode(data, fileSafe, false)`.
function encode(bytes memory data, bool fileSafe) internal pure returns (string memory result) { result = encode(data, fileSafe, false); }
function encode(bytes memory data, bool fileSafe) internal pure returns (string memory result) { result = encode(data, fileSafe, false); }
14,164
825
// Creates a market object and ensures that the rate oracle time window is updated appropriately, this/ is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate
function loadMarketWithSettlementDate( MarketParameters memory market, uint256 currencyId, uint256 maturity, uint256 blockTime, bool needsLiquidity, uint256 rateOracleTimeWindow, uint256 settlementDate
16,236
23
// ------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account. The spender contract function receiveApproval(...) is then executed ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
2,186
22
// See `IERC20.transfer`. Requirements: - `recipient` cannot be the zero address.- the caller must have a balance of at least `amount`. /
function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
14,664
100
// Get the token balance of the `owner` owner The address of the account to queryreturn The number of tokens owned by `owner` /
function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); }
function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); }
13,579
35
// update last selector slot position info
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
39,967
26
// Returns number of valid guardian signatures required to vet (depositRoot, keysOpIndex) pair. /
function getGuardianQuorum() external view returns (uint256) { return quorum; }
function getGuardianQuorum() external view returns (uint256) { return quorum; }
79,457
4
// Change organisation nametakes newOrganisationNamemodified with onlyOwner /
function changeOrganisationName( string newOrganisationName
function changeOrganisationName( string newOrganisationName
2,752
26
// Allows to mint one NFT if whitelisted _tokenIds Tokens that sender want to transfer_custom custom council/
function presaleMint(uint256[] calldata _tokenIds, bool _custom) external payable nonReentrant { uint numberNftSold = _totalMinted(); uint price=0; //Are we in Presale ? require(sellingStep == Steps.Presale, "Presale has not started yet."); // Check length of token require(_tokenIds.length == 3 ||_tokenIds.length == 5 ||_tokenIds.length == 7 ||_tokenIds.length == 20, "Wrong length of tokens."); //Did the user send enought Ethers ? if(_tokenIds.length == 3 && _custom){ price = priceCustomBikkuri; }else if(_tokenIds.length == 5 && _custom){ price = priceCustomSame; } require(msg.value >= price, "Not enought funds."); for (uint index = 0; index < _tokenIds.length; index++) { require(msg.sender == tokenContract.ownerOf(_tokenIds[index]), "You don't own those token"); tokenContract.safeTransferFrom(msg.sender, _owner, _tokenIds[index]); require(_owner == tokenContract.ownerOf(_tokenIds[index]), "Transaction fail.."); } //Mint the user NFT _safeMint(msg.sender, 1); numberNftSold++; if(_tokenIds.length == 3){ tier[numberNftSold] = tiers[1]; }else if(_tokenIds.length == 5){ tier[numberNftSold] = tiers[2]; }else if(_tokenIds.length == 7){ tier[numberNftSold] = tiers[3]; }else if(_tokenIds.length == 20){ tier[numberNftSold] = tiers[4]; } }
function presaleMint(uint256[] calldata _tokenIds, bool _custom) external payable nonReentrant { uint numberNftSold = _totalMinted(); uint price=0; //Are we in Presale ? require(sellingStep == Steps.Presale, "Presale has not started yet."); // Check length of token require(_tokenIds.length == 3 ||_tokenIds.length == 5 ||_tokenIds.length == 7 ||_tokenIds.length == 20, "Wrong length of tokens."); //Did the user send enought Ethers ? if(_tokenIds.length == 3 && _custom){ price = priceCustomBikkuri; }else if(_tokenIds.length == 5 && _custom){ price = priceCustomSame; } require(msg.value >= price, "Not enought funds."); for (uint index = 0; index < _tokenIds.length; index++) { require(msg.sender == tokenContract.ownerOf(_tokenIds[index]), "You don't own those token"); tokenContract.safeTransferFrom(msg.sender, _owner, _tokenIds[index]); require(_owner == tokenContract.ownerOf(_tokenIds[index]), "Transaction fail.."); } //Mint the user NFT _safeMint(msg.sender, 1); numberNftSold++; if(_tokenIds.length == 3){ tier[numberNftSold] = tiers[1]; }else if(_tokenIds.length == 5){ tier[numberNftSold] = tiers[2]; }else if(_tokenIds.length == 7){ tier[numberNftSold] = tiers[3]; }else if(_tokenIds.length == 20){ tier[numberNftSold] = tiers[4]; } }
21,333
9
// WhiteList check
require( MerkleProof.verify( _merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender, uint16(alloc))) ), "You don't have a whitelist!" ); require( balanceOf(msg.sender) + _mintAmount <= alloc,
require( MerkleProof.verify( _merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender, uint16(alloc))) ), "You don't have a whitelist!" ); require( balanceOf(msg.sender) + _mintAmount <= alloc,
18,401
277
// accumulate rewards from stakes and transfer at once
uint256 rewardLength = farms[fId].phase.rewards.length; uint256[] memory rewardAmounts = new uint256[](rewardLength); for (uint256 i; i < nftLength; ) { for (uint256 j; j < rewardLength; ) { rewardAmounts[j] += stakes[nftIds[i]].rewardUnclaimed[j]; stakes[nftIds[i]].rewardUnclaimed[j] = 0; unchecked { ++j; }
uint256 rewardLength = farms[fId].phase.rewards.length; uint256[] memory rewardAmounts = new uint256[](rewardLength); for (uint256 i; i < nftLength; ) { for (uint256 j; j < rewardLength; ) { rewardAmounts[j] += stakes[nftIds[i]].rewardUnclaimed[j]; stakes[nftIds[i]].rewardUnclaimed[j] = 0; unchecked { ++j; }
4,226
18
// alphaIndex
rarities[15] = [ 173, 255, 163, 10 ]; aliases[15] = [ 1, 1, 0, 0 ];
rarities[15] = [ 173, 255, 163, 10 ]; aliases[15] = [ 1, 1, 0, 0 ];
10,534
10
// Add tx to the syscoinTxHashesAlreadyProcessed and Check tx was not already processed
require(syscoinTxHashesAlreadyProcessed.insert(txHash), "TX already processed");
require(syscoinTxHashesAlreadyProcessed.insert(txHash), "TX already processed");
46,834
98
// Overrides finishMinting function from RBACMintableTokenMixin to prevent finishing minting before finalization/ return A boolean that indicates if the operation was successful.
function finishMinting() internal returns (bool) { require(finalized == true); require(super.finishMinting()); return true; }
function finishMinting() internal returns (bool) { require(finalized == true); require(super.finishMinting()); return true; }
56,228
15
// withdraw token
function withdrawToken(string symbolName,uint256 amount) public { uint8 symbolIndex = getSymbolIndex(symbolName); require(tokens[symbolIndex].tokenContract !=address(0)); IERC20 token = IERC20(tokens[symbolIndex].tokenContract); require(tokenBalances[msg.sender][symbolIndex] - amount >=0); require(tokenBalances[msg.sender][symbolIndex] - amount <= tokenBalances[msg.sender][symbolIndex]); tokenBalances[msg.sender][symbolIndex] -= amount; require(token.transfer(msg.sender,amount) == true); emit log_WithDrawToken(msg.sender, symbolIndex,amount,now); }
function withdrawToken(string symbolName,uint256 amount) public { uint8 symbolIndex = getSymbolIndex(symbolName); require(tokens[symbolIndex].tokenContract !=address(0)); IERC20 token = IERC20(tokens[symbolIndex].tokenContract); require(tokenBalances[msg.sender][symbolIndex] - amount >=0); require(tokenBalances[msg.sender][symbolIndex] - amount <= tokenBalances[msg.sender][symbolIndex]); tokenBalances[msg.sender][symbolIndex] -= amount; require(token.transfer(msg.sender,amount) == true); emit log_WithDrawToken(msg.sender, symbolIndex,amount,now); }
4,374
156
// Approve strategy for spending of renbtc.
renBTC.safeApprove(strategy, _amount); try ISwapStrategy(strategy).swapTokens(address(renBTC), address(wBTC), _amount, _slippage) { return true; } catch (bytes memory _error) {
renBTC.safeApprove(strategy, _amount); try ISwapStrategy(strategy).swapTokens(address(renBTC), address(wBTC), _amount, _slippage) { return true; } catch (bytes memory _error) {
12,537
9
// close re-entry gate
receipt.timeWithdrawn = block.timestamp; uint[] memory rewards = getRewards(poolId, receiptId); pool.totalDepositsWei = pool.totalDepositsWei.minus(receipt.amountDepositedWei); bool success = true; for (uint i = 0; i < rewards.length; i++) { pool.rewardsWeiClaimed[i] = pool.rewardsWeiClaimed[i].plus(rewards[i]); success = success && IERC20(pool.rewardTokens[i]).transfer(receipt.owner, rewards[i]); }
receipt.timeWithdrawn = block.timestamp; uint[] memory rewards = getRewards(poolId, receiptId); pool.totalDepositsWei = pool.totalDepositsWei.minus(receipt.amountDepositedWei); bool success = true; for (uint i = 0; i < rewards.length; i++) { pool.rewardsWeiClaimed[i] = pool.rewardsWeiClaimed[i].plus(rewards[i]); success = success && IERC20(pool.rewardTokens[i]).transfer(receipt.owner, rewards[i]); }
9,166
75
// Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5(1018)`. a uint to convert into a FixedPoint.return the converted FixedPoint. /
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); }
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); }
17,391
203
// Remove the LP count from the old proxy
proxy_lp_balances[old_proxy_addr] -= _locked_liquidity[msg.sender];
proxy_lp_balances[old_proxy_addr] -= _locked_liquidity[msg.sender];
16,419
14
// about 0.3%
uint fee = ((amount * 3) / 997) + 1; uint amountToRepay = amount + fee;
uint fee = ((amount * 3) / 997) + 1; uint amountToRepay = amount + fee;
9,984
61
// ERC20 11 11/
function transfer(address recipient, uint256 amount) external override isAllowedUser(msg.sender) returns (bool){ return __transfer(recipient, amount); }
function transfer(address recipient, uint256 amount) external override isAllowedUser(msg.sender) returns (bool){ return __transfer(recipient, amount); }
50,781
0
// Retrieves node's info nodeID ID of node (Tendermint consensus key)returns tuple representation of Node structure /
function getNode(bytes32 nodeID) external view returns (bytes24, uint16, uint16, address, bool, uint256[] memory)
function getNode(bytes32 nodeID) external view returns (bytes24, uint16, uint16, address, bool, uint256[] memory)
30,563
24
// que el mes de los calculos sea menor al mes actual
if(ServiceLib.getLastSendedEmails(serviceId).length < 4){ if (newService == true){ ServiceLib.SendedEmail memory newSendedEmail = ServiceLib.SendedEmail({date:toTimestamp(last_year, last_month, 1, 0, 0, 0) + seconds_to_add, hasChanged:false});
if(ServiceLib.getLastSendedEmails(serviceId).length < 4){ if (newService == true){ ServiceLib.SendedEmail memory newSendedEmail = ServiceLib.SendedEmail({date:toTimestamp(last_year, last_month, 1, 0, 0, 0) + seconds_to_add, hasChanged:false});
24,129
36
// Create new Aworker token smart contract, with given number of tokens issuedand given to msg.sender, and make msg.sender the owner of this smartcontract._tokenCount number of tokens to issue and give to msg.sender /
function AworkerToken (uint256 _tokenCount) public { owner = msg.sender; tokenCount = _tokenCount; accounts [msg.sender] = _tokenCount; }
function AworkerToken (uint256 _tokenCount) public { owner = msg.sender; tokenCount = _tokenCount; accounts [msg.sender] = _tokenCount; }
73,741
1
// Emitted when a proxy is deployed.
event ProxyDeployed(address indexed implementation, address proxy, address indexed deployer); event ImplementationAdded(address implementation, bytes32 indexed contractType, uint256 version); event ImplementationApproved(address implementation, bool isApproved);
event ProxyDeployed(address indexed implementation, address proxy, address indexed deployer); event ImplementationAdded(address implementation, bytes32 indexed contractType, uint256 version); event ImplementationApproved(address implementation, bool isApproved);
3,628
30
// create an instance of the jekyll island bank
Bank currentCorpBank_;
Bank currentCorpBank_;
45,441
10
// Actualiza el nombre y precio al NUEVO maximo postor
highestBidder = payable(msg.sender); highestPrice = msg.value;
highestBidder = payable(msg.sender); highestPrice = msg.value;
38,486
200
// remove Liquidity from Exchange _exchange IExchange address _lpTokenAmount lp token asset amount in 18 digits. Can Not be 0 /
function removeLiquidity(IExchange _exchange, Decimal.decimal calldata _lpTokenAmount) external { requireExchange(_exchange, true); requireNonZeroInput(_lpTokenAmount); SignedDecimal.signedDecimal memory totalLpUnrealizedPNL = getTotalLpUnrealizedPNL(_exchange); Decimal.decimal memory totalLpTokenAmount = Decimal.decimal(IERC20Upgradeable(address(_exchange)).totalSupply()); SignedDecimal.signedDecimal memory totalLpLiquidity = getMMLiquidity(address(_exchange)); SignedDecimal.signedDecimal memory returnQuoteAssetAmount = MixedDecimal .fromDecimal(_lpTokenAmount) .mulD(totalLpLiquidity.addD(totalLpUnrealizedPNL)) .divD(totalLpTokenAmount) .mulD(Decimal.one().subD(systemSettings.lpWithdrawFeeRatio())); _exchange.burn(_msgSender(), _lpTokenAmount.toUint()); IERC20Upgradeable(_exchange.quoteAsset()).safeTransfer(_msgSender(), returnQuoteAssetAmount.toUint()); exchangeLiquidityMap[address(_exchange)] = totalLpLiquidity.subD(returnQuoteAssetAmount); emit LiquidityRemove(address(_exchange), _msgSender(), returnQuoteAssetAmount.toUint(), _lpTokenAmount.toUint()); requireMMNotBankrupt(_exchange); }
function removeLiquidity(IExchange _exchange, Decimal.decimal calldata _lpTokenAmount) external { requireExchange(_exchange, true); requireNonZeroInput(_lpTokenAmount); SignedDecimal.signedDecimal memory totalLpUnrealizedPNL = getTotalLpUnrealizedPNL(_exchange); Decimal.decimal memory totalLpTokenAmount = Decimal.decimal(IERC20Upgradeable(address(_exchange)).totalSupply()); SignedDecimal.signedDecimal memory totalLpLiquidity = getMMLiquidity(address(_exchange)); SignedDecimal.signedDecimal memory returnQuoteAssetAmount = MixedDecimal .fromDecimal(_lpTokenAmount) .mulD(totalLpLiquidity.addD(totalLpUnrealizedPNL)) .divD(totalLpTokenAmount) .mulD(Decimal.one().subD(systemSettings.lpWithdrawFeeRatio())); _exchange.burn(_msgSender(), _lpTokenAmount.toUint()); IERC20Upgradeable(_exchange.quoteAsset()).safeTransfer(_msgSender(), returnQuoteAssetAmount.toUint()); exchangeLiquidityMap[address(_exchange)] = totalLpLiquidity.subD(returnQuoteAssetAmount); emit LiquidityRemove(address(_exchange), _msgSender(), returnQuoteAssetAmount.toUint(), _lpTokenAmount.toUint()); requireMMNotBankrupt(_exchange); }
34,721
207
// require(_state.epochs[epoch].coupons.outstanding == 0);
vsdRedeemable = _state.epochs[epoch].coupons.vsdRedeemable.mul(couponRedeemed).div(_state.epochs[epoch].coupons.couponRedeemed);
vsdRedeemable = _state.epochs[epoch].coupons.vsdRedeemable.mul(couponRedeemed).div(_state.epochs[epoch].coupons.couponRedeemed);
19,829
227
// Adds a verified proxy address.Can be done through a multisig wallet in the future. _proxy Proxy address. /
function addProxy(
function addProxy(
5,206
5
// Token ordering is verified by submitSolution. Required because binary search is used to fetch token info. tokenIdsForPrice list of tokenIdsreturn true if tokenIdsForPrice is sorted else false /
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) { for (uint256 i = 1; i < tokenIdsForPrice.length; i++) { if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) { return false; } } return true; }
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) { for (uint256 i = 1; i < tokenIdsForPrice.length; i++) { if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) { return false; } } return true; }
29,336
145
// The contract that will return artwork metadata
ERC721Metadata public erc721Metadata; bytes4 private constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 private constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^
ERC721Metadata public erc721Metadata; bytes4 private constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 private constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^
40,189
25
// FoxGame membership date
mapping(address => uint48) public membershipDate; mapping(address => uint32) public memberNumber; event MemberJoined(address member, uint32 memberCount); uint32 public membershipCount;
mapping(address => uint48) public membershipDate; mapping(address => uint32) public memberNumber; event MemberJoined(address member, uint32 memberCount); uint32 public membershipCount;
23,351
957
// Gets the category acion details _categoryId is the category id in concernreturn the category idreturn the contract addressreturn the contract namereturn the default incentive /
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) { return ( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); }
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) { return ( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); }
29,132
337
// Sync modules for a list of modules IDs based on their current implementation address_modulesToBeSynced List of addresses of connected modules to be synced_idsToBeSet List of IDs of the modules included in the sync/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor
19,562
53
// check that passed in pointer is greater than current share pointer and less than length of LP's shares over time array
if ( _newSharePointer <= lpInfo.currSharePtr || _newSharePointer + 1 > lpInfo.sharesOverTime.length ) revert InvalidNewSharePointer(); lpInfo.currSharePtr = uint32(_newSharePointer); lpInfo.fromLoanIdx = uint32( lpInfo.loanIdxsWhereSharesChanged[_newSharePointer - 1] );
if ( _newSharePointer <= lpInfo.currSharePtr || _newSharePointer + 1 > lpInfo.sharesOverTime.length ) revert InvalidNewSharePointer(); lpInfo.currSharePtr = uint32(_newSharePointer); lpInfo.fromLoanIdx = uint32( lpInfo.loanIdxsWhereSharesChanged[_newSharePointer - 1] );
25,440
163
// Return pending manager address// return code
function getPendingManager() public view returns (address) { return pendingManager; }
function getPendingManager() public view returns (address) { return pendingManager; }
42,924
121
// Sets asset spending allowance for a specified spender. Note: to revoke allowance, one needs to set allowance to 0._spenderId holder id to set allowance for. _value amount to allow. _symbol asset symbol. _senderId approve initiator holder id. return success. /
function _approve(uint _spenderId, uint _value, bytes32 _symbol, uint _senderId) internal returns(uint) { // Asset should exist. if (!isCreated(_symbol)) { return _error(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (_senderId == _spenderId) { return _error(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint if (assets[_symbol].wallets[_senderId].allowance[_spenderId] != 0 && _value != 0) { return _error(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } assets[_symbol].wallets[_senderId].allowance[_spenderId] = _value; // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. ChronoBankPlatformEmitter(eventsHistory).emitApprove(_address(_senderId), _address(_spenderId), _symbol, _value); if (proxies[_symbol] != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(proxies[_symbol]).emitApprove(_address(_senderId), _address(_spenderId), _value); } return OK; }
function _approve(uint _spenderId, uint _value, bytes32 _symbol, uint _senderId) internal returns(uint) { // Asset should exist. if (!isCreated(_symbol)) { return _error(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (_senderId == _spenderId) { return _error(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint if (assets[_symbol].wallets[_senderId].allowance[_spenderId] != 0 && _value != 0) { return _error(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } assets[_symbol].wallets[_senderId].allowance[_spenderId] = _value; // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. ChronoBankPlatformEmitter(eventsHistory).emitApprove(_address(_senderId), _address(_spenderId), _symbol, _value); if (proxies[_symbol] != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(proxies[_symbol]).emitApprove(_address(_senderId), _address(_spenderId), _value); } return OK; }
6,914
63
// Interface for Strategies. /
interface IStrategy { /** * @dev Returns the token address that the strategy expects. */ function want() external view returns (address); /** * @dev Returns the total amount of tokens deposited in this strategy. */ function balanceOf() external view returns (uint256); /** * @dev Deposits the token to start earning. */ function deposit() external; /** * @dev Withdraws partial funds from the strategy. */ function withdraw(uint256 _amount) external; /** * @dev Withdraws all funds from the strategy. */ function withdrawAll() external returns (uint256); /** * @dev Claims yield and convert it back to want token. */ function harvest() external; }
interface IStrategy { /** * @dev Returns the token address that the strategy expects. */ function want() external view returns (address); /** * @dev Returns the total amount of tokens deposited in this strategy. */ function balanceOf() external view returns (uint256); /** * @dev Deposits the token to start earning. */ function deposit() external; /** * @dev Withdraws partial funds from the strategy. */ function withdraw(uint256 _amount) external; /** * @dev Withdraws all funds from the strategy. */ function withdrawAll() external returns (uint256); /** * @dev Claims yield and convert it back to want token. */ function harvest() external; }
18,127
175
// calc cvx here
if(reward.reward_token == crv){ claimable[rewardCount].amount = cvx_claimable_reward[_account].add(CvxMining.ConvertCrvToCvx(newlyClaimable)); claimable[i].token = cvx; }
if(reward.reward_token == crv){ claimable[rewardCount].amount = cvx_claimable_reward[_account].add(CvxMining.ConvertCrvToCvx(newlyClaimable)); claimable[i].token = cvx; }
25,730
10
// Require the reward to be less than or equal to the maximum reward parameter,which basically is a hard, floating limit on the number of DID that can be issued for any single task
require((_reward * 1 ether) <= distense.getParameterValueByTitle(distense.maxRewardParameterTitle())); task.rewardVotes[msg.sender] = true; uint256 pctDIDOwned = didToken.pctDIDOwned(msg.sender); task.pctDIDVoted = task.pctDIDVoted + pctDIDOwned;
require((_reward * 1 ether) <= distense.getParameterValueByTitle(distense.maxRewardParameterTitle())); task.rewardVotes[msg.sender] = true; uint256 pctDIDOwned = didToken.pctDIDOwned(msg.sender); task.pctDIDVoted = task.pctDIDVoted + pctDIDOwned;
47
39
// Check that the contract has enough tokens
require(contractTokenBalance > 0, "Contract has no tokens to add as liquidity");
require(contractTokenBalance > 0, "Contract has no tokens to add as liquidity");
14,627
17
// Timestamp Pool Data
timestampsPoolData[_params.poolToken] = TimestampsPoolEntry({ timeStamp: block.timestamp, timeStampScaling: block.timestamp });
timestampsPoolData[_params.poolToken] = TimestampsPoolEntry({ timeStamp: block.timestamp, timeStampScaling: block.timestamp });
40,854
8
// Retrieves the stored address of the LINK tokenreturn The address of the LINK token /
function nulinkToken() internal view returns (address)
function nulinkToken() internal view returns (address)
13,175
21
// Change the Receiver of the total flow
function _changeReceiver( address from, address newReceiver, uint tokenId) internal { require(newReceiver != address(0), "zero addr"); // @dev because our app is registered as final, we can't take downstream apps require(!_ap.host.isApp(ISuperApp(newReceiver)), "SA addr"); if (newReceiver == from) return ; // This gets the current outflowRate of the newReceiver (can be 0 if no flow) (,int96 oldOwnerOutflowRate,,) = _ap.cfa.getFlow(_ap.acceptedToken, address(this), from); // If the newReceiver already has a flow, update it adding tokenOutflow // from the newly acquired token require( _ap.links[tokenId].outflowRate > 0, "!flow"); _createFlow(newReceiver, oldOwnerOutflowRate); // NOTE: This is a hack where we assume each owner has 1 NFT // So all I do now is just delete the flow to the previous holder _deleteFlow(address(this), from); // // Lastly, update the owner on the token _ap.links[tokenId].owner = newReceiver; emit ReceiverChanged(newReceiver, tokenId); }
function _changeReceiver( address from, address newReceiver, uint tokenId) internal { require(newReceiver != address(0), "zero addr"); // @dev because our app is registered as final, we can't take downstream apps require(!_ap.host.isApp(ISuperApp(newReceiver)), "SA addr"); if (newReceiver == from) return ; // This gets the current outflowRate of the newReceiver (can be 0 if no flow) (,int96 oldOwnerOutflowRate,,) = _ap.cfa.getFlow(_ap.acceptedToken, address(this), from); // If the newReceiver already has a flow, update it adding tokenOutflow // from the newly acquired token require( _ap.links[tokenId].outflowRate > 0, "!flow"); _createFlow(newReceiver, oldOwnerOutflowRate); // NOTE: This is a hack where we assume each owner has 1 NFT // So all I do now is just delete the flow to the previous holder _deleteFlow(address(this), from); // // Lastly, update the owner on the token _ap.links[tokenId].owner = newReceiver; emit ReceiverChanged(newReceiver, tokenId); }
43,236
22
// Called when tokens are redeemed
event Redeem(uint amount);
event Redeem(uint amount);
77,794
13
// if ',' is found, new country ahead
if(countriesInBytes[i]=="," || i == countriesInBytes.length-1){ if(i == countriesInBytes.length-1){ country[countryLength]=countriesInBytes[i]; }
if(countriesInBytes[i]=="," || i == countriesInBytes.length-1){ if(i == countriesInBytes.length-1){ country[countryLength]=countriesInBytes[i]; }
70,146
86
// proposer can create 2 proposal in a month
uint256 lastProposeAt = getConfig(_proposerLastProposeAt_, senderInt); if (now.sub(lastProposeAt) < MONTH) {
uint256 lastProposeAt = getConfig(_proposerLastProposeAt_, senderInt); if (now.sub(lastProposeAt) < MONTH) {
40,309
8
// Remove address into whiteList successevent
event RemoveWhiter(address remover);
event RemoveWhiter(address remover);
77,776
189
// Math: if _msgValue was not sufficient then revert
uint refund = _msgValue.sub(_quantityToInvest); if(refund > 0) { Address.sendValue(msg.sender, refund); }
uint refund = _msgValue.sub(_quantityToInvest); if(refund > 0) { Address.sendValue(msg.sender, refund); }
4,863
144
// set collateral occupied value, only foundation operator can modify database.totalCallOccupied new call options occupied collateral calculation result.totalPutOccupied new put options occupied collateral calculation result.beginOption new first valid option's positon.latestCallOccpied latest call options' occupied value when operater invoke collateral occupied calculation.latestPutOccpied latest put options' occupied value when operater invoke collateral occupied calculation. /
function setCollateralPhase(uint256 /*totalCallOccupied*/,uint256 /*totalPutOccupied*/,
function setCollateralPhase(uint256 /*totalCallOccupied*/,uint256 /*totalPutOccupied*/,
35,085
36
// /
function disableTransfers(bool _disable) public onlyOwner { transfersEnabled = !_disable; }
function disableTransfers(bool _disable) public onlyOwner { transfersEnabled = !_disable; }
888
16
// độ lớn của deposit phải lớn hơn 0
require(amount > 0, "Deposit amount must be > 0");
require(amount > 0, "Deposit amount must be > 0");
6,214
120
// Returns the owner of the `tokenId` token. Requirements: - `tokenId` must exist. /
function ownerOf(uint256 tokenId) external view returns (address owner);
function ownerOf(uint256 tokenId) external view returns (address owner);
8,842
68
// constructor (string memory _name, string memory _symbol) public {name = _name;symbol = _symbol;decimals = 18;}
function __name() public view returns (string) { return name; }
function __name() public view returns (string) { return name; }
18,703
12
// Caller withdraws previously accepted deposit of asset. /
function withdraw( IERC20 _asset, uint256 _amount
function withdraw( IERC20 _asset, uint256 _amount
39,085
59
// Updates the currently active fork to given block number This is similar to `roll` but for the currently active fork
function rollFork(uint256) external;
function rollFork(uint256) external;
28,744
33
// Modular function to set Wrapped to Usdt path
function setWrappedToUsdtPath(address[] memory _path) external onlyAdmin { require (_path[0] == wrapped && _path[_path.length - 1] == usdt, "!path"); wrappedToUsdtPath = _path; emit SetWrappedToUsdtPath(_path); }
function setWrappedToUsdtPath(address[] memory _path) external onlyAdmin { require (_path[0] == wrapped && _path[_path.length - 1] == usdt, "!path"); wrappedToUsdtPath = _path; emit SetWrappedToUsdtPath(_path); }
25,804
246
// Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it,and then reverting unless the tokens plus a proportional protocol fee have been returned. The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amountfor each token contract. `tokens` must be sorted in ascending order. The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the`receiveFlashLoan` call. Emits `FlashLoan` events. /
function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external;
function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external;
33,519
77
// bot/sniper penalty.
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){ if(!boughtEarly[to]){ boughtEarly[to] = true; botsCaught += 1; emit CaughtEarlyBuyer(to); }
if(earlyBuyPenaltyInEffect() && automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to] && buyTotalFees > 0){ if(!boughtEarly[to]){ boughtEarly[to] = true; botsCaught += 1; emit CaughtEarlyBuyer(to); }
11,729
45
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; }
unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; }
8,611
3
// Deposit LP tokens to MasterChef for CAKE allocation. function deposit(uint256 _pid, uint256 _amount) external;
function deposit(uint256 _pid, uint256 _amount) external;
function deposit(uint256 _pid, uint256 _amount) external;
6,196
228
// getManagerFor(): returns the points _proxy can manageNote: only useful for clients, as Solidity does not currentlysupport returning dynamic arrays.
function getManagerFor(address _proxy) view external returns (uint32[] mfor)
function getManagerFor(address _proxy) view external returns (uint32[] mfor)
43,435
224
// pay out POOH
_POOH = _POOH.add((_eth.mul(fees_[_team].pooh)) / (100)); if (_POOH > 0) {
_POOH = _POOH.add((_eth.mul(fees_[_team].pooh)) / (100)); if (_POOH > 0) {
31,105
4
// Emits a {Transfer} event./ only TicketAdmin can call this function
function mint(address to) external onlyTicketAdmin { _safeMint(to, _ticketCounter); _ticketCounter++; }
function mint(address to) external onlyTicketAdmin { _safeMint(to, _ticketCounter); _ticketCounter++; }
31,734
243
// Math: safeSub is not required since the if confirms this won't underflow
refund -= penalty;
refund -= penalty;
37,409
356
// convert our keeper's eth cost into want, we don't need this anymore since we don't use baseStrategy harvestTrigger
function ethToWant(uint256 _ethAmount) public view override returns (uint256)
function ethToWant(uint256 _ethAmount) public view override returns (uint256)
21,716
21
// check if request has already been approved and if coin deadline is not exceeded and if there is still enough supply
require(!request.approved, "Request is already approved"); require(coloredCoins[request.coinID].deadlineBlock >= block.number, "Colored Coin has already timed out."); require(coloredCoins[request.coinID].supply >= request.amount, "Not enough supply left.");
require(!request.approved, "Request is already approved"); require(coloredCoins[request.coinID].deadlineBlock >= block.number, "Colored Coin has already timed out."); require(coloredCoins[request.coinID].supply >= request.amount, "Not enough supply left.");
43,066
2
// If the latest observation occurred in the past, then no tick-changing trades have happened in this block therefore the tick in `slot0` is the same as at the beginning of the current block. We don't need to check if this observation is initialized - it is guaranteed to be.
(uint32 observationTimestamp, int56 tickCumulative, , ) = pool.observations(observationIndex); if (observationTimestamp != uint32(_blockTimestamp())) { blockStartingTick = currentTick; } else {
(uint32 observationTimestamp, int56 tickCumulative, , ) = pool.observations(observationIndex); if (observationTimestamp != uint32(_blockTimestamp())) { blockStartingTick = currentTick; } else {
24,673
80
// send back the rest of token to airdrop program
function sendToOwner(uint256 _amount) public onlyOwner { require(icoClosed); _deliverTokens(owner, _amount); }
function sendToOwner(uint256 _amount) public onlyOwner { require(icoClosed); _deliverTokens(owner, _amount); }
2,005
134
// Refunds the highest bidder for an auction. listingId The id of the listing. listing The listing. /
function _refundHighestBid( uint48 listingId, Listings.Listing storage listing
function _refundHighestBid( uint48 listingId, Listings.Listing storage listing
30,949
449
// The interface for the Periodic Prize Strategy before award listener.This listener will be called immediately before the award is distributed.
interface BeforeAwardListenerInterface is IERC165Upgradeable { /// @notice Called immediately before the award is distributed function beforePrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external; }
interface BeforeAwardListenerInterface is IERC165Upgradeable { /// @notice Called immediately before the award is distributed function beforePrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external; }
27,469
10
// `msg.sender` approves `_addr` to spend `_value` tokens /_spender The address of the account able to transfer the tokens /_value The amount of wei to be approved for transfer / return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
13,212
36
// Update owner to deployer
owner = msg.sender;
owner = msg.sender;
15,398
43
// Owner => Avatar
mapping (address => address) public avatarOf;
mapping (address => address) public avatarOf;
34,925
14
// Raise error again from result if error exists
assembly { switch success
assembly { switch success
10,490
76
// Refund remaining balance to organizer
organizer.transfer(this.balance);
organizer.transfer(this.balance);
17,474
2
// signature ECDSA signature along with the mode [{mode}{v}, {r}, {s}]/ return Returns whether signature is from a specified user.
function isValidSignature(bytes32 hash, address signer, bytes32[3] memory signature) internal pure returns (bool) { return recoverAddr(hash, signature) == signer; }
function isValidSignature(bytes32 hash, address signer, bytes32[3] memory signature) internal pure returns (bool) { return recoverAddr(hash, signature) == signer; }
47,416
7
// Removes expired limit orders _orderIds The array of order IDs to remove. /
function cancelExpiredLimitOrders(uint256[] calldata _orderIds) external;
function cancelExpiredLimitOrders(uint256[] calldata _orderIds) external;
20,545
90
// Creates a new extension node. _key Key for the extension node, unprefixed. _value Value for the extension node.return _node New extension node with the given k/v pair. /
function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node )
function _makeExtensionNode( bytes memory _key, bytes memory _value ) private pure returns ( TrieNode memory _node )
37,955
145
// burns $SQUID from a holder from the holder of the $SQUID amount the amount of $SQUID to burn /
function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); }
function burn(address from, uint256 amount) external { require(controllers[msg.sender], "Only controllers can burn"); _burn(from, amount); }
21,071
42
// handle the case if user has not claimed even after vesting period is over or amount was not divisible
if (totalReleasableAmount > vestingSchedule.amount) totalReleasableAmount = vestingSchedule.amount; uint256 amountToRelease = totalReleasableAmount.minus(vestingSchedule.amountReleased); vestingSchedule.amountReleased = vestingSchedule.amountReleased.plus(amountToRelease);
if (totalReleasableAmount > vestingSchedule.amount) totalReleasableAmount = vestingSchedule.amount; uint256 amountToRelease = totalReleasableAmount.minus(vestingSchedule.amountReleased); vestingSchedule.amountReleased = vestingSchedule.amountReleased.plus(amountToRelease);
18,697
31
// Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], butwith `errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._ /
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
18,265
124
// Create application
project.workerEnrolNoApplication( campaign, application, _projectID, applicationCount ); applicationCount++; return applicationCount - 1;
project.workerEnrolNoApplication( campaign, application, _projectID, applicationCount ); applicationCount++; return applicationCount - 1;
1,512
123
// Guaranteed to run at least once because of the prior if statements.
while (pos != 0 && _isPricedLtOrEq(id, pos)) { old_pos = pos; pos = _rank[pos].prev; }
while (pos != 0 && _isPricedLtOrEq(id, pos)) { old_pos = pos; pos = _rank[pos].prev; }
39,553
120
// After modifying contract parameters, call this function to run internal consistency checks.
function validateContractParameters() internal view { // These upper bounds have been added per community request require(_burnRatePerTransferThousandth <= 50, "Error: Burn cannot be larger than 5%"); require(_interestRatePerBuyThousandth <= 50, "Error: Interest cannot be larger than 5%"); // This is to avoid an owner accident/misuse, if uniswap can reward a larger amount than a single buy+sell, // that would allow anyone to drain the Uniswap pool with a flash loan. // Since Uniswap fees are not considered, all Uniswap transactions are ultimately deflationary. require(_interestRatePerBuyThousandth <= _burnRatePerTransferThousandth.mul(2), "Error: Interest cannot exceed 2*Burn"); }
function validateContractParameters() internal view { // These upper bounds have been added per community request require(_burnRatePerTransferThousandth <= 50, "Error: Burn cannot be larger than 5%"); require(_interestRatePerBuyThousandth <= 50, "Error: Interest cannot be larger than 5%"); // This is to avoid an owner accident/misuse, if uniswap can reward a larger amount than a single buy+sell, // that would allow anyone to drain the Uniswap pool with a flash loan. // Since Uniswap fees are not considered, all Uniswap transactions are ultimately deflationary. require(_interestRatePerBuyThousandth <= _burnRatePerTransferThousandth.mul(2), "Error: Interest cannot exceed 2*Burn"); }
81,173
138
// src/FakeNewsNetworkInu.sol/ pragma solidity >=0.8.10; /
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract FakeNewsNetworkInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Fake News Network Inu", "FNN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xE0fC381f18c5A75DceB20aD2Da8fc96b4aB3c6a7); // set as marketing wallet devWallet = address(0xCf0088f2D787a572256cbcb28E04b01B51b18BBe); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */ /* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */ /* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */ /* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */ /* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */ /* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */ /* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */ contract FakeNewsNetworkInu is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Fake News Network Inu", "FNN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 3; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xE0fC381f18c5A75DceB20aD2Da8fc96b4aB3c6a7); // set as marketing wallet devWallet = address(0xCf0088f2D787a572256cbcb28E04b01B51b18BBe); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
61,780
4
// Mints new tokens and adds them to the specified address./to The address to mint tokens to./amount The amount of tokens to mint.
function mint( address to, uint256 amount
function mint( address to, uint256 amount
245
37
// Destroys a `value` amount of tokens of type `id` from `from`
* Emits a {TransferSingle} event. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `value` amount of tokens of type `id`. */ function _burn(address from, uint256 id, uint256 value) internal { if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value); _updateWithAcceptanceCheck(from, address(0), ids, values, ""); }
* Emits a {TransferSingle} event. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `value` amount of tokens of type `id`. */ function _burn(address from, uint256 id, uint256 value) internal { if (from == address(0)) { revert ERC1155InvalidSender(address(0)); } (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value); _updateWithAcceptanceCheck(from, address(0), ids, values, ""); }
14,283
101
// getCreator : NFT Creator조회/
function getCreator(uint256 id) external view returns (address) { return _tokens[id].creator; }
function getCreator(uint256 id) external view returns (address) { return _tokens[id].creator; }
24,227
56
// Assume the first option is the winner, and then change if another match has more votes
uint64 winner = optionsPerElection[electionId][0].matchId; uint256 mostVotes = 0; for (uint j = 0; j < optionsPerElection[electionId].length; j++) { if (voteTotals[optionsPerElection[electionId][j].matchId] > mostVotes) { winner = optionsPerElection[electionId][j].matchId; mostVotes = voteTotals[winner]; }
uint64 winner = optionsPerElection[electionId][0].matchId; uint256 mostVotes = 0; for (uint j = 0; j < optionsPerElection[electionId].length; j++) { if (voteTotals[optionsPerElection[electionId][j].matchId] > mostVotes) { winner = optionsPerElection[electionId][j].matchId; mostVotes = voteTotals[winner]; }
55,473
34
// get the amount of Papa received
uint256 amountOut = amounts[amounts.length - 1];
uint256 amountOut = amounts[amounts.length - 1];
11,412
17
// Digitalax Index contract /
contract DigitalaxIndex is Context { using SafeMath for uint256; using Address for address; // DigitalaxIndex Events event AuctionSetAdded(uint256 indexed sid, uint256[] tokenIds); event AuctionSetRemoved(uint256 indexed sid); event AuctionSetUpdated(uint256 indexed sid, uint256[] tokenIds); event DesignerSetAdded(uint256 indexed sid, uint256[] tokenIds); event DesignerSetRemoved(uint256 indexed sid); event DesignerSetUpdated(uint256 indexed sid, uint256[] tokenIds); event DesignerInfoUpdated(uint256 indexed designerId, string uri); // Structure for set of token ids struct TokenIdSet { uint256[] value; } // Access Controls DigitalaxAccessControls public accessControls; // Array for auction set TokenIdSet[] auctionSet; // Array for designer set TokenIdSet[] designerSet; // Mapping for designer info mapping(uint256 => string) public designerInfo; /** * @dev Constructor of DigitalaxIndex contract * @param _accessControls AccessControls */ constructor(DigitalaxAccessControls _accessControls) public { require(address(_accessControls) != address(0), "DigitalaxIndex: Invalid Access Controls"); accessControls = _accessControls; } /** * @dev Function to update access controls * @param _accessControls Address of the new access controls contract (Cannot be zero address) */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.updateAccessControls: Sender must be admin"); require(address(_accessControls) != address(0), "DigitalaxIndex.updateAccessControls: Zero Address"); accessControls = _accessControls; } /** * @dev View function for auction set * @param _sid Id of auction set */ function AuctionSet(uint256 _sid) external view returns (uint256[] memory tokenIds) { TokenIdSet memory set = auctionSet[_sid]; tokenIds = set.value; } /** * @dev View function for designer set * @param _sid Designer Id */ function DesignerSet(uint256 _sid) external view returns (uint256[] memory tokenIds) { TokenIdSet memory set = designerSet[_sid]; tokenIds = set.value; } /** * @dev Function for adding auction set * @param _tokenIds Array of token ids to be added */ function addAuctionSet(uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.addAuctionSet: Sender must be admin"); uint256 index = auctionSet.length; auctionSet.push(TokenIdSet(_tokenIds)); emit AuctionSetAdded(index, _tokenIds); } /** * @dev Funtion for removal of auction set * @param _sid Id of auction set */ function removeAuctionSet(uint256 _sid) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.removeAuctionSet: Sender must be admin"); TokenIdSet storage set = auctionSet[_sid]; delete set.value; emit AuctionSetRemoved(_sid); } /** * @dev Function for auction set update * @param _sid Id of auction set * @param _tokenIds Array of token ids to be updated */ function updateAuctionSet(uint256 _sid, uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.removeAuctionSet: Sender must be admin"); TokenIdSet storage set = auctionSet[_sid]; set.value = _tokenIds; emit AuctionSetUpdated(_sid, _tokenIds); } /** * @dev Function for adding designer token set * @param _tokenIds Array of token ids to be added */ function addDesignerSet(uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.addDesignerSet: Sender must be admin"); uint256 index = designerSet.length; designerSet.push(TokenIdSet(_tokenIds)); emit DesignerSetAdded(index, _tokenIds); } /** * @dev Funtion for removal of designer set * @param _sid Id of designer set */ function removeDesignerSet(uint256 _sid) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.removeDesignerSet: Sender must be admin"); TokenIdSet storage set = designerSet[_sid]; delete set.value; emit DesignerSetRemoved(_sid); } /** * @dev Function for designer set update * @param _sid Id of designer set * @param _tokenIds Array of token ids to be updated */ function updateDesignerSet(uint256 _sid, uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.updateDesignerSet: Sender must be admin"); TokenIdSet storage set = designerSet[_sid]; set.value = _tokenIds; emit DesignerSetUpdated(_sid, _tokenIds); } /** * @dev Function to update designer info * @param _designerId Designer Id * @param _uri IPFS uri for designer info */ function updateDesignerInfo(uint256 _designerId, string memory _uri) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.updateDesignerInfo: Sender must be admin"); designerInfo[_designerId] = _uri; emit DesignerInfoUpdated(_designerId, _uri); } }
contract DigitalaxIndex is Context { using SafeMath for uint256; using Address for address; // DigitalaxIndex Events event AuctionSetAdded(uint256 indexed sid, uint256[] tokenIds); event AuctionSetRemoved(uint256 indexed sid); event AuctionSetUpdated(uint256 indexed sid, uint256[] tokenIds); event DesignerSetAdded(uint256 indexed sid, uint256[] tokenIds); event DesignerSetRemoved(uint256 indexed sid); event DesignerSetUpdated(uint256 indexed sid, uint256[] tokenIds); event DesignerInfoUpdated(uint256 indexed designerId, string uri); // Structure for set of token ids struct TokenIdSet { uint256[] value; } // Access Controls DigitalaxAccessControls public accessControls; // Array for auction set TokenIdSet[] auctionSet; // Array for designer set TokenIdSet[] designerSet; // Mapping for designer info mapping(uint256 => string) public designerInfo; /** * @dev Constructor of DigitalaxIndex contract * @param _accessControls AccessControls */ constructor(DigitalaxAccessControls _accessControls) public { require(address(_accessControls) != address(0), "DigitalaxIndex: Invalid Access Controls"); accessControls = _accessControls; } /** * @dev Function to update access controls * @param _accessControls Address of the new access controls contract (Cannot be zero address) */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.updateAccessControls: Sender must be admin"); require(address(_accessControls) != address(0), "DigitalaxIndex.updateAccessControls: Zero Address"); accessControls = _accessControls; } /** * @dev View function for auction set * @param _sid Id of auction set */ function AuctionSet(uint256 _sid) external view returns (uint256[] memory tokenIds) { TokenIdSet memory set = auctionSet[_sid]; tokenIds = set.value; } /** * @dev View function for designer set * @param _sid Designer Id */ function DesignerSet(uint256 _sid) external view returns (uint256[] memory tokenIds) { TokenIdSet memory set = designerSet[_sid]; tokenIds = set.value; } /** * @dev Function for adding auction set * @param _tokenIds Array of token ids to be added */ function addAuctionSet(uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.addAuctionSet: Sender must be admin"); uint256 index = auctionSet.length; auctionSet.push(TokenIdSet(_tokenIds)); emit AuctionSetAdded(index, _tokenIds); } /** * @dev Funtion for removal of auction set * @param _sid Id of auction set */ function removeAuctionSet(uint256 _sid) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.removeAuctionSet: Sender must be admin"); TokenIdSet storage set = auctionSet[_sid]; delete set.value; emit AuctionSetRemoved(_sid); } /** * @dev Function for auction set update * @param _sid Id of auction set * @param _tokenIds Array of token ids to be updated */ function updateAuctionSet(uint256 _sid, uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.removeAuctionSet: Sender must be admin"); TokenIdSet storage set = auctionSet[_sid]; set.value = _tokenIds; emit AuctionSetUpdated(_sid, _tokenIds); } /** * @dev Function for adding designer token set * @param _tokenIds Array of token ids to be added */ function addDesignerSet(uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.addDesignerSet: Sender must be admin"); uint256 index = designerSet.length; designerSet.push(TokenIdSet(_tokenIds)); emit DesignerSetAdded(index, _tokenIds); } /** * @dev Funtion for removal of designer set * @param _sid Id of designer set */ function removeDesignerSet(uint256 _sid) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.removeDesignerSet: Sender must be admin"); TokenIdSet storage set = designerSet[_sid]; delete set.value; emit DesignerSetRemoved(_sid); } /** * @dev Function for designer set update * @param _sid Id of designer set * @param _tokenIds Array of token ids to be updated */ function updateDesignerSet(uint256 _sid, uint256[] calldata _tokenIds) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.updateDesignerSet: Sender must be admin"); TokenIdSet storage set = designerSet[_sid]; set.value = _tokenIds; emit DesignerSetUpdated(_sid, _tokenIds); } /** * @dev Function to update designer info * @param _designerId Designer Id * @param _uri IPFS uri for designer info */ function updateDesignerInfo(uint256 _designerId, string memory _uri) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxIndex.updateDesignerInfo: Sender must be admin"); designerInfo[_designerId] = _uri; emit DesignerInfoUpdated(_designerId, _uri); } }
39,982
19
// RACES /
function createRace(uint256 _cardId, uint256 _betAmount, uint256 pinkSlip) public payable isUnlocked { uint256 excess = msg.value.sub(_betAmount); require(_owns(msg.sender, TYPE_CAR, _cardId)); require(!carsMap[_cardId].locked); carsMap[_cardId].locked = true; racesMap[openRaceCount+finishedRaceCount].player1Data = _packPlayerData(msg.sender, _cardId); racesMap[openRaceCount+finishedRaceCount].metaData = _packRaceData(_betAmount, 0, pinkSlip, RACE_OPENED); openRaceCount++; emit RaceCreated(openRaceCount+finishedRaceCount, msg.sender, _cardId, _betAmount); _pay(msg.sender, excess); }
function createRace(uint256 _cardId, uint256 _betAmount, uint256 pinkSlip) public payable isUnlocked { uint256 excess = msg.value.sub(_betAmount); require(_owns(msg.sender, TYPE_CAR, _cardId)); require(!carsMap[_cardId].locked); carsMap[_cardId].locked = true; racesMap[openRaceCount+finishedRaceCount].player1Data = _packPlayerData(msg.sender, _cardId); racesMap[openRaceCount+finishedRaceCount].metaData = _packRaceData(_betAmount, 0, pinkSlip, RACE_OPENED); openRaceCount++; emit RaceCreated(openRaceCount+finishedRaceCount, msg.sender, _cardId, _betAmount); _pay(msg.sender, excess); }
11,751
28
// slength can contain both the length and contents of the array if length < 32 bytes so let's prepare for that v. http:solidity.readthedocs.io/en/latest/miscellaneous.htmllayout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32)) case 2 {
switch add(lt(slength, 32), lt(newlength, 32)) case 2 {
24,343
0
// See https:docs.openzeppelin.com/contracts/4.x/api/accessIAccessControl
interface Roleable { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousRoleAdmin, bytes32 indexed newRoleAdmin); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; }
interface Roleable { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousRoleAdmin, bytes32 indexed newRoleAdmin); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; }
18,859