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
122
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; }
for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; }
82,912
47
// Division of two int256 variables and fails on overflow. /
function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; }
function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; }
3,834
41
// Guns
function createGun(uint256 _gunId, string _name, uint256 _min, uint256 _max, uint256 _radius, uint256 _recharge, uint256 _ability, uint256 _price, uint256 _durability) public onlyOwnerOfStorage { mI.createGun(_gunId); stringStorage[_b1("guns", _gunId, "name")] = _name; uintStorage[_b1("guns", _gunId, "min")] = _min; uintStorage[_b1("guns", _gunId, "max")] = _max; uintStorage[_b1("guns", _gunId, "radius")] = _radius; uintStorage[_b1("guns", _gunId, "recharge")] = _recharge; uintStorage[_b1("guns", _gunId, "ability")] = _ability; uintStorage[_b1("guns", _gunId, "price")] = _price; uintStorage[_b1("guns", _gunId, "durability")] = _durability; }
function createGun(uint256 _gunId, string _name, uint256 _min, uint256 _max, uint256 _radius, uint256 _recharge, uint256 _ability, uint256 _price, uint256 _durability) public onlyOwnerOfStorage { mI.createGun(_gunId); stringStorage[_b1("guns", _gunId, "name")] = _name; uintStorage[_b1("guns", _gunId, "min")] = _min; uintStorage[_b1("guns", _gunId, "max")] = _max; uintStorage[_b1("guns", _gunId, "radius")] = _radius; uintStorage[_b1("guns", _gunId, "recharge")] = _recharge; uintStorage[_b1("guns", _gunId, "ability")] = _ability; uintStorage[_b1("guns", _gunId, "price")] = _price; uintStorage[_b1("guns", _gunId, "durability")] = _durability; }
79,636
92
// Ensure the ExchangeCircuitBreaker contract can suspend synths - see SIP-65;
systemstatus_i.updateAccessControl("Synth", new_ExchangeCircuitBreaker_contract, true, false);
systemstatus_i.updateAccessControl("Synth", new_ExchangeCircuitBreaker_contract, true, false);
38,034
3
// Returns the average of two numbers. The result is rounded towardszero. /
function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); }
function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); }
9,812
37
// Initializes the contract setting the _ownerAddress as the initial owner. /
constructor(address _ownerAddress) public { owner = _ownerAddress; UserStruct memory userstruct; userstruct = UserStruct({ isExist: true, id: 1, currentLevel: NUMBEROFLEVELS, referer: 0, referalEarnings: 0, poolEarned:0, referals: new address[](0) }); users[owner] = userstruct; userList[1] = owner; // Owner active 10levels for (uint i = 1; i <= NUMBEROFLEVELS; i++) { users[owner].activeLevel[i] = true; } // Levels levelprice levelPrice[1] = 0.05 ether; for (uint i = 2; i <= NUMBEROFLEVELS; i++) { levelPrice[i] = levelPrice[i - 1] * 2; } // Minimum referal count by each level referalUpline[1] = 3; for (uint i = 2; i <= NUMBEROFLEVELS; i++) { referalUpline[i] = referalUpline[i - 1] + 1; } }
constructor(address _ownerAddress) public { owner = _ownerAddress; UserStruct memory userstruct; userstruct = UserStruct({ isExist: true, id: 1, currentLevel: NUMBEROFLEVELS, referer: 0, referalEarnings: 0, poolEarned:0, referals: new address[](0) }); users[owner] = userstruct; userList[1] = owner; // Owner active 10levels for (uint i = 1; i <= NUMBEROFLEVELS; i++) { users[owner].activeLevel[i] = true; } // Levels levelprice levelPrice[1] = 0.05 ether; for (uint i = 2; i <= NUMBEROFLEVELS; i++) { levelPrice[i] = levelPrice[i - 1] * 2; } // Minimum referal count by each level referalUpline[1] = 3; for (uint i = 2; i <= NUMBEROFLEVELS; i++) { referalUpline[i] = referalUpline[i - 1] + 1; } }
28,106
280
// Test that matron and sire are a valid mating pair.
require( _isValidMatingPair(matron, _matronId, sire, _sireId), "CryptoAlpaca: Matron and Sire are not valid mating pair" );
require( _isValidMatingPair(matron, _matronId, sire, _sireId), "CryptoAlpaca: Matron and Sire are not valid mating pair" );
52,503
21
// return The Address of the implementation. /
function _implementation() internal virtual view returns (address);
function _implementation() internal virtual view returns (address);
17,259
48
// permanently lock the first MINIMUM_LIQUIDITY tokens
_mint(address(0), MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY);
19,004
43
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
Checkpoint[] totalSupplyHistory;
49,062
84
// Subtract stake amount from regular token balance
balances[_user] = balances[_user].sub(_value);
balances[_user] = balances[_user].sub(_value);
65,741
10
// Pay keeper some amount in the collateral token for the perpetual pools market to Address of the pool keeper to pay amount Amount to pay the pool keeperreturn Whether the keeper is going to be paid; false if the amount exceeds the balances of thelong and short pool, and true if the keeper can successfully be paid out /
function payKeeperFromBalances(address to, uint256 amount) external override onlyKeeper onlyUnpaused returns (bool)
function payKeeperFromBalances(address to, uint256 amount) external override onlyKeeper onlyUnpaused returns (bool)
38,405
6
// Virtual data set, ordering not guaranteed because removal just replaces position with last item and decreases collection size /
constructor(bytes32 _name, address _registry, uint16 _traitId) { name = _name; ECRegistry = IECRegistry(_registry); traitId = _traitId; }
constructor(bytes32 _name, address _registry, uint16 _traitId) { name = _name; ECRegistry = IECRegistry(_registry); traitId = _traitId; }
55,309
42
// Get the number of tokens held by the `account` account The address of the account to get the balance ofreturn The number of tokens held /
function balanceOf(address account) external view returns (uint256) { return balances[account]; }
function balanceOf(address account) external view returns (uint256) { return balances[account]; }
3,466
2
// requires a fee for the owner
modifier fee(uint256 amount) { require(msg.value >= amount, "not enough payment for the fee"); _; owner.transfer(amount); emit feePaid(owner, amount); }
modifier fee(uint256 amount) { require(msg.value >= amount, "not enough payment for the fee"); _; owner.transfer(amount); emit feePaid(owner, amount); }
25,661
37
// function to modify whats being voted on and the description
function changeVotingDetails(string memory _voteDetailsName, string memory _voteDetailsDescription) public votingShouldNotHaveStarted() onlyOwner()
function changeVotingDetails(string memory _voteDetailsName, string memory _voteDetailsDescription) public votingShouldNotHaveStarted() onlyOwner()
17,486
164
// Emit when a draw has started. rngRequestIddraw id rngLockBlockBlock when draw becomes invalid /
event DrawStarted(uint32 indexed rngRequestId, uint32 rngLockBlock);
event DrawStarted(uint32 indexed rngRequestId, uint32 rngLockBlock);
84,554
16
// Prevent a contract function from being reentrant-called. /
modifier reentrancyGuard() { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; }
modifier reentrancyGuard() { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; }
879
38
// Transfers '_value' in aToken to the '_to' address/_to The recipient address/_value The amount of wei to transfer
function transfer(address _to, uint256 _value) public returns (bool success) { /* Check if sender has balance and for overflows */ require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]); /* Check if amount is nonzero */ require(_value > 0); /* Add and subtract new balances */ balances[msg.sender] -= _value; balances[_to] += _value; /* Notify anyone listening that this transfer took place */ emit Transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) public returns (bool success) { /* Check if sender has balance and for overflows */ require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]); /* Check if amount is nonzero */ require(_value > 0); /* Add and subtract new balances */ balances[msg.sender] -= _value; balances[_to] += _value; /* Notify anyone listening that this transfer took place */ emit Transfer(msg.sender, _to, _value); return true; }
5,450
115
// Returns all tokens registered with the Allocator.return the tokens /
function tokens() external view override returns (IERC20[] memory) { return _tokens; }
function tokens() external view override returns (IERC20[] memory) { return _tokens; }
63,701
19
// via https:github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) public view returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) public view returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
41,984
67
// The current system prices of ETH and PXL, for which unsold Properties are listed for sale at
uint256 systemSalePriceETH; uint256 systemSalePricePXL; uint8 systemPixelIncreasePercent; uint8 systemPriceIncreaseStep; uint16 systemETHStepTally; uint16 systemPXLStepTally; uint16 systemETHStepCount; uint16 systemPXLStepCount;
uint256 systemSalePriceETH; uint256 systemSalePricePXL; uint8 systemPixelIncreasePercent; uint8 systemPriceIncreaseStep; uint16 systemETHStepTally; uint16 systemPXLStepTally; uint16 systemETHStepCount; uint16 systemPXLStepCount;
17,308
14
// Applying the mutation color via a mask
bytes32 nullMask = bytes32(~(0xFFFFFF << (byteIndex * 8))); bytes32 valueMask = bytes32(mutationColor << (byteIndex * 8)); image[iWord] = (image[iWord] & nullMask) | valueMask;
bytes32 nullMask = bytes32(~(0xFFFFFF << (byteIndex * 8))); bytes32 valueMask = bytes32(mutationColor << (byteIndex * 8)); image[iWord] = (image[iWord] & nullMask) | valueMask;
2,078
1
// Mint token with the supplied tokenId if it is currently available. /
function mint(uint256 tokenId) external;
function mint(uint256 tokenId) external;
28,146
54
// contract ProjectMngr wird in Company eingebunden.. verwaltet das Projekte.. Projekte sind einmalige Budget Contracts die zum erledigendiverser Aufgaben angelegt werden.
contract ProjectMngr is Board { // //adding Projects... // address private addProjectBy = 0; address private newProjectAddr; uint private newProjectBudget; Project[] public Projects; function _projectAddNew(address _addr, uint _budget) public onlybyboardmember { if(addProjectBy != 0) throw; if(BudgetProject < _budget) return; newProjectBudget = _budget; addProjectBy = msg.sender; newProjectAddr = _addr; } function _projectCommitNew(address _addr) public onlybyboardmember { if(msg.sender==addProjectBy) throw; //no self commit if(newProjectAddr != _addr) throw; Project myProject = Project(newProjectAddr); myProject.setCompany(); bool res = myProject.send(newProjectBudget); Projects.push(myProject); addProjectBy = 0; } function _projectCancelNew() public onlybyboardmember { addProjectBy = 0; } }
contract ProjectMngr is Board { // //adding Projects... // address private addProjectBy = 0; address private newProjectAddr; uint private newProjectBudget; Project[] public Projects; function _projectAddNew(address _addr, uint _budget) public onlybyboardmember { if(addProjectBy != 0) throw; if(BudgetProject < _budget) return; newProjectBudget = _budget; addProjectBy = msg.sender; newProjectAddr = _addr; } function _projectCommitNew(address _addr) public onlybyboardmember { if(msg.sender==addProjectBy) throw; //no self commit if(newProjectAddr != _addr) throw; Project myProject = Project(newProjectAddr); myProject.setCompany(); bool res = myProject.send(newProjectBudget); Projects.push(myProject); addProjectBy = 0; } function _projectCancelNew() public onlybyboardmember { addProjectBy = 0; } }
14,983
326
// Calculate fee in underlyings and send them to feeAddressamount : in idleTokens redeemed : in underlying currPrice : current idleToken pricereturn : net value in underlying /
function _getFee(uint256 amount, uint256 redeemed, uint256 currPrice) internal returns (uint256) { uint256 avgPrice = userAvgPrices[msg.sender]; if (currPrice < avgPrice) { return redeemed; } // 10**23 -> ONE_18 * FULL_ALLOC uint256 feeDue = amount.mul(currPrice.sub(avgPrice)).mul(fee).div(10**23); _transferTokens(token, feeAddress, feeDue); return redeemed.sub(feeDue); }
function _getFee(uint256 amount, uint256 redeemed, uint256 currPrice) internal returns (uint256) { uint256 avgPrice = userAvgPrices[msg.sender]; if (currPrice < avgPrice) { return redeemed; } // 10**23 -> ONE_18 * FULL_ALLOC uint256 feeDue = amount.mul(currPrice.sub(avgPrice)).mul(fee).div(10**23); _transferTokens(token, feeAddress, feeDue); return redeemed.sub(feeDue); }
61,614
24
// Allows any user to get his eth refunded before the purchase is made or after approx. 20 days in case the devs refund the eth.
function refund_me() { if (bought_tokens) { // Only allow refunds when the tokens have been bought if the minimum refund block has been reached. if (block.number < min_refund_block) throw; } // Store the user's balance prior to withdrawal in a temporary variable. uint256 eth_to_withdraw = balances[msg.sender]; // Update the user's balance prior to sending ETH to prevent recursive call. balances[msg.sender] = 0; // Return the user's funds. Throws on failure to prevent loss of funds. msg.sender.transfer(eth_to_withdraw); }
function refund_me() { if (bought_tokens) { // Only allow refunds when the tokens have been bought if the minimum refund block has been reached. if (block.number < min_refund_block) throw; } // Store the user's balance prior to withdrawal in a temporary variable. uint256 eth_to_withdraw = balances[msg.sender]; // Update the user's balance prior to sending ETH to prevent recursive call. balances[msg.sender] = 0; // Return the user's funds. Throws on failure to prevent loss of funds. msg.sender.transfer(eth_to_withdraw); }
36,689
20
// Check that the NFT is for sale.
require( idToMarketItem[tokenId].active == true, "This NFT is not for sale." );
require( idToMarketItem[tokenId].active == true, "This NFT is not for sale." );
25,869
11
// Returns the underlying token address from the joinAddr/For eth based collateral returns 0xEee... not weth addr/_joinAddr Join address to check
function getTokenFromJoin(address _joinAddr) internal view returns (address) { // if it's dai_join_addr don't check gem() it will fail, return dai addr if (_joinAddr == DAI_JOIN_ADDR) { return DAI_ADDR; } return address(IJoin(_joinAddr).gem()); }
function getTokenFromJoin(address _joinAddr) internal view returns (address) { // if it's dai_join_addr don't check gem() it will fail, return dai addr if (_joinAddr == DAI_JOIN_ADDR) { return DAI_ADDR; } return address(IJoin(_joinAddr).gem()); }
45,728
91
// Return the stored Borrow data for a given LoanReturn the Borrow data for a given Loan_loanAddress Address of the palLoan Composants of a Borrow struct/
function getBorrowData(address _loanAddress) external view override returns( address _borrower, address _delegatee, address _loan, uint256 _palLoanTokenId, uint _amount, address _underlying, uint _feesAmount, uint _feesUsed, uint _startBlock,
function getBorrowData(address _loanAddress) external view override returns( address _borrower, address _delegatee, address _loan, uint256 _palLoanTokenId, uint _amount, address _underlying, uint _feesAmount, uint _feesUsed, uint _startBlock,
38,646
35
// send minting tokens for array of adresses
function multisend(address[] recipients, uint256 value) onlyOwner public { for (uint256 i = 0; i < recipients.length; i++) { mintToken(recipients[i], value); } }
function multisend(address[] recipients, uint256 value) onlyOwner public { for (uint256 i = 0; i < recipients.length; i++) { mintToken(recipients[i], value); } }
49,658
157
// Important: Updates the token and clears the strategy!
token = IERC20(IMigrator(migrator).get());
token = IERC20(IMigrator(migrator).get());
16,076
128
// The following function should be used to substract amounts from the current balancestate, if the pending withdrawRequests are not considered and should not effectively reducethe available balance.For example, the reversion of trades from a previous batch-solution do notneed to consider withdrawRequests. This is the case as withdraws are blocked for onebatch for accounts having credited funds in a previous submission.PendingWithdraws must also be ignored since otherwise for the reversion of trades,a solution reversion could be blocked: A bigger withdrawRequest could set the return value ofgetBalance(user, token) to zero, although the user was just credited tokens inthe last submission. In this
function subtractBalanceUnchecked( address user, address token, uint256 amount
function subtractBalanceUnchecked( address user, address token, uint256 amount
26,191
56
// sqrtRatioLowerX96 = state.sqrtRatioLowerX96
sqrtRatioLowerX96 := mload(add(state, 0xa0))
sqrtRatioLowerX96 := mload(add(state, 0xa0))
24,152
176
// `_isValidDAO` since DAOs can be disabled.
require(_isValidDAO[daoAddress] != UNTRACKED_DAO, "DAO not tracked");
require(_isValidDAO[daoAddress] != UNTRACKED_DAO, "DAO not tracked");
29,266
6
// after the 90 days period, the contract cannot add new minters anymore/ and this can be called to remove it from the list of minters,/ although this will in practice not make a difference
function shutdown() external { require(block.timestamp >= deployedAt + ACTIVE_TIME, "EmergencyMinter: still active"); torus.renounceMinterRights(); emit Shutdown(); }
function shutdown() external { require(block.timestamp >= deployedAt + ACTIVE_TIME, "EmergencyMinter: still active"); torus.renounceMinterRights(); emit Shutdown(); }
12,505
55
// check current position
uint256 currentCollatRatio = _getCollatRatio(deposits, borrows);
uint256 currentCollatRatio = _getCollatRatio(deposits, borrows);
623
36
// return "Nocturnal Bank";
return s.bankName;
return s.bankName;
17,875
32
// Takes a snapshot of the registry for use when rebalancingproposeRebalance is callable multiple times, as long as there's enough time left /
function proposeRebalance() public onlyDuringValidPeriod(FN.PROPOSE)
function proposeRebalance() public onlyDuringValidPeriod(FN.PROPOSE)
44,736
47
// Atomically increases the allowance granted to `spender` by the caller.
* This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; }
* This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; }
23,186
124
// Notifies the controller about a transfer, for this EarlyTokenSale all/ transfers are allowed by default and no extra notifications are needed/_from The origin of the transfer/_to The destination of the transfer/_amount The amount of the transfer/ return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool success) { if ( _from == vaultAddress ) { return true; } return false; }
function onTransfer(address _from, address _to, uint _amount) returns(bool success) { if ( _from == vaultAddress ) { return true; } return false; }
28,099
5
// Returns the bep token owner. /
function getOwner() external view returns (address);
function getOwner() external view returns (address);
6,822
472
// Cumulative index at credit account opening
uint256 public override cumulativeIndexAtOpen;
uint256 public override cumulativeIndexAtOpen;
28,800
50
// Gets the Nickname for an Account Address /
function getAccountNickname(address _playerAddress) public view returns (string) { return playerData_[_playerAddress].name; }
function getAccountNickname(address _playerAddress) public view returns (string) { return playerData_[_playerAddress].name; }
28,222
30
// Token amount set as share
uint256 private _share = 1000000000000000;
uint256 private _share = 1000000000000000;
48,538
45
// Endpoint to withdraw payouts
function withdraw(uint112 amount) public { updatePayout(msg.sender); require(amount > minWithdraw, "Minimum Withdrawal amount not met"); require(users[msg.sender].payout >= amount, "Not enough payout available"); uint112 transfer = amount * 19 / 20; users[msg.sender].payout -= amount; payable(msg.sender).transfer(transfer); payable(owner()).transfer(amount - transfer); emit Withdraw(msg.sender, amount); }
function withdraw(uint112 amount) public { updatePayout(msg.sender); require(amount > minWithdraw, "Minimum Withdrawal amount not met"); require(users[msg.sender].payout >= amount, "Not enough payout available"); uint112 transfer = amount * 19 / 20; users[msg.sender].payout -= amount; payable(msg.sender).transfer(transfer); payable(owner()).transfer(amount - transfer); emit Withdraw(msg.sender, amount); }
17,056
298
// Get balance of every protocol implemented
tokenAddresses = new address[](allAvailableTokens.length); amounts = new uint256[](allAvailableTokens.length); address currentToken; uint256 currTokenPrice; for (uint256 i = 0; i < allAvailableTokens.length; i++) { currentToken = allAvailableTokens[i]; tokenAddresses[i] = currentToken; currTokenPrice = ILendingProtocol(protocolWrappers[currentToken]).getPriceInToken();
tokenAddresses = new address[](allAvailableTokens.length); amounts = new uint256[](allAvailableTokens.length); address currentToken; uint256 currTokenPrice; for (uint256 i = 0; i < allAvailableTokens.length; i++) { currentToken = allAvailableTokens[i]; tokenAddresses[i] = currentToken; currTokenPrice = ILendingProtocol(protocolWrappers[currentToken]).getPriceInToken();
10,529
13
// Allow storage slots to be manually updated /
function updateSlot(bytes32 slot, bytes32 value) external { require(msg.sender == ownerAddress); assembly { sstore(slot, value) } }
function updateSlot(bytes32 slot, bytes32 value) external { require(msg.sender == ownerAddress); assembly { sstore(slot, value) } }
31,646
1
// InitializableUpgradeabilityProxy Extends BaseUpgradeabilityProxy with an initializer for initializingimplementation and init data. /
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } }
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } }
33,514
28
// mapping of buyout bidders and their respective unsettled bids
mapping(address => uint256) public unsettledBids; mapping(address => uint256) public nonces;
mapping(address => uint256) public unsettledBids; mapping(address => uint256) public nonces;
8,691
48
// Third-party initiates transfer of token from address _from to address _to/_from The address for the token to be transferred from./_to The address for the token to be transferred to./_tokenId The ID of the Token that can be transferred if this call succeeds./Required for ERC-721 compliance.
function transferFrom( address _from, address _to, uint256 _tokenId
function transferFrom( address _from, address _to, uint256 _tokenId
12,690
24
// This is the function we call
function flashLoan(uint loanAmount) external { /* The flash loan functionality in dydx is predicated by their "operate" function, which takes a list of operations to execute, and defers validating the state of things until it's done executing them. We thus create three operations, a Withdraw (which loans us the funds), a Call (which invokes the callFunction method on this contract), and a Deposit (which repays the loan, plus the 2 wei fee), and pass them all to "operate". Note that the Deposit operation will invoke the transferFrom to pay the loan (or whatever amount it was initialised with) back to itself, there is no need to pay it back explicitly. The loan must be given as an ERC-20 token, so WETH is used instead of ETH. Other currencies (DAI, USDC) are also available, their index can be looked up by calling getMarketTokenAddress on the solo margin contract, and set as the primaryMarketId in the Withdraw and Deposit definitions. */ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: loanAmount // Amount to borrow }), primaryMarketId: 0, // WETH secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); operations[1] = Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: abi.encode( // Replace or add any additional variables that you want // to be available to the receiver function msg.sender, loanAmount ) }); operations[2] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: loanAmount + 2 // Repayment amount with 2 wei fee }), primaryMarketId: 0, // WETH secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = Account.Info({owner: address(this), number: 1}); soloMargin.operate(accountInfos, operations); }
function flashLoan(uint loanAmount) external { /* The flash loan functionality in dydx is predicated by their "operate" function, which takes a list of operations to execute, and defers validating the state of things until it's done executing them. We thus create three operations, a Withdraw (which loans us the funds), a Call (which invokes the callFunction method on this contract), and a Deposit (which repays the loan, plus the 2 wei fee), and pass them all to "operate". Note that the Deposit operation will invoke the transferFrom to pay the loan (or whatever amount it was initialised with) back to itself, there is no need to pay it back explicitly. The loan must be given as an ERC-20 token, so WETH is used instead of ETH. Other currencies (DAI, USDC) are also available, their index can be looked up by calling getMarketTokenAddress on the solo margin contract, and set as the primaryMarketId in the Withdraw and Deposit definitions. */ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: loanAmount // Amount to borrow }), primaryMarketId: 0, // WETH secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); operations[1] = Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: abi.encode( // Replace or add any additional variables that you want // to be available to the receiver function msg.sender, loanAmount ) }); operations[2] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: loanAmount + 2 // Repayment amount with 2 wei fee }), primaryMarketId: 0, // WETH secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = Account.Info({owner: address(this), number: 1}); soloMargin.operate(accountInfos, operations); }
11,259
81
// Check for approved spend
if (_from != msg.sender) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; }
if (_from != msg.sender) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value; }
19,512
44
// Remove sacrificed snails, increase req
hatcherySnail[msg.sender] = hatcherySnail[msg.sender].sub(spiderReq); spiderReq = spiderReq.mul(2);
hatcherySnail[msg.sender] = hatcherySnail[msg.sender].sub(spiderReq); spiderReq = spiderReq.mul(2);
76,750
14
// cap == 0 means revoking bridge role
bridges[_bridge].cap = _cap; emit BridgeSupplyCapUpdated(_bridge, _cap);
bridges[_bridge].cap = _cap; emit BridgeSupplyCapUpdated(_bridge, _cap);
19,766
286
// holds the user address index corresponds to the lockup. lockupName => userAddress => userIndex
mapping (bytes32 => mapping(address => uint256)) internal lockupToUserIndex; bytes32[] lockupArray;
mapping (bytes32 => mapping(address => uint256)) internal lockupToUserIndex; bytes32[] lockupArray;
47,921
546
// underlying stable token we are holding and valuing treasury with
IERC20 private STABLEC;
IERC20 private STABLEC;
49,102
7
// Returns whether the given trading bot can be updated.Returns false if the bot is not found.Either [_index] or [_tradingBot] is used for getting the data.If [_index] is 0, then [_tradingBot] is used.If [_tradingBot] is address(0), then [_index] is used.If [_index] and [_tradingBot] are both valid values, then [_index] is used._index Index of the trading bot._tradingBot Address of the trading bot. return address Whether the trading bot can be updated./
function canUpdate(uint256 _index, address _tradingBot) external view override returns (bool) { if (_index == 0) { return ITradingBot(_tradingBot).canUpdate(); } if (_tradingBot == address(0)) { return ITradingBot(tradingBotAddresses[_index]).canUpdate(); } return false; }
function canUpdate(uint256 _index, address _tradingBot) external view override returns (bool) { if (_index == 0) { return ITradingBot(_tradingBot).canUpdate(); } if (_tradingBot == address(0)) { return ITradingBot(tradingBotAddresses[_index]).canUpdate(); } return false; }
21,024
4
// Returns the number of games. 게임의 개수를 반환합니다.
function getGameCount() external view returns (uint);
function getGameCount() external view returns (uint);
21,205
12
// Create payable 1: Custodian --> Maker
_createPayable(1, 0, address(_issuanceEscrow), makerAddress, _bip.collateralTokenAddress, _bip.collateralAmount, _issuanceProperty.issuanceDueTimestamp);
_createPayable(1, 0, address(_issuanceEscrow), makerAddress, _bip.collateralTokenAddress, _bip.collateralAmount, _issuanceProperty.issuanceDueTimestamp);
39,158
35
// the The awardable balance
uint256 internal _currentAwardBalance;
uint256 internal _currentAwardBalance;
16,358
19
// Set tournament status canceled
_tournament.tournamentCanceled = true;
_tournament.tournamentCanceled = true;
7,383
2
// IHashflowMessenger/Victor Ionescu/ This interface should be implemented by any contractthat is to be used for X-Chain Message passing. /
interface IHashflowXChainMessenger { struct XChainQuote { uint16 srcChainId; uint16 dstChainId; address srcPool; bytes32 dstPool; address srcExternalAccount; bytes32 dstExternalAccount; address trader; bytes32 dstTrader; address baseToken; bytes32 quoteToken; uint256 baseTokenAmount; uint256 quoteTokenAmount; bytes32 txid; } struct XChainTradePayload { uint16 dstChainId; bytes32 txid; bytes32 srcPool; bytes32 dstPool; bytes32 dstExternalAccount; bytes32 quoteToken; bytes32 dstTrader; uint256 quoteTokenAmount; bytes32 permissionedRelayer; bytes32 srcCaller; bytes32 dstContract; bytes dstContractCalldata; } /// @notice Emitted when an associated IHashflowMessenger on a source chain changes. /// @param chainId The Hashflow Chain ID. /// @param remoteAddress The address of the remote, pre-padded to 32 bytes. event UpdateXChainRemoteAddress(uint16 chainId, bytes remoteAddress); /// @notice The Hashflow Chain ID for this chain. function hChainId() external view returns (uint16); /// @notice Returns the Hashflow Router. function router() external view returns (address); /// @notice Returns the registered remote for a Hashflow Chain ID. /// @param hChainId The foreign Hashflow Chain ID. function xChainRemotes(uint16 hChainId) external view returns (bytes memory); /// @notice Send X-Chain trade fill message. /// @param xChainQuote Quote object. /// @param caller The caller of the X-Chain trade. /// @param dstContract The contract to call on the destination chain. /// @param dstCalldata The calldata to pass to the contract. function tradeXChain( XChainQuote memory xChainQuote, address caller, bytes32 dstContract, bytes memory dstCalldata ) external payable; /// @notice Updates the associated IHashflowMessenger address on a different chain. /// @param hChainId The Hashflow Chain ID of the peer chain. /// @param remoteAddress The address of the IHashflowMessenger on the peer chain. function updateXChainRemoteAddress( uint16 hChainId, bytes calldata remoteAddress ) external; /// @notice Withdraws excess fees to the owner. function withdrawFunds() external; }
interface IHashflowXChainMessenger { struct XChainQuote { uint16 srcChainId; uint16 dstChainId; address srcPool; bytes32 dstPool; address srcExternalAccount; bytes32 dstExternalAccount; address trader; bytes32 dstTrader; address baseToken; bytes32 quoteToken; uint256 baseTokenAmount; uint256 quoteTokenAmount; bytes32 txid; } struct XChainTradePayload { uint16 dstChainId; bytes32 txid; bytes32 srcPool; bytes32 dstPool; bytes32 dstExternalAccount; bytes32 quoteToken; bytes32 dstTrader; uint256 quoteTokenAmount; bytes32 permissionedRelayer; bytes32 srcCaller; bytes32 dstContract; bytes dstContractCalldata; } /// @notice Emitted when an associated IHashflowMessenger on a source chain changes. /// @param chainId The Hashflow Chain ID. /// @param remoteAddress The address of the remote, pre-padded to 32 bytes. event UpdateXChainRemoteAddress(uint16 chainId, bytes remoteAddress); /// @notice The Hashflow Chain ID for this chain. function hChainId() external view returns (uint16); /// @notice Returns the Hashflow Router. function router() external view returns (address); /// @notice Returns the registered remote for a Hashflow Chain ID. /// @param hChainId The foreign Hashflow Chain ID. function xChainRemotes(uint16 hChainId) external view returns (bytes memory); /// @notice Send X-Chain trade fill message. /// @param xChainQuote Quote object. /// @param caller The caller of the X-Chain trade. /// @param dstContract The contract to call on the destination chain. /// @param dstCalldata The calldata to pass to the contract. function tradeXChain( XChainQuote memory xChainQuote, address caller, bytes32 dstContract, bytes memory dstCalldata ) external payable; /// @notice Updates the associated IHashflowMessenger address on a different chain. /// @param hChainId The Hashflow Chain ID of the peer chain. /// @param remoteAddress The address of the IHashflowMessenger on the peer chain. function updateXChainRemoteAddress( uint16 hChainId, bytes calldata remoteAddress ) external; /// @notice Withdraws excess fees to the owner. function withdrawFunds() external; }
29,441
96
// BingoGame Betting token for Bingo Game /
contract BingoTokenContract is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 100_000_000 * 10 ** 8; // Percent of the initial supply that will go to the LP uint constant LP_BPS = 9000; // Percent of the initial supply that will go to marketing uint constant MARKETING_BPS = 10_000 - LP_BPS; // // The tax to deduct, in basis points // uint public buyTaxBps = 500; uint public sellTaxBps = 500; // bool isSellingCollectedTaxes; event AntiBotEngaged(); event AntiBotDisengaged(); event StealthLaunchEngaged(); address public bingoContractAddress; bool public isLaunched; address public gameFeeWallet; address public marketingWallet; address public revenueWallet; bool public engagedOnce; bool public disengagedOnce; constructor() ERC20("BINGO Game Betting Token", "BINGO", 8) { if (isGoerli()) { router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); } else if (isSepolia()) { router = IUniswapV2Router02( 0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008 ); } else { require(block.chainid == 1, "expected mainnet"); router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); } factory = IUniswapV2Factory(router.factory()); // Approve infinite spending by DEX, to sell tokens collected via tax. allowance[address(this)][address(router)] = type(uint).max; emit Approval(address(this), address(router), type(uint).max); isLaunched = false; } modifier lockTheSwap() { isSellingCollectedTaxes = true; _; isSellingCollectedTaxes = false; } modifier onlyTestnet() { require(isTestnet(), "not testnet"); _; } receive() external payable {} fallback() external payable {} function burn(uint amount) external { _burn(msg.sender, amount); } /** * @dev Allow minting on testnet so I don't have to deal with * buying from Uniswap. * @param amount the number of tokens to mint */ function mint(uint amount) external onlyTestnet { _mint(address(msg.sender), amount); } function getMinSwapAmount() internal view returns (uint) { return (totalSupply * 2) / 10000; // 0.02% } function isGoerli() public view returns (bool) { return block.chainid == 5; } function isSepolia() public view returns (bool) { return block.chainid == 11155111; } function isTestnet() public view returns (bool) { return isGoerli() || isSepolia(); } function enableAntiBotMode() public onlyOwner { require(!engagedOnce, "this is a one shot function"); engagedOnce = true; buyTaxBps = 1000; sellTaxBps = 1000; emit AntiBotEngaged(); } function disableAntiBotMode() public onlyOwner { require(!disengagedOnce, "this is a one shot function"); disengagedOnce = true; buyTaxBps = 500; sellTaxBps = 500; emit AntiBotDisengaged(); } /** * @dev Does the same thing as a max approve for the roulette * contract, but takes as input a secret that the bot uses to * verify ownership by a Telegram user. * @param secret The secret that the bot is expecting. * @return true */ function connectAndApprove(uint32 secret) external returns (bool) { address pwner = _msgSender(); allowance[pwner][bingoContractAddress] = type(uint).max; emit Approval(pwner, bingoContractAddress, type(uint).max); return true; } function setBignoContractAddress(address a) public onlyOwner { require(a != address(0), "null address"); bingoContractAddress = a; } function setGameFeeWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); gameFeeWallet = wallet; } function setMarketingWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); marketingWallet = wallet; } function setRevenueWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); revenueWallet = wallet; } function stealthLaunch() external payable onlyOwner { require(!isLaunched, "already launched"); require(gameFeeWallet != address(0), "null address"); require(marketingWallet != address(0), "null address"); require(revenueWallet != address(0), "null address"); require(bingoContractAddress != address(0), "null address"); isLaunched = true; _mint(address(this), (INITIAL_SUPPLY * LP_BPS) / 10_000); router.addLiquidityETH{value: msg.value}( address(this), balanceOf[address(this)], 0, 0, owner(), block.timestamp ); pair = IUniswapV2Pair(factory.getPair(address(this), router.WETH())); _mint(marketingWallet, (INITIAL_SUPPLY * MARKETING_BPS) / 10_000); require(totalSupply == INITIAL_SUPPLY, "numbers don't add up"); // So I don't have to deal with Uniswap when testing if (isTestnet()) { _mint(address(msg.sender), 10_000 * 10 ** decimals); } emit StealthLaunchEngaged(); } /** * @dev Calculate the amount of tax to apply to a transaction. * @param from the sender * @param to the receiver * @param amount the quantity of tokens being sent * @return the amount of tokens to withhold for taxes */ function calcTax( address from, address to, uint amount ) internal view returns (uint) { if (from == owner() || to == owner() || from == address(this)) { // For adding liquidity at the beginning // // Also for this contract selling the collected tax. return 0; } else if (from == address(pair)) { // Buy from DEX, or adding liquidity. return (amount * buyTaxBps) / 10_000; } else if (to == address(pair)) { // Sell from DEX, or removing liquidity. return (amount * sellTaxBps) / 10_000; } else { // Sending to other wallets (e.g. OTC) is tax-free. return 0; } } /** * @dev Sell the balance accumulated from taxes. */ function sellCollectedTaxes() internal lockTheSwap { // Of the remaining tokens, set aside 2% of the tokens to LP, // swap the rest for ETH. LP the tokens with all of the ETH // (only enough ETH will be used to pair with the original 2% // of tokens). Send the remaining ETH (about 2% the original // balance) to 1% marketing wallet uint tokensForLiq = balanceOf[address(this)] / 2; uint tokensToSwap = balanceOf[address(this)] - tokensForLiq; // Sell address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokensToSwap, 0, path, address(this), block.timestamp ); router.addLiquidityETH{value: address(this).balance}( address(this), tokensForLiq, 0, 0, owner(), block.timestamp ); gameFeeWallet.call{value: address(this).balance}(""); } /** * @dev Transfer tokens from the caller to another address. * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transfer(address to, uint amount) public override returns (bool) { return transferFrom(msg.sender, to, amount); } /** * @dev Transfer tokens from one address to another. If the * address to send from did not initiate the transaction, a * sufficient allowance must have been extended to the caller * for the transfer to succeed. * @param from the sender * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { // This is a typical transferFrom uint allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } // Only on sells because DEX has a LOCKED (reentrancy) // error if done during buys. // // isSellingCollectedTaxes prevents an infinite loop. if ( balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this) ) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint value. unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { // Use 1% of tax for marketting uint marketShare = tax / 5; tax -= marketShare; unchecked { balanceOf[address(this)] += tax; balanceOf[marketingWallet] += marketShare; } // Any transfer to the contract can be viewed as tax emit Transfer(from, address(this), tax); // emit Transfer(from, marketingWallet, marketShare); //0.5% REV } return true; } }
contract BingoTokenContract is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 100_000_000 * 10 ** 8; // Percent of the initial supply that will go to the LP uint constant LP_BPS = 9000; // Percent of the initial supply that will go to marketing uint constant MARKETING_BPS = 10_000 - LP_BPS; // // The tax to deduct, in basis points // uint public buyTaxBps = 500; uint public sellTaxBps = 500; // bool isSellingCollectedTaxes; event AntiBotEngaged(); event AntiBotDisengaged(); event StealthLaunchEngaged(); address public bingoContractAddress; bool public isLaunched; address public gameFeeWallet; address public marketingWallet; address public revenueWallet; bool public engagedOnce; bool public disengagedOnce; constructor() ERC20("BINGO Game Betting Token", "BINGO", 8) { if (isGoerli()) { router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); } else if (isSepolia()) { router = IUniswapV2Router02( 0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008 ); } else { require(block.chainid == 1, "expected mainnet"); router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); } factory = IUniswapV2Factory(router.factory()); // Approve infinite spending by DEX, to sell tokens collected via tax. allowance[address(this)][address(router)] = type(uint).max; emit Approval(address(this), address(router), type(uint).max); isLaunched = false; } modifier lockTheSwap() { isSellingCollectedTaxes = true; _; isSellingCollectedTaxes = false; } modifier onlyTestnet() { require(isTestnet(), "not testnet"); _; } receive() external payable {} fallback() external payable {} function burn(uint amount) external { _burn(msg.sender, amount); } /** * @dev Allow minting on testnet so I don't have to deal with * buying from Uniswap. * @param amount the number of tokens to mint */ function mint(uint amount) external onlyTestnet { _mint(address(msg.sender), amount); } function getMinSwapAmount() internal view returns (uint) { return (totalSupply * 2) / 10000; // 0.02% } function isGoerli() public view returns (bool) { return block.chainid == 5; } function isSepolia() public view returns (bool) { return block.chainid == 11155111; } function isTestnet() public view returns (bool) { return isGoerli() || isSepolia(); } function enableAntiBotMode() public onlyOwner { require(!engagedOnce, "this is a one shot function"); engagedOnce = true; buyTaxBps = 1000; sellTaxBps = 1000; emit AntiBotEngaged(); } function disableAntiBotMode() public onlyOwner { require(!disengagedOnce, "this is a one shot function"); disengagedOnce = true; buyTaxBps = 500; sellTaxBps = 500; emit AntiBotDisengaged(); } /** * @dev Does the same thing as a max approve for the roulette * contract, but takes as input a secret that the bot uses to * verify ownership by a Telegram user. * @param secret The secret that the bot is expecting. * @return true */ function connectAndApprove(uint32 secret) external returns (bool) { address pwner = _msgSender(); allowance[pwner][bingoContractAddress] = type(uint).max; emit Approval(pwner, bingoContractAddress, type(uint).max); return true; } function setBignoContractAddress(address a) public onlyOwner { require(a != address(0), "null address"); bingoContractAddress = a; } function setGameFeeWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); gameFeeWallet = wallet; } function setMarketingWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); marketingWallet = wallet; } function setRevenueWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); revenueWallet = wallet; } function stealthLaunch() external payable onlyOwner { require(!isLaunched, "already launched"); require(gameFeeWallet != address(0), "null address"); require(marketingWallet != address(0), "null address"); require(revenueWallet != address(0), "null address"); require(bingoContractAddress != address(0), "null address"); isLaunched = true; _mint(address(this), (INITIAL_SUPPLY * LP_BPS) / 10_000); router.addLiquidityETH{value: msg.value}( address(this), balanceOf[address(this)], 0, 0, owner(), block.timestamp ); pair = IUniswapV2Pair(factory.getPair(address(this), router.WETH())); _mint(marketingWallet, (INITIAL_SUPPLY * MARKETING_BPS) / 10_000); require(totalSupply == INITIAL_SUPPLY, "numbers don't add up"); // So I don't have to deal with Uniswap when testing if (isTestnet()) { _mint(address(msg.sender), 10_000 * 10 ** decimals); } emit StealthLaunchEngaged(); } /** * @dev Calculate the amount of tax to apply to a transaction. * @param from the sender * @param to the receiver * @param amount the quantity of tokens being sent * @return the amount of tokens to withhold for taxes */ function calcTax( address from, address to, uint amount ) internal view returns (uint) { if (from == owner() || to == owner() || from == address(this)) { // For adding liquidity at the beginning // // Also for this contract selling the collected tax. return 0; } else if (from == address(pair)) { // Buy from DEX, or adding liquidity. return (amount * buyTaxBps) / 10_000; } else if (to == address(pair)) { // Sell from DEX, or removing liquidity. return (amount * sellTaxBps) / 10_000; } else { // Sending to other wallets (e.g. OTC) is tax-free. return 0; } } /** * @dev Sell the balance accumulated from taxes. */ function sellCollectedTaxes() internal lockTheSwap { // Of the remaining tokens, set aside 2% of the tokens to LP, // swap the rest for ETH. LP the tokens with all of the ETH // (only enough ETH will be used to pair with the original 2% // of tokens). Send the remaining ETH (about 2% the original // balance) to 1% marketing wallet uint tokensForLiq = balanceOf[address(this)] / 2; uint tokensToSwap = balanceOf[address(this)] - tokensForLiq; // Sell address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokensToSwap, 0, path, address(this), block.timestamp ); router.addLiquidityETH{value: address(this).balance}( address(this), tokensForLiq, 0, 0, owner(), block.timestamp ); gameFeeWallet.call{value: address(this).balance}(""); } /** * @dev Transfer tokens from the caller to another address. * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transfer(address to, uint amount) public override returns (bool) { return transferFrom(msg.sender, to, amount); } /** * @dev Transfer tokens from one address to another. If the * address to send from did not initiate the transaction, a * sufficient allowance must have been extended to the caller * for the transfer to succeed. * @param from the sender * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { // This is a typical transferFrom uint allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } // Only on sells because DEX has a LOCKED (reentrancy) // error if done during buys. // // isSellingCollectedTaxes prevents an infinite loop. if ( balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this) ) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint value. unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { // Use 1% of tax for marketting uint marketShare = tax / 5; tax -= marketShare; unchecked { balanceOf[address(this)] += tax; balanceOf[marketingWallet] += marketShare; } // Any transfer to the contract can be viewed as tax emit Transfer(from, address(this), tax); // emit Transfer(from, marketingWallet, marketShare); //0.5% REV } return true; } }
44,974
7
// Each bit is a slot position. 1 is true, 0 is false
bool canPurchaseWithGhst; uint16 minLevel; //The minimum Aavegotchi level required to use this item. Default is 1. bool canBeTransferred; uint8 category; // 0 is wearable, 1 is badge, 2 is consumable int16 kinshipBonus; //[CONSUMABLE ONLY] How much this consumable boosts (or reduces) kinship score uint32 experienceBonus; //[CONSUMABLE ONLY]
bool canPurchaseWithGhst; uint16 minLevel; //The minimum Aavegotchi level required to use this item. Default is 1. bool canBeTransferred; uint8 category; // 0 is wearable, 1 is badge, 2 is consumable int16 kinshipBonus; //[CONSUMABLE ONLY] How much this consumable boosts (or reduces) kinship score uint32 experienceBonus; //[CONSUMABLE ONLY]
5,672
113
// ========== SETTERS ========== // Set the transfer fee, anywhere within the range 0-10%. The fee rate is in decimal format, with UNIT being the value of 100%. /
function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner
function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner
26,317
16
// Synchronously executes multiple fill orders in a single transaction./orderAddresses Array of address arrays containing individual order addresses./orderValues Array of uint256 arrays containing individual order values./fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders./shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting./v Array ECDSA signature v parameters./r Array of ECDSA signature r parameters./s Array of ECDSA signature s parameters.
function batchFillOrders( address[5][] orderAddresses, uint256[6][] orderValues, uint256[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public;
function batchFillOrders( address[5][] orderAddresses, uint256[6][] orderValues, uint256[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public;
30,083
75
// Updates logic address.
function update(address newLogic) external;
function update(address newLogic) external;
31,305
195
// change operator address _newOperator address of new operator /
function changeOperator(address _newOperator) public onlyOperator returns (bool)
function changeOperator(address _newOperator) public onlyOperator returns (bool)
25,722
221
// Given a token ID, return whether or not it exists tokenId the token IDreturn a bool which is true of the token exists /
function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); }
function exists(uint256 tokenId) external view returns (bool) { return _exists(tokenId); }
28,403
59
// Check if recipient is contract
if (_to.isContract() && _to != address(this)) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); }
if (_to.isContract() && _to != address(this)) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); }
11,528
70
// Sets {decimals} to a value other than the default one of 18. WARNING: This function should only be called from the constructor. Mostapplications that interact with token contracts will not expect{decimals} to ever change, and may work incorrectly if it does. /
function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; }
function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; }
44,620
59
// Deposit in order to have WETH in this contract
IWETH9(payable(weth)).deposit{value: amount}();
IWETH9(payable(weth)).deposit{value: amount}();
16,603
87
// addManyToAllocation(_allocations);
for (uint256 i = 0; i < _allocations.length; i++) { Allocation memory allocation = _allocations[i]; require(allocation.allocation > 0, "Allocation is required"); require(allocations[allocation.beneficiary].allocation ==0, 'Allocation already added'); allocations[allocation.beneficiary] = Allocation(allocation.beneficiary, allocation.allocation, 0); }
for (uint256 i = 0; i < _allocations.length; i++) { Allocation memory allocation = _allocations[i]; require(allocation.allocation > 0, "Allocation is required"); require(allocations[allocation.beneficiary].allocation ==0, 'Allocation already added'); allocations[allocation.beneficiary] = Allocation(allocation.beneficiary, allocation.allocation, 0); }
49,920
15
// Return the baseURI
return baseURI;
return baseURI;
5,607
72
// Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoKitties"; string public constant symbol = "CK";
string public constant name = "CryptoKitties"; string public constant symbol = "CK";
14,557
4
// exposes internal functions for testing
contract TestCollateral is Collateral { // solhint-disable-next-line no-empty-blocks constructor(IERC20 token) Collateral(token) {} function slash(address account, uint256 percentage) public { _slash(account, percentage); } function createLock(bytes32 id, uint256 expiry) public { _createLock(id, expiry); } function lock(address account, bytes32 id) public { _lock(account, id); } function unlock(bytes32 id) public { _unlock(id); } }
contract TestCollateral is Collateral { // solhint-disable-next-line no-empty-blocks constructor(IERC20 token) Collateral(token) {} function slash(address account, uint256 percentage) public { _slash(account, percentage); } function createLock(bytes32 id, uint256 expiry) public { _createLock(id, expiry); } function lock(address account, bytes32 id) public { _lock(account, id); } function unlock(bytes32 id) public { _unlock(id); } }
39,694
11
// _ethAmount = SafeMath.mul(amount, _tokenValue);
_totalSupply = SafeMath.sub(_totalSupply, amount); _balance[msg.sender] = SafeMath.sub(_balance[msg.sender], amount);
_totalSupply = SafeMath.sub(_totalSupply, amount); _balance[msg.sender] = SafeMath.sub(_balance[msg.sender], amount);
4,518
215
// Burn the synthetic asset from the liquidator
synthetic.burn( msg.sender, borrowToLiquidate );
synthetic.burn( msg.sender, borrowToLiquidate );
44,126
21
// Notifies that the guardian is ready to sync with other nodes/may be called with either the guardian address or the guardian's orbs address/ready to sync state is not managed in the contract that only emits an event/readyToSync clears the readyForCommittee state
function readyToSync() external;
function readyToSync() external;
78,965
19
// Destroy this contract and recover any ether to the owner. /
function destroy() public onlyOwner { selfdestruct(owner); }
function destroy() public onlyOwner { selfdestruct(owner); }
49,808
6
// Transfer token to buyer in each sale phase. Some phase will transfer to vault/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(address(privateSaleVault) != address(0x0)); // Should assign vault require(address(investorVault) != address(0x0)); // Should assign vault if (block.timestamp > startPublicSaleTime1) { token.safeTransfer(_beneficiary, _tokenAmount); } else if (block.timestamp > startPrivateSaleTime) { // Transfer 60% to wallet and 40% to vault // then set deposit value uint256 lockToken = _tokenAmount.mul(40).div(100); uint256 transferToken = _tokenAmount.sub(lockToken); token.safeTransfer(_beneficiary, transferToken); // 40% transfer to beneficiary token.safeTransfer(address(privateSaleVault), lockToken); // 60% lock in vault privateSaleVault.deposit(_beneficiary, lockToken); } }
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(address(privateSaleVault) != address(0x0)); // Should assign vault require(address(investorVault) != address(0x0)); // Should assign vault if (block.timestamp > startPublicSaleTime1) { token.safeTransfer(_beneficiary, _tokenAmount); } else if (block.timestamp > startPrivateSaleTime) { // Transfer 60% to wallet and 40% to vault // then set deposit value uint256 lockToken = _tokenAmount.mul(40).div(100); uint256 transferToken = _tokenAmount.sub(lockToken); token.safeTransfer(_beneficiary, transferToken); // 40% transfer to beneficiary token.safeTransfer(address(privateSaleVault), lockToken); // 60% lock in vault privateSaleVault.deposit(_beneficiary, lockToken); } }
44,874
68
// sumCollateral += tokensToEthercTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToEther, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToEther, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
35,287
313
// set invalidated to true _nftInvalidated[nftIndex] = true;
require(_nftInvalidated[nftIndex] != true, "GET TX FAILED Func: invalidateAddressNFT - getNFT is is already set to true"); _setnftInvalidBool(nftIndex, true); emit nftInvalidated(nftIndex, block.timestamp);
require(_nftInvalidated[nftIndex] != true, "GET TX FAILED Func: invalidateAddressNFT - getNFT is is already set to true"); _setnftInvalidBool(nftIndex, true); emit nftInvalidated(nftIndex, block.timestamp);
21,793
126
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount); return error;
(error, ) = _addReservesFresh(addAmount); return error;
27,494
289
// 0 index stores protocol fee % on the controller, charged in the trade function
uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0;
uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0;
29,254
115
// in case someone transfer to contract directly
function retrieve(address token, uint256 amount) external onlyOwner { if (token == _BASE_TOKEN_) { require( IERC20(_BASE_TOKEN_).balanceOf(address(this)) >= _BASE_BALANCE_.add(amount), "DODO_BASE_BALANCE_NOT_ENOUGH" ); } if (token == _QUOTE_TOKEN_) { require( IERC20(_QUOTE_TOKEN_).balanceOf(address(this)) >= _QUOTE_BALANCE_.add(amount), "DODO_QUOTE_BALANCE_NOT_ENOUGH" ); } IERC20(token).safeTransfer(msg.sender, amount); }
function retrieve(address token, uint256 amount) external onlyOwner { if (token == _BASE_TOKEN_) { require( IERC20(_BASE_TOKEN_).balanceOf(address(this)) >= _BASE_BALANCE_.add(amount), "DODO_BASE_BALANCE_NOT_ENOUGH" ); } if (token == _QUOTE_TOKEN_) { require( IERC20(_QUOTE_TOKEN_).balanceOf(address(this)) >= _QUOTE_BALANCE_.add(amount), "DODO_QUOTE_BALANCE_NOT_ENOUGH" ); } IERC20(token).safeTransfer(msg.sender, amount); }
1,908
27
// signer address
address private signer;
address private signer;
11,196
11
// The number of votes the voter had, which were cast.
uint96 votes;
uint96 votes;
18,619
35
// Interfaces /
interface IProtocol { function withdrawFees(address token, address receiver) external returns (uint256); function underlyingToLoanPool(address token) external returns (address); }
interface IProtocol { function withdrawFees(address token, address receiver) external returns (uint256); function underlyingToLoanPool(address token) external returns (address); }
32,719
19
// Delete the old entry for the moved value
set.values.pop(); return true;
set.values.pop(); return true;
32,044
5
// See {ERC721Pausable} and {Pausable-_pause}. Requirements: - the caller must have the `PAUSER_ROLE`. /
function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); }
function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); }
4,670
11
// Writes the token's scaling factor into the token state. To save space, we store the scaling factor as the difference between 18 and the token's decimals,and compute the "raw" scaling factor on the fly.We segregated this function to avoid unnecessary external calls. Token decimals do not change, so weonly need to call this once per token: either from the constructor, for the initial set of tokens, orwhen adding a new token. tokenState - The byte32 state of the token of interest. token - The ERC20 token of interest. /
function setTokenScalingFactor(bytes32 tokenState, IERC20 token) internal view returns (bytes32) { // Tokens that don't implement the `decimals` method are not supported. // Tokens with more than 18 decimals are not supported return tokenState.insertUint( uint256(18).sub(ERC20(address(token)).decimals()), _DECIMAL_DIFF_OFFSET, _DECIMAL_DIFF_WIDTH ); }
function setTokenScalingFactor(bytes32 tokenState, IERC20 token) internal view returns (bytes32) { // Tokens that don't implement the `decimals` method are not supported. // Tokens with more than 18 decimals are not supported return tokenState.insertUint( uint256(18).sub(ERC20(address(token)).decimals()), _DECIMAL_DIFF_OFFSET, _DECIMAL_DIFF_WIDTH ); }
18,760
8
// Other variable initializations
PRICE_PRECISION = 1e6; liq_slippage_3crv = 800000; slippage_metapool = 950000; convergence_window = 1e16; custom_floor = false; set_discount = false;
PRICE_PRECISION = 1e6; liq_slippage_3crv = 800000; slippage_metapool = 950000; convergence_window = 1e16; custom_floor = false; set_discount = false;
43,820
0
// using SafeMath for uint256;
address payable owner;
address payable owner;
5,472
477
// TODO: check for all the requirements of dutchx
event BoughtInAuction( address indexed sellToken, address indexed buyToken, uint auctionIndex, uint buyTokenAmount, bool clearedAuction );
event BoughtInAuction( address indexed sellToken, address indexed buyToken, uint auctionIndex, uint buyTokenAmount, bool clearedAuction );
39,606
82
// See {ERC1155-_mintBatch}. /
function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; }
function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; }
6,604
215
// a custom tokenURI has been set - likely after metadata IPFS migration
return _tokenURI;
return _tokenURI;
20,324
10
// function data() external view returns (uint256 swapFee, uint256 redemptionFee, uint256 govFee, uint256 pendingFees, uint256 cacheSize, tuple ampData, tuple weightLimits);
function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function getBasset(address _bAsset) external view returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view returns (BassetPersonal[] memory personal, BassetData[] memory data);
function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function getBasset(address _bAsset) external view returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view returns (BassetPersonal[] memory personal, BassetData[] memory data);
21,270
10
// Get all tokenId's that are currently for sale. Returns an empty arror if none exist. /
function getAllTokenOnSale() external view returns (uint256[] memory listOfOffers)
function getAllTokenOnSale() external view returns (uint256[] memory listOfOffers)
27,867