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
2
// Burns. /
function burn(uint256 amount) external;
function burn(uint256 amount) external;
7,130
28
// Get borrow APR data from Dydx from Dydx contract address
function getBorrowDyDxAPR(uint256 marketId) public view returns(uint256) { uint256 rate = DyDx(DYDX).getMarketInterestRate(marketId).value; uint256 aprBorrow = rate * 31622400; return aprBorrow; }
function getBorrowDyDxAPR(uint256 marketId) public view returns(uint256) { uint256 rate = DyDx(DYDX).getMarketInterestRate(marketId).value; uint256 aprBorrow = rate * 31622400; return aprBorrow; }
45,213
196
// `mint` but with `minter`, `fee`, `nonce`, and `sig` as extra parameters.`fee` is a mint fee amount in Gluwacoin, which the minter will pay for the mint.`sig` is a signature created by signing the mint information with the minter’s private key.Anyone can initiate the mint for the minter by calling the Etherless Mint functionwith the mint information and the signature.The caller will have to pay the gas for calling the function. Transfers `amount` + `fee` of base tokens from the minter to the contract using `transferFrom`.Creates `amount` + `fee` of tokens to the minter and transfers `fee` tokens to the caller.
* See {ERC20-_mint} and {ERC20-allowance}. * * Requirements: * * - the minter must have base tokens of at least `amount` + `fee`. * - the contract must have allowance for receiver's base tokens of at least `amount` + `fee`. */ function mint(address minter, uint256 amount, uint256 fee, uint256 nonce, bytes calldata sig) external { _useWrapperNonce(minter, nonce); bytes32 hash = keccak256(abi.encodePacked(address(this), minter, amount, fee, nonce)); Validate.validateSignature(hash, minter, sig); __mint(minter, amount); address wrapper = getRoleMember(WRAPPER_ROLE, 0); _transfer(minter, wrapper, fee); }
* See {ERC20-_mint} and {ERC20-allowance}. * * Requirements: * * - the minter must have base tokens of at least `amount` + `fee`. * - the contract must have allowance for receiver's base tokens of at least `amount` + `fee`. */ function mint(address minter, uint256 amount, uint256 fee, uint256 nonce, bytes calldata sig) external { _useWrapperNonce(minter, nonce); bytes32 hash = keccak256(abi.encodePacked(address(this), minter, amount, fee, nonce)); Validate.validateSignature(hash, minter, sig); __mint(minter, amount); address wrapper = getRoleMember(WRAPPER_ROLE, 0); _transfer(minter, wrapper, fee); }
43,837
78
// Parses the data to extract the method signature. /
function functionPrefix(bytes _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } }
function functionPrefix(bytes _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } }
2,408
59
// Get two new random special moves.
uint256[2] memory randomMoves = randomizeActions(_specialId); assert(kittyData.trainSpecial(_kittyId, _specialId, randomMoves, _slots)); assert(kittyGym.addMoves(_kittyId, randomMoves)); uint256 specialRank = special.population - special.amountLeft + 1; SpecialTrained(_kittyId, _specialId, specialRank, randomMoves); special.amountLeft--; specialKitties[_kittyId] = true;
uint256[2] memory randomMoves = randomizeActions(_specialId); assert(kittyData.trainSpecial(_kittyId, _specialId, randomMoves, _slots)); assert(kittyGym.addMoves(_kittyId, randomMoves)); uint256 specialRank = special.population - special.amountLeft + 1; SpecialTrained(_kittyId, _specialId, specialRank, randomMoves); special.amountLeft--; specialKitties[_kittyId] = true;
42,954
76
// Token removal is forbidden during a weight change or if one is scheduled so we can assume that the weight change progress is 100%.
uint256 tokenToRemoveNormalizedWeight = ManagedPoolTokenStorageLib.getTokenWeight( _tokenState[tokenToRemove], FixedPoint.ONE );
uint256 tokenToRemoveNormalizedWeight = ManagedPoolTokenStorageLib.getTokenWeight( _tokenState[tokenToRemove], FixedPoint.ONE );
8,854
36
// 15 seeconds from the current block time
uint256 deadline = block.timestamp + 15;
uint256 deadline = block.timestamp + 15;
14,370
14
// Validate the values were signed by an authorized oracle
address signer = recover(val_[i], age_[i], v[i], r[i], s[i]);
address signer = recover(val_[i], age_[i], v[i], r[i], s[i]);
5,984
231
// Returns a hash for a given tokenId _tokenId The tokenId to return the hash for. /
function _tokenIdToHash(uint256 _tokenId) public view returns (string memory)
function _tokenIdToHash(uint256 _tokenId) public view returns (string memory)
9,615
133
// Function: subtractCampaignTokens()/
function subtractCampaignTokens(uint256 noOfTokens) external
function subtractCampaignTokens(uint256 noOfTokens) external
50,068
154
// Gets the Witnet.Request part of a given query.
function _getRequestData(uint256 _queryId) internal view returns (Witnet.Request storage)
function _getRequestData(uint256 _queryId) internal view returns (Witnet.Request storage)
22,390
259
// returns whether or not the deviation of the average rate from the spot rate is within rangefor example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95`_spotRateN spot rate numerator _spotRateD spot rate denominator _averageRateNaverage rate numerator _averageRateDaverage rate denominator _maxDeviationthe maximum permitted deviation of the average rate from the spot rate /
function averageRateInRange( uint256 _spotRateN, uint256 _spotRateD, uint256 _averageRateN, uint256 _averageRateD, uint32 _maxDeviation
function averageRateInRange( uint256 _spotRateN, uint256 _spotRateD, uint256 _averageRateN, uint256 _averageRateD, uint32 _maxDeviation
43,262
7
// Add to the deposit of the given account. account - The account to add to. /
function depositTo(address account) external payable;
function depositTo(address account) external payable;
24,513
8
// token Token address to Send to address amount Amount to send /
event Rescue(address token, address to, uint256 amount);
event Rescue(address token, address to, uint256 amount);
43,364
40
// Destination account claim the amount from the escorw senderId The sender unique ID generated by EPN destinationId The destination unique ID generated by EPN/
function claimEthAmount(uint256 senderId, uint256 destinationId) public { require (destinationId != 0 && senderId != destinationId); require(epnToken.isRegistered(destinationId) && epnToken.getOwnerOf(destinationId) == msg.sender); uint256 mappingId = getUniqueId(senderId, destinationId); EscrowPayment storage payment = escrowEthPayments[mappingId]; require(payment.destinationId == destinationId && payment.amount > 0 && payment.expiryTime > block.timestamp); address payable destinationAddress = payable(epnToken.getOwnerOf(destinationId)); uint256 claimAmount = payment.amount; payment.amount = 0; destinationAddress.transfer(claimAmount); emit ClaimEthTransfered(mappingId, senderId, destinationId, claimAmount); }
function claimEthAmount(uint256 senderId, uint256 destinationId) public { require (destinationId != 0 && senderId != destinationId); require(epnToken.isRegistered(destinationId) && epnToken.getOwnerOf(destinationId) == msg.sender); uint256 mappingId = getUniqueId(senderId, destinationId); EscrowPayment storage payment = escrowEthPayments[mappingId]; require(payment.destinationId == destinationId && payment.amount > 0 && payment.expiryTime > block.timestamp); address payable destinationAddress = payable(epnToken.getOwnerOf(destinationId)); uint256 claimAmount = payment.amount; payment.amount = 0; destinationAddress.transfer(claimAmount); emit ClaimEthTransfered(mappingId, senderId, destinationId, claimAmount); }
26,422
323
// ----------------- TOKEN CONVERSIONS -----------------
function getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path)
function getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path)
4,413
3
// Implementation of the {IERC165} interface.Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to checkreturn interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);``` Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. /
abstract contract ERC165 is IERC165 {
abstract contract ERC165 is IERC165 {
29,193
14
// withdraw ethers
function withdrawAll() external onlyAdmin { payable(_fundAddress).transfer(address(this).balance); }
function withdrawAll() external onlyAdmin { payable(_fundAddress).transfer(address(this).balance); }
45,302
26
// Getters./
function generateCard(uint256 cardId) public view returns (BingoGenerate.Card memory) { return BingoGenerate.generateBingoCard(cardRandomness[cardId]); }
function generateCard(uint256 cardId) public view returns (BingoGenerate.Card memory) { return BingoGenerate.generateBingoCard(cardRandomness[cardId]); }
77,970
19
// mark as complete
request.complete = true;
request.complete = true;
20,697
61
// ================ Structs ================ Needed to lower stack size
struct MintFF_Params { uint256 mint_fee; uint256 fxs_price_usd; uint256 frax_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 collateral_token_balance; uint256 pool_ceiling; uint256 col_ratio; }
struct MintFF_Params { uint256 mint_fee; uint256 fxs_price_usd; uint256 frax_price_usd; uint256 col_price_usd; uint256 fxs_amount; uint256 collateral_amount; uint256 collateral_token_balance; uint256 pool_ceiling; uint256 col_ratio; }
8,231
17
// fill_pool() creates a swap pool with specific parameters from input_hashsha3-256(password)_start start time delta, real start time = base_time + _start_end end time delta, real end time = base_time + _endmessageswap pool creation message, only stored in FillSuccess event_exchange_addrsswap token list (0x0 for ETH, only supports ETH and ERC20 now)_ratiosswap pair ratio list_unlock_time unlock time delta real unlock time = base_time + _unlock_time_token_addrswap target token address_total_tokenstarget token total swap amount_limit target token single swap limit_qualification the qualification contract address based on IQLF to determine qualificationThis function takes the above parameters and creates the pool. _total_tokens of the target tokenwill be successfully
public payable { nonce ++; require(_start < _end, "Start time should be earlier than end time."); require(_end < _unlock_time || _unlock_time == 0, "End time should be earlier than unlock time"); require(_limit <= _total_tokens, "Limit needs to be less than or equal to the total supply"); require(_total_tokens < 2 ** 128, "No more than 2^128 tokens(incluidng decimals) allowed"); require(_exchange_addrs.length > 0, "Exchange token addresses need to be set"); require(_ratios.length == 2 * _exchange_addrs.length, "Size of ratios = 2 * size of exchange_addrs"); bytes32 _id = keccak256(abi.encodePacked(msg.sender, block.timestamp, nonce, seed)); Pool storage pool = pool_by_id[_id]; pool.packed1 = Packed1(_qualification, uint40(uint256(_hash) >> 216)); pool.packed2 = Packed2(uint128(_total_tokens), uint128(_limit)); pool.packed3 = Packed3(_token_addr, uint32(_start), uint32(_end), uint32(_unlock_time)); pool.creator = msg.sender; pool.exchange_addrs = _exchange_addrs; pool.destructed = false; // Init each token swapped amount to 0 for (uint256 i = 0; i < _exchange_addrs.length; i++) { if (_exchange_addrs[i] != DEFAULT_ADDRESS) { // TODO: Is there a better way to validate an ERC20? require(IERC20(_exchange_addrs[i]).totalSupply() > 0, "Not a valid ERC20"); } pool.exchanged_tokens.push(0); } pool.ratios = _ratios; // 256 * k IERC20(_token_addr).safeTransferFrom(msg.sender, address(this), _total_tokens); { // Solidity has stack depth limitation: "Stack too deep, try removing local variables" // add local variables as a workaround uint256 total_tokens = _total_tokens; address token_addr = _token_addr; string memory message = _message; uint256 start = _start; uint256 end = _end; address[] memory exchange_addrs = _exchange_addrs; uint128[] memory ratios = _ratios; address qualification = _qualification; uint256 limit = _limit; emit FillSuccess( msg.sender, _id, total_tokens, block.timestamp, token_addr, message, start, end, exchange_addrs, ratios, qualification, limit ); } }
public payable { nonce ++; require(_start < _end, "Start time should be earlier than end time."); require(_end < _unlock_time || _unlock_time == 0, "End time should be earlier than unlock time"); require(_limit <= _total_tokens, "Limit needs to be less than or equal to the total supply"); require(_total_tokens < 2 ** 128, "No more than 2^128 tokens(incluidng decimals) allowed"); require(_exchange_addrs.length > 0, "Exchange token addresses need to be set"); require(_ratios.length == 2 * _exchange_addrs.length, "Size of ratios = 2 * size of exchange_addrs"); bytes32 _id = keccak256(abi.encodePacked(msg.sender, block.timestamp, nonce, seed)); Pool storage pool = pool_by_id[_id]; pool.packed1 = Packed1(_qualification, uint40(uint256(_hash) >> 216)); pool.packed2 = Packed2(uint128(_total_tokens), uint128(_limit)); pool.packed3 = Packed3(_token_addr, uint32(_start), uint32(_end), uint32(_unlock_time)); pool.creator = msg.sender; pool.exchange_addrs = _exchange_addrs; pool.destructed = false; // Init each token swapped amount to 0 for (uint256 i = 0; i < _exchange_addrs.length; i++) { if (_exchange_addrs[i] != DEFAULT_ADDRESS) { // TODO: Is there a better way to validate an ERC20? require(IERC20(_exchange_addrs[i]).totalSupply() > 0, "Not a valid ERC20"); } pool.exchanged_tokens.push(0); } pool.ratios = _ratios; // 256 * k IERC20(_token_addr).safeTransferFrom(msg.sender, address(this), _total_tokens); { // Solidity has stack depth limitation: "Stack too deep, try removing local variables" // add local variables as a workaround uint256 total_tokens = _total_tokens; address token_addr = _token_addr; string memory message = _message; uint256 start = _start; uint256 end = _end; address[] memory exchange_addrs = _exchange_addrs; uint128[] memory ratios = _ratios; address qualification = _qualification; uint256 limit = _limit; emit FillSuccess( msg.sender, _id, total_tokens, block.timestamp, token_addr, message, start, end, exchange_addrs, ratios, qualification, limit ); } }
11,751
45
// Set an upgrade agent that handles /
function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading throw; } if (agent == 0x0) throw; // Only a master can designate the next agent if (msg.sender != upgradeMaster) throw; // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) throw; upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) throw; // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) throw; UpgradeAgentSet(upgradeAgent); }
function setUpgradeAgent(address agent) external { if(!canUpgrade()) { // The token is not yet in a state that we could think upgrading throw; } if (agent == 0x0) throw; // Only a master can designate the next agent if (msg.sender != upgradeMaster) throw; // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) throw; upgradeAgent = UpgradeAgent(agent); // Bad interface if(!upgradeAgent.isUpgradeAgent()) throw; // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply) throw; UpgradeAgentSet(upgradeAgent); }
24,286
662
// Require new proposal submission would not push number of InProgress proposals over max number
require( inProgressProposals.length < maxInProgressProposals, "Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire." );
require( inProgressProposals.length < maxInProgressProposals, "Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire." );
7,703
38
// This is internal function is equivalent to {transfer}, and can be used to /
function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance"
function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance"
8,064
23
// WHITELIST
mapping(address => bool) public whitelisted_Prebuy; // pID => isWhitelisted
mapping(address => bool) public whitelisted_Prebuy; // pID => isWhitelisted
26,957
61
// Apply our fixed presale rate and verify we are not sold out. eth the amount of ether used to purchase presale tokens. /
function _allocatePresaleTokens(uint256 eth) private view returns(uint256 tokens) { tokens = presale_eth_to_zilla.mul(eth); require( zilla_remaining >= tokens ); }
function _allocatePresaleTokens(uint256 eth) private view returns(uint256 tokens) { tokens = presale_eth_to_zilla.mul(eth); require( zilla_remaining >= tokens ); }
38,661
26
// Mapping Series Address => PluginID => Content
mapping(address=>mapping(uint16=>string)) private contents;
mapping(address=>mapping(uint16=>string)) private contents;
49,154
8
// no more can get minted by {mintTeamTreasury}
uint256 public constant TEAM_TREASURY_SUPPLY = 1000;
uint256 public constant TEAM_TREASURY_SUPPLY = 1000;
2,587
188
// Get the balance of an account's Tokens _ownerThe address of the token holder _id ID of the TokenreturnThe _owner's balance of the Token type requested /
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
9,688
265
// Transfers 'tokenId' from 'from' to 'to'.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - 'to' cannot be the zero address. * - 'tokenId' token must be owned by 'from'. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId, 1); // Check that tokenId was not transferred by '_beforeTokenTransfer' hook require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); // Clear approvals from the previous owner delete _tokenApprovals[tokenId]; unchecked { // '_balances[from]' cannot overflow for the same reason as described in '_burn': // 'from''s balance is the number of token held, which is at least one before the current // transfer. // '_balances[to]' could overflow in the conditions described in '_mint'. That would require // all 2**256 token ids to be minted, which in practice is impossible. _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); }
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - 'to' cannot be the zero address. * - 'tokenId' token must be owned by 'from'. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId, 1); // Check that tokenId was not transferred by '_beforeTokenTransfer' hook require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); // Clear approvals from the previous owner delete _tokenApprovals[tokenId]; unchecked { // '_balances[from]' cannot overflow for the same reason as described in '_burn': // 'from''s balance is the number of token held, which is at least one before the current // transfer. // '_balances[to]' could overflow in the conditions described in '_mint'. That would require // all 2**256 token ids to be minted, which in practice is impossible. _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); }
19,685
16
// Get all articles in rule
uint articlesCount = dealsInstance.getArticlesCount(_dealId, _ruleId); bool success = true; for (uint i=0;i<articlesCount;i++) { success = interpretArticle(_from, _dealId, _ruleId, i); if (!success) { revert(); }
uint articlesCount = dealsInstance.getArticlesCount(_dealId, _ruleId); bool success = true; for (uint i=0;i<articlesCount;i++) { success = interpretArticle(_from, _dealId, _ruleId, i); if (!success) { revert(); }
17,157
57
// validate, transfer ownership, and emit relevant events /
function _transferOwnership(address to) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); }
function _transferOwnership(address to) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); }
14,986
3
// Assume out of gas We need to revert here so gas estimation works
require(false, "GAS");
require(false, "GAS");
38,221
34
// Advance `outPtr` to point to the end of the header data (i.e. the start of the decoded inner transaction data)
outPtr := add(outPtr, ROLLUP_HEADER_LENGTH)
outPtr := add(outPtr, ROLLUP_HEADER_LENGTH)
14,554
22
// This famous algorithm is called "exponentiation by squaring" and calculates x^n with x as fixed-point and n as regular unsigned. It's O(log n), instead of O(n) for naive repeated multiplication. These facts are why it works:If n is even, then x^n = (x^2)^(n/2).If n is odd,then x^n = xx^(n-1), and applying the equation for even x givesx^n = x(x^2)^((n-1) / 2).Also, EVM division is flooring andfloor[(n-1) / 2] = floor[n / 2].
function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } }
function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } }
609
436
// fire hook
uint pricePaid = tokenAddress == address(0) ? msg.value : _values[i]; if(address(onKeyPurchaseHook) != address(0)) { onKeyPurchaseHook.onKeyPurchase( msg.sender, _recipient, _referrers[i], _data[i], inMemoryKeyPrice, pricePaid );
uint pricePaid = tokenAddress == address(0) ? msg.value : _values[i]; if(address(onKeyPurchaseHook) != address(0)) { onKeyPurchaseHook.onKeyPurchase( msg.sender, _recipient, _referrers[i], _data[i], inMemoryKeyPrice, pricePaid );
37,886
93
// performance fee sent to treasury when harvest() generates profit
uint public performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000;
uint public performanceFee = 500; uint private constant PERFORMANCE_FEE_CAP = 2000; // upper limit to performance fee uint internal constant PERFORMANCE_FEE_MAX = 10000;
61,849
76
// Get total pool shares
uint totalShares = IuniswapExchange(_UniSwapExchangeContractAddress).totalSupply();
uint totalShares = IuniswapExchange(_UniSwapExchangeContractAddress).totalSupply();
52,698
25
// else, negate outlook of maker
newTakerOrder = HDGXStructs.TakerOrder( takerOrderIDCount + 1, sender, valueSent, block.timestamp, makerOrderID, !(makersLegs[makerOrderID][0].outlook) );
newTakerOrder = HDGXStructs.TakerOrder( takerOrderIDCount + 1, sender, valueSent, block.timestamp, makerOrderID, !(makersLegs[makerOrderID][0].outlook) );
5,194
6
// event TransferSingle same / related to safeTransferFrom
982
20
// Get balance of specified address._address Tokens owner address. /
function balanceOf(address _address) public view returns (uint256 balance) { return balances[_address]; }
function balanceOf(address _address) public view returns (uint256 balance) { return balances[_address]; }
14,213
94
// Trades _tokenIn to _tokenOut using Uniswap V3_tokenIn Token that is sold _tokenOutToken that is purchased _amountAmount of tokenin to sell /
function _trade( address _tokenIn, address _tokenOut, uint256 _amount
function _trade( address _tokenIn, address _tokenOut, uint256 _amount
15,645
5
// See {ITREXFactory-recoverContractOwnership}. /
function recoverContractOwnership(address _contract, address _newOwner) external override onlyOwner { (Ownable(_contract)).transferOwnership(_newOwner); }
function recoverContractOwnership(address _contract, address _newOwner) external override onlyOwner { (Ownable(_contract)).transferOwnership(_newOwner); }
29,678
221
// similar gas saving effort here
for (uint256 ii = 0; ii<conBalance && _foundCount < _functionalLimit; ii++){ ERC721Enumerable conE = ERC721Enumerable(_tokenContractAddresses[i]); uint256 tokenID = conE.tokenOfOwnerByIndex(_addy,ii); if(tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] == false){ tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] = true; _foundCount++; }
for (uint256 ii = 0; ii<conBalance && _foundCount < _functionalLimit; ii++){ ERC721Enumerable conE = ERC721Enumerable(_tokenContractAddresses[i]); uint256 tokenID = conE.tokenOfOwnerByIndex(_addy,ii); if(tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] == false){ tokenVer[_childContract][_tokenContractAddresses[i]][tokenID] = true; _foundCount++; }
40,260
40
// ------------------------------------------------------------------------14120 PPU Tokens per 1 ETH ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); require((icoSupply + placementSupply) > 0); require(msg.value > 0); uint tokens = 0; if (now <= bonusEnds) { tokens = msg.value * 16944; require(tokens < icoSupply && icoSupply > 0); icoSupply -= tokens; balances[address(this)] -= tokens; } else { tokens = msg.value * 14120; require(tokens < placementSupply && placementSupply > 0); icoSupply -= tokens; balances[address(this)] -= tokens; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); Transfer(address(this), msg.sender, tokens); owner.transfer(msg.value); }
function () public payable { require(now >= startDate && now <= endDate); require((icoSupply + placementSupply) > 0); require(msg.value > 0); uint tokens = 0; if (now <= bonusEnds) { tokens = msg.value * 16944; require(tokens < icoSupply && icoSupply > 0); icoSupply -= tokens; balances[address(this)] -= tokens; } else { tokens = msg.value * 14120; require(tokens < placementSupply && placementSupply > 0); icoSupply -= tokens; balances[address(this)] -= tokens; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); Transfer(address(this), msg.sender, tokens); owner.transfer(msg.value); }
36,652
8
// Transfer token for a specified address _to The address to transfer to. _value The amount to be transferred. /
function _transfer(address _to, uint _value) private returns (bool){ require(msg.sender != address(0)); require(_to != address(0)); require(_value > 0 && _value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
function _transfer(address _to, uint _value) private returns (bool){ require(msg.sender != address(0)); require(_to != address(0)); require(_value > 0 && _value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
9,515
156
// Apply transformation to verify the claim provided by the user is true
uint32 transformedWinningNumber = _bracketCalculator[_bracket] + (winningTicketNumber % (uint32(10)**(_bracket + 1))); uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1)));
uint32 transformedWinningNumber = _bracketCalculator[_bracket] + (winningTicketNumber % (uint32(10)**(_bracket + 1))); uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1)));
27,277
379
// Reserve asset not supported
uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85;
uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85;
67,982
4
// give modules from address(this) to line so we can run line.init()
LineFactoryLib.transferModulesToLine(address(line), s, e); emit DeployedSecuredLine(address(line), s, e, swapTarget, split);
LineFactoryLib.transferModulesToLine(address(line), s, e); emit DeployedSecuredLine(address(line), s, e, swapTarget, split);
45,149
12
// WeiUnsortedSplitterWill split money (order does not matter!). /
contract WeiUnsortedSplitter is SplitterBase, IWeiReceiver { event ConsoleUint(string a, uint b); constructor(string _name) SplitterBase(_name) public { } // IWeiReceiver: // calculate only absolute outputs, but do not take into account the Percents function getMinWeiNeeded()public view returns(uint) { if(!isOpen()) { return 0; } uint absSum = 0; uint percentsMul100ReverseSum = 10000; for(uint i=0; i<childrenCount; ++i) { if(0!=IWeiReceiver(children[i]).getPercentsMul100()) { percentsMul100ReverseSum -= IWeiReceiver(children[i]).getPercentsMul100(); }else { absSum += IWeiReceiver(children[i]).getMinWeiNeeded(); } } if(percentsMul100ReverseSum==0) { return 0; }else { return 10000*absSum/percentsMul100ReverseSum; } } function getTotalWeiNeeded(uint _inputWei)public view returns(uint) { if(!isOpen()) { return 0; } uint total = 0; for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_inputWei); total = total + needed; } return total; } function getPercentsMul100()public view returns(uint) { uint total = 0; for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); total = total + c.getPercentsMul100(); } // truncate, no more than 100% allowed! if(total>10000) { return 10000; } return total; } function isNeedsMoney()public view returns(bool) { if(!isOpen()) { return false; } for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); // if at least 1 child needs money -> return true if(c.isNeedsMoney()) { return true; } } return false; } // WeiSplitter allows to receive money from ANY address // WeiSplitter should not hold any funds. Instead - it should split immediately // If WeiSplitter receives less or more money than needed -> exception function processFunds(uint _currentFlow) public payable { require(isOpen()); emit SplitterBaseProcessFunds(msg.sender, msg.value, _currentFlow); uint amount = msg.value; // TODO: can remove this line? // transfer below will throw if not enough money? require(amount>=getTotalWeiNeeded(_currentFlow)); // DO NOT SEND LESS! // DO NOT SEND MORE! for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_currentFlow); // send money. can throw! // we sent needed money but specifying TOTAL amount of flow // this help relative Splitters to calculate how to split money if(needed>0) { c.processFunds.value(needed)(_currentFlow); } } if(this.balance>0) { revert(); } } function() public { } }
contract WeiUnsortedSplitter is SplitterBase, IWeiReceiver { event ConsoleUint(string a, uint b); constructor(string _name) SplitterBase(_name) public { } // IWeiReceiver: // calculate only absolute outputs, but do not take into account the Percents function getMinWeiNeeded()public view returns(uint) { if(!isOpen()) { return 0; } uint absSum = 0; uint percentsMul100ReverseSum = 10000; for(uint i=0; i<childrenCount; ++i) { if(0!=IWeiReceiver(children[i]).getPercentsMul100()) { percentsMul100ReverseSum -= IWeiReceiver(children[i]).getPercentsMul100(); }else { absSum += IWeiReceiver(children[i]).getMinWeiNeeded(); } } if(percentsMul100ReverseSum==0) { return 0; }else { return 10000*absSum/percentsMul100ReverseSum; } } function getTotalWeiNeeded(uint _inputWei)public view returns(uint) { if(!isOpen()) { return 0; } uint total = 0; for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_inputWei); total = total + needed; } return total; } function getPercentsMul100()public view returns(uint) { uint total = 0; for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); total = total + c.getPercentsMul100(); } // truncate, no more than 100% allowed! if(total>10000) { return 10000; } return total; } function isNeedsMoney()public view returns(bool) { if(!isOpen()) { return false; } for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); // if at least 1 child needs money -> return true if(c.isNeedsMoney()) { return true; } } return false; } // WeiSplitter allows to receive money from ANY address // WeiSplitter should not hold any funds. Instead - it should split immediately // If WeiSplitter receives less or more money than needed -> exception function processFunds(uint _currentFlow) public payable { require(isOpen()); emit SplitterBaseProcessFunds(msg.sender, msg.value, _currentFlow); uint amount = msg.value; // TODO: can remove this line? // transfer below will throw if not enough money? require(amount>=getTotalWeiNeeded(_currentFlow)); // DO NOT SEND LESS! // DO NOT SEND MORE! for(uint i=0; i<childrenCount; ++i) { IWeiReceiver c = IWeiReceiver(children[i]); uint needed = c.getTotalWeiNeeded(_currentFlow); // send money. can throw! // we sent needed money but specifying TOTAL amount of flow // this help relative Splitters to calculate how to split money if(needed>0) { c.processFunds.value(needed)(_currentFlow); } } if(this.balance>0) { revert(); } } function() public { } }
49,971
329
// Fetch option market baseToken Address of base token. Same as underlying for calls andstrike currency for puts. Equal to 0x0 for ETH expiry Expiry time as timestamp isPut True if put, false if call /
function getMarket(IERC20 baseToken, uint256 expiry, bool isPut) external view returns (OptionMarket) { return markets[baseToken][expiry][isPut]; }
function getMarket(IERC20 baseToken, uint256 expiry, bool isPut) external view returns (OptionMarket) { return markets[baseToken][expiry][isPut]; }
29,908
53
// Pull final fee from liquidator.
feePayerData.collateralCurrency.safeTransferFrom( msg.sender, address(this), finalFeeBond.rawValue );
feePayerData.collateralCurrency.safeTransferFrom( msg.sender, address(this), finalFeeBond.rawValue );
10,764
2
// Modifier to allow only minters to mint/
modifier onlyMinter() virtual { require(creatorWhitelist[msg.sender] == true); _; }
modifier onlyMinter() virtual { require(creatorWhitelist[msg.sender] == true); _; }
40,466
18
// call swap method cost fee.
uint fee = ethFee; require(msg.value >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds;
uint fee = ethFee; require(msg.value >= fee,"TitanSwapV1 : no fee enough"); orderIds = orderIds.add(1); uint _orderId = orderIds;
51,479
10
// Maps team/advisor/etc. addresses to private RGT distribution quantities. /
mapping(address => uint256) public privateRgtAllocations;
mapping(address => uint256) public privateRgtAllocations;
32,007
3
// uint256 liquidity = address(this).balance;
uint256 liquidity = msg.value; _mint(msg.sender, liquidity);
uint256 liquidity = msg.value; _mint(msg.sender, liquidity);
524
433
// Returns the downcasted int152 from int256, reverting onoverflow (when the input is less than smallest int152 orgreater than largest int152). Counterpart to Solidity's `int152` operator. Requirements: - input must fit into 152 bits /
function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } }
function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } }
36,507
25
// Variables used during a borrow or withdraw./Used to avoid stack too deep.
struct BorrowWithdrawVars { uint256 onPool; // The working scaled balance on pool of the user. uint256 inP2P; // The working scaled balance in peer-to-peer of the user. uint256 toWithdraw; // The amount to withdraw from the pool (in underlying). uint256 toBorrow; // The amount to borrow on the pool (in underlying). }
struct BorrowWithdrawVars { uint256 onPool; // The working scaled balance on pool of the user. uint256 inP2P; // The working scaled balance in peer-to-peer of the user. uint256 toWithdraw; // The amount to withdraw from the pool (in underlying). uint256 toBorrow; // The amount to borrow on the pool (in underlying). }
41,570
133
// Check it&39;s expected and uncalled
require(queryIds[_queryId] == oraclizeState.Called); require(queriesByGame[_queryId] == GameNumber); _;
require(queryIds[_queryId] == oraclizeState.Called); require(queriesByGame[_queryId] == GameNumber); _;
10,354
29
// This contract enables to create multiple contract administrators.
contract CustomAdmin is Ownable { ///@notice List of administrators. mapping(address => bool) public admins; event AdminAdded(address indexed _address); event AdminRemoved(address indexed _address); ///@notice Validates if the sender is actually an administrator. modifier onlyAdmin() { require(admins[msg.sender] || msg.sender == owner); _; } ///@notice Adds the specified address to the list of administrators. ///@param _address The address to add to the administrator list. function addAdmin(address _address) external onlyAdmin { require(_address != address(0)); require(!admins[_address]); //The owner is already an admin and cannot be added. require(_address != owner); admins[_address] = true; emit AdminAdded(_address); } ///@notice Adds multiple addresses to the administrator list. ///@param _accounts The wallet addresses to add to the administrator list. function addManyAdmins(address[] _accounts) external onlyAdmin { for(uint8 i=0; i<_accounts.length; i++) { address account = _accounts[i]; ///Zero address cannot be an admin. ///The owner is already an admin and cannot be assigned. ///The address cannot be an existing admin. if(account != address(0) && !admins[account] && account != owner){ admins[account] = true; emit AdminAdded(_accounts[i]); } } } ///@notice Removes the specified address from the list of administrators. ///@param _address The address to remove from the administrator list. function removeAdmin(address _address) external onlyAdmin { require(_address != address(0)); require(admins[_address]); //The owner cannot be removed as admin. require(_address != owner); admins[_address] = false; emit AdminRemoved(_address); } ///@notice Removes multiple addresses to the administrator list. ///@param _accounts The wallet addresses to remove from the administrator list. function removeManyAdmins(address[] _accounts) external onlyAdmin { for(uint8 i=0; i<_accounts.length; i++) { address account = _accounts[i]; ///Zero address can neither be added or removed from this list. ///The owner is the super admin and cannot be removed. ///The address must be an existing admin in order for it to be removed. if(account != address(0) && admins[account] && account != owner){ admins[account] = false; emit AdminRemoved(_accounts[i]); } } } }
contract CustomAdmin is Ownable { ///@notice List of administrators. mapping(address => bool) public admins; event AdminAdded(address indexed _address); event AdminRemoved(address indexed _address); ///@notice Validates if the sender is actually an administrator. modifier onlyAdmin() { require(admins[msg.sender] || msg.sender == owner); _; } ///@notice Adds the specified address to the list of administrators. ///@param _address The address to add to the administrator list. function addAdmin(address _address) external onlyAdmin { require(_address != address(0)); require(!admins[_address]); //The owner is already an admin and cannot be added. require(_address != owner); admins[_address] = true; emit AdminAdded(_address); } ///@notice Adds multiple addresses to the administrator list. ///@param _accounts The wallet addresses to add to the administrator list. function addManyAdmins(address[] _accounts) external onlyAdmin { for(uint8 i=0; i<_accounts.length; i++) { address account = _accounts[i]; ///Zero address cannot be an admin. ///The owner is already an admin and cannot be assigned. ///The address cannot be an existing admin. if(account != address(0) && !admins[account] && account != owner){ admins[account] = true; emit AdminAdded(_accounts[i]); } } } ///@notice Removes the specified address from the list of administrators. ///@param _address The address to remove from the administrator list. function removeAdmin(address _address) external onlyAdmin { require(_address != address(0)); require(admins[_address]); //The owner cannot be removed as admin. require(_address != owner); admins[_address] = false; emit AdminRemoved(_address); } ///@notice Removes multiple addresses to the administrator list. ///@param _accounts The wallet addresses to remove from the administrator list. function removeManyAdmins(address[] _accounts) external onlyAdmin { for(uint8 i=0; i<_accounts.length; i++) { address account = _accounts[i]; ///Zero address can neither be added or removed from this list. ///The owner is the super admin and cannot be removed. ///The address must be an existing admin in order for it to be removed. if(account != address(0) && admins[account] && account != owner){ admins[account] = false; emit AdminRemoved(_accounts[i]); } } } }
32,949
24
// Emitted when the contract is deployed.Parameters are arbitrary.timestamp block time, in epoch seconds, when deployed sender becomes the address of owner initNum value assigned with constructor() Test address of this contract /
event TestConstructed(
event TestConstructed(
47,964
3
// Only tokens that are accepted by Aave can be passed to functions marked by this modifier./
modifier onlyAcceptedToken(address _asset){ address[] memory aaveAcceptedTokens = IPool(poolAddr).getReservesList(); bool found; for(uint8 j = 0; j < aaveAcceptedTokens.length; j++){ if(_asset == aaveAcceptedTokens[j]){ found = true; } } require(found, "token not approved"); _; }
modifier onlyAcceptedToken(address _asset){ address[] memory aaveAcceptedTokens = IPool(poolAddr).getReservesList(); bool found; for(uint8 j = 0; j < aaveAcceptedTokens.length; j++){ if(_asset == aaveAcceptedTokens[j]){ found = true; } } require(found, "token not approved"); _; }
2,416
23
// calculate tax per block (tpb)
uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt? CEO_tax_balance = CEO_tax_balance - debt; // deduct tax _burn(address(this), debt); // burn the tax emit TaxBurned(msg.sender, debt); } else {
uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch uint256 debt = (block.number - taxBurnBlock) * tpb; if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt? CEO_tax_balance = CEO_tax_balance - debt; // deduct tax _burn(address(this), debt); // burn the tax emit TaxBurned(msg.sender, debt); } else {
48,562
96
// Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver to address The address which you want to transfer to amount uint256 The amount of tokens to be transferredreturn true unless throwing /
function transferAndCall(address to, uint256 amount) external returns (bool);
function transferAndCall(address to, uint256 amount) external returns (bool);
22,696
5
// Super simple, insecure function /Reserve Ratio = Reserve Token Balance / (Continuous Token Supply x Continuous Token Price) /Continuous Token Price = Reserve Token Balance / (Continuous Token Supply x Reserve Ratio)
uint256 tokenSupply = currentERC20.balanceOf(msg.sender); uint256 reserveRatio = reserveTokenBalance / continuousTokenPrice; uint256 continuousTokenPriceNew = reserveTokenBalance / (tokenSupply * reserveRatio); return eth_sold * continuousTokenPriceNew;
uint256 tokenSupply = currentERC20.balanceOf(msg.sender); uint256 reserveRatio = reserveTokenBalance / continuousTokenPrice; uint256 continuousTokenPriceNew = reserveTokenBalance / (tokenSupply * reserveRatio); return eth_sold * continuousTokenPriceNew;
24,098
40
// network contract doesn't hold the tokens, do nothing
if (stepData.beneficiary != address(this)) { return; }
if (stepData.beneficiary != address(this)) { return; }
4,984
9
// Write data to be accessed by a given file key./key The key to access the written data./data The data to be written.
function writeFile(uint256 key, string memory data) external onlyOwner { files[key] = SSTORE2.write(bytes(data)); }
function writeFile(uint256 key, string memory data) external onlyOwner { files[key] = SSTORE2.write(bytes(data)); }
31,240
9
// Assumes ids are integers
function parseMintingBlobTokenId(bytes memory mintingBlob, uint start) internal pure returns (uint256, uint256) { uint256 result = 0; for (uint256 i = start; i < mintingBlob.length; i++) { if (mintingBlob[i] == "}") { return (result, i); } //Convert to integer result = (result * 10) + (uint8(mintingBlob[i]) - 48); }
function parseMintingBlobTokenId(bytes memory mintingBlob, uint start) internal pure returns (uint256, uint256) { uint256 result = 0; for (uint256 i = start; i < mintingBlob.length; i++) { if (mintingBlob[i] == "}") { return (result, i); } //Convert to integer result = (result * 10) + (uint8(mintingBlob[i]) - 48); }
13,446
3
// assert(b > 0);Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == bc + a % b);There is no case in which this doesn't hold
return a / b;
return a / b;
791
9
// Address of the WETH9 contract.
address public immutable wethAddress;
address public immutable wethAddress;
59,134
809
// Check whether to redeem rewards from strategy or not
if (!_skipFlags[3]) { uint256 _totSold; if (!_skipFlags[0]) {
if (!_skipFlags[3]) { uint256 _totSold; if (!_skipFlags[0]) {
29,632
56
// this func will only be called once
cp.ready = true;
cp.ready = true;
33,753
21
// if now is past the active period, users are eligible to claim
if (_currentPeriod > _checkpointedPeriod) {
if (_currentPeriod > _checkpointedPeriod) {
23,694
203
// Used to change `profitFactor`. `profitFactor` is used to determine if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` for more details.)This may only be called by governance or the strategist. _profitFactor A ratio to multiply anticipated`harvest()` gas cost against. /
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); }
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); }
6,592
25
// Reverts if sender does not have relay or admin role associated. /
modifier onlyAdminOrRelay() { require( isAdmin(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the admin role nor relay" ); _; }
modifier onlyAdminOrRelay() { require( isAdmin(msg.sender) || isRelay(msg.sender), "Operatorable: caller does not have the admin role nor relay" ); _; }
11,839
5
// Free mint function /
function mintFreeWithBone( uint256 boneTokenId,
function mintFreeWithBone( uint256 boneTokenId,
8,977
122
// uint256 balance; balance of this token
uint256 minBalance; //Minimum balance to send rewards / No use of spending 1$ to 1000 people.
uint256 minBalance; //Minimum balance to send rewards / No use of spending 1$ to 1000 people.
32,160
715
// res += val(coefficients[342] + coefficients[343]adjustments[23]).
res := addmod(res, mulmod(val, add(/*coefficients[342]*/ mload(0x2f00), mulmod(/*coefficients[343]*/ mload(0x2f20),
res := addmod(res, mulmod(val, add(/*coefficients[342]*/ mload(0x2f00), mulmod(/*coefficients[343]*/ mload(0x2f20),
17,714
37
// EmiVesting inerface/
interface IEmiVesting { function balanceOf(address beneficiary) external view returns (uint256); function getCrowdsaleLimit() external view returns (uint256); }
interface IEmiVesting { function balanceOf(address beneficiary) external view returns (uint256); function getCrowdsaleLimit() external view returns (uint256); }
70,384
20
//
owner.transfer( this.balance ); selfdestruct(owner);
owner.transfer( this.balance ); selfdestruct(owner);
6,027
245
// Loops through all of the positions and returns the smallest absolute value of the virtualUnit. return Min virtual unit across positions denominated as int256 /
function _getPositionsAbsMinimumVirtualUnit() internal view returns(int256) { // Additional assignment happens in the loop below uint256 minimumUnit = uint256(-1); for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // A default position exists if the default virtual unit is > 0 uint256 defaultUnit = _defaultPositionVirtualUnit(component).toUint256(); if (defaultUnit > 0 && defaultUnit < minimumUnit) { minimumUnit = defaultUnit; } address[] memory externalModules = _externalPositionModules(component); for (uint256 j = 0; j < externalModules.length; j++) { address currentModule = externalModules[j]; uint256 virtualUnit = _absoluteValue( _externalPositionVirtualUnit(component, currentModule) ); if (virtualUnit > 0 && virtualUnit < minimumUnit) { minimumUnit = virtualUnit; } } } return minimumUnit.toInt256(); }
function _getPositionsAbsMinimumVirtualUnit() internal view returns(int256) { // Additional assignment happens in the loop below uint256 minimumUnit = uint256(-1); for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // A default position exists if the default virtual unit is > 0 uint256 defaultUnit = _defaultPositionVirtualUnit(component).toUint256(); if (defaultUnit > 0 && defaultUnit < minimumUnit) { minimumUnit = defaultUnit; } address[] memory externalModules = _externalPositionModules(component); for (uint256 j = 0; j < externalModules.length; j++) { address currentModule = externalModules[j]; uint256 virtualUnit = _absoluteValue( _externalPositionVirtualUnit(component, currentModule) ); if (virtualUnit > 0 && virtualUnit < minimumUnit) { minimumUnit = virtualUnit; } } } return minimumUnit.toInt256(); }
17,505
97
// For a VF that has been resolved with winners and winner-profits,claim the share of the total ERC-20 winner-profits corresponding to the ERC-1155 balancesheld by the calling account on the specified `tokenIds`.If a tokenId is included multiple times, it will count only once. vfId The VF id. This VF must be in the Claimable_Payouts state. tokenIds The ERC-1155 token-ids for which to claim payouts.If a tokenId is included multiple times, it will count only once. /
function claimPayouts(uint256 vfId, uint256[] calldata tokenIds) public whenNotPaused
function claimPayouts(uint256 vfId, uint256[] calldata tokenIds) public whenNotPaused
22,414
11
// ERC223 /
library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } }
library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } }
2,819
75
// lower rate
if (info[_index].rate <= adjustment.target) {// if target met adjustments[_index].rate = 0;
if (info[_index].rate <= adjustment.target) {// if target met adjustments[_index].rate = 0;
50,260
13
// Returns the decimals places of the token. /
function decimals() external view returns (uint8);
function decimals() external view returns (uint8);
33,562
6
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) }
assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) }
3,228
14
// The amount invested will be swapped to the current allocations of the PairedTokens. The rest will remain in BaseToken.
for (uint i=0; i < pairedTokenArray.length; i++) { swapAutoSlippage(baseTokenAddress, pairedTokens[pairedTokenArray[i]].tokenAddress, amount.mul(pairedTokens[pairedTokenArray[i]].maxAllocation.mul(UNITY.sub(pairedTokens[pairedTokenArray[i]].currentAvailableAllocation))).div(UNITY).div(UNITY), pairedTokens[pairedTokenArray[i]].directPath); }
for (uint i=0; i < pairedTokenArray.length; i++) { swapAutoSlippage(baseTokenAddress, pairedTokens[pairedTokenArray[i]].tokenAddress, amount.mul(pairedTokens[pairedTokenArray[i]].maxAllocation.mul(UNITY.sub(pairedTokens[pairedTokenArray[i]].currentAvailableAllocation))).div(UNITY).div(UNITY), pairedTokens[pairedTokenArray[i]].directPath); }
15,960
13
// SafeBox requires bytes32[] proof to claim. see alpha-homora-v2-contract/blob/master/contracts/SafeBox.solL67 for more details
function harvest(uint256 totalAmount, bytes32[] memory proof) external { uint256 balanceBeforeClaim = IERC20(supplyToken).balanceOf(address(this)); // Claim from homora v2. after verify merkle root, we get totalAmount - claimed[msg.sender] // then claimed[msg.sender] is set to totalAmount ISafeBox(ibToken).claim(totalAmount, proof); uint256 balanceAfterClaim = IERC20(supplyToken).balanceOf(address(this)); // deposit new usdt into ibToken uint256 _buyAmount = balanceAfterClaim - balanceBeforeClaim; IERC20(supplyToken).safeIncreaseAllowance(ibToken, _buyAmount); ISafeBox(ibToken).deposit(_buyAmount); }
function harvest(uint256 totalAmount, bytes32[] memory proof) external { uint256 balanceBeforeClaim = IERC20(supplyToken).balanceOf(address(this)); // Claim from homora v2. after verify merkle root, we get totalAmount - claimed[msg.sender] // then claimed[msg.sender] is set to totalAmount ISafeBox(ibToken).claim(totalAmount, proof); uint256 balanceAfterClaim = IERC20(supplyToken).balanceOf(address(this)); // deposit new usdt into ibToken uint256 _buyAmount = balanceAfterClaim - balanceBeforeClaim; IERC20(supplyToken).safeIncreaseAllowance(ibToken, _buyAmount); ISafeBox(ibToken).deposit(_buyAmount); }
23,464
7
// Assert that the mintId has not been used before
require(!mintIds[mintId]);
require(!mintIds[mintId]);
24,764
53
// Update reward info
rInfo.rewardsPerTokenPoints = currentRewardPoints; rInfo.lastUpdateTime = BoringMath.to48(block.timestamp) ; _updateTokenRewards(_tokenId, rewardToken, currentRewardPoints);
rInfo.rewardsPerTokenPoints = currentRewardPoints; rInfo.lastUpdateTime = BoringMath.to48(block.timestamp) ; _updateTokenRewards(_tokenId, rewardToken, currentRewardPoints);
59,606
55
// Caller signals to the system that they want a refund on this chain, which they set as the`repaymentChainId` on the original fillRelay() call on the `destinationChainId`. An observer should bebe able to 1-to-1 match the emitted RefundRequested event with the FilledRelay event on the `destinationChainId`. This function could be used to artificially inflate the `fillCounter`, allowing the caller to "frontrun"and cancel pending fills in the mempool. This would in the worst case censor fills at the cost of the caller'sgas costs. We don't view this as a major issue as the fill can be resubmitted and obtain the same incentive,since
function requestRefund( address refundToken, uint256 amount, uint256 originChainId, uint256 destinationChainId, int64 realizedLpFeePct, uint32 depositId, uint256 fillBlock, uint256 maxCount
function requestRefund( address refundToken, uint256 amount, uint256 originChainId, uint256 destinationChainId, int64 realizedLpFeePct, uint32 depositId, uint256 fillBlock, uint256 maxCount
36,232
201
// Want tokens moved from user -> AUTOFarm (AUTO allocation) -> Strat (compounding)
function deposit(uint256 _pid, uint256 _wantAmt) public nonReentrant { updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.shares > 0) { uint256 pending = user.shares.mul(pool.accAUTOPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeAUTOTransfer(msg.sender, pending); } } if (_wantAmt > 0) { pool.want.safeTransferFrom( address(msg.sender), address(this), _wantAmt ); pool.want.safeIncreaseAllowance(pool.strat, _wantAmt); uint256 sharesAdded = IStrategy(poolInfo[_pid].strat).deposit(msg.sender, _wantAmt); user.shares = user.shares.add(sharesAdded); } user.rewardDebt = user.shares.mul(pool.accAUTOPerShare).div(1e12); emit Deposit(msg.sender, _pid, _wantAmt); }
function deposit(uint256 _pid, uint256 _wantAmt) public nonReentrant { updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.shares > 0) { uint256 pending = user.shares.mul(pool.accAUTOPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeAUTOTransfer(msg.sender, pending); } } if (_wantAmt > 0) { pool.want.safeTransferFrom( address(msg.sender), address(this), _wantAmt ); pool.want.safeIncreaseAllowance(pool.strat, _wantAmt); uint256 sharesAdded = IStrategy(poolInfo[_pid].strat).deposit(msg.sender, _wantAmt); user.shares = user.shares.add(sharesAdded); } user.rewardDebt = user.shares.mul(pool.accAUTOPerShare).div(1e12); emit Deposit(msg.sender, _pid, _wantAmt); }
30,953
25
// Sell Fee
uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 5;
uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 5;
2,872
9
// PURPOSE: Revoke store owner privileges by setting checkBool to false
function removeStoreOwner(address _addr) public onlyAdmin whenNotPaused { emit RemovedStoreOwner(_addr); storeOwners[_addr] = false; }
function removeStoreOwner(address _addr) public onlyAdmin whenNotPaused { emit RemovedStoreOwner(_addr); storeOwners[_addr] = false; }
9,766
18
// handle buy/sell taxes
if (!_isExcludedFromFee[from] || !_isExcludedFromFee[to] || from != _receiptAddress || to != _receiptAddress) {
if (!_isExcludedFromFee[from] || !_isExcludedFromFee[to] || from != _receiptAddress || to != _receiptAddress) {
35,159
1
// ========Public View Functions======== // Returns the total amount of rewards a given address is able to withdraw. _account Address of a reward recipientreturn A uint256 representing the rewards `account` can withdraw /
function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; }
function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; }
16,455
77
// Whether `a` is greater than `b`. a a FixedPoint. b a FixedPoint.return True if `a > b`, or False. /
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; }
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; }
26,618
86
// import "/Users/present/code/brownie-sett/deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "/Users/present/code/brownie-sett/deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";/ Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions. By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; }
* can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; }
25,782
47
// If the amount being transfered is more than the balance of the account the transfer returns false
uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount);
uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount);
22,383