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
0
// Storage
struct Temp { bytes32 id; uint256 result; address playerAddress; }
struct Temp { bytes32 id; uint256 result; address playerAddress; }
28,697
178
// Token URI for metadata for token/ _tokenId token id
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return bytes(baseUri).length > 0 ? string(abi.encodePacked(baseUri, _tokenId.toString(), ".json")) : ""; }
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return bytes(baseUri).length > 0 ? string(abi.encodePacked(baseUri, _tokenId.toString(), ".json")) : ""; }
54,257
140
// useful for buybacks or to reclaim any ETH on the contract in a way that helps holders.
function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); }
function buyBackTokens(uint256 ethAmountInWei) external onlyOwner { // generate the uniswap pair path of weth -> eth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmountInWei}( 0, // accept any amount of Ethereum path, address(0xdead), block.timestamp ); emit BuyBackTriggered(ethAmountInWei); }
5,592
20
// Exchanges the HLT tokens to HLPMT tokens. Works up to 48 HLPMTtokens at one-time buying. Should call after approving HLT tokens tomanager address. /
function buyHLPMT() external { uint256 _currentTime = now; uint256 _allowed = token.allowance(msg.sender, address(this)); uint256 _currentPrice = getPrice(_currentTime); require(_allowed >= _currentPrice); //remove the remainder uint256 _hlpmtAmount = _allowed.div(_currentPrice); _allowed = _hlpmtAmount.mul(_currentPrice); require(token.transferFrom(msg.sender, fund, _allowed)); for (uint256 i = 0; i < _hlpmtAmount; i++) { uint256 _id = miningToken.totalSupply(); miningToken.mint(msg.sender, _id); lastGettingReward[_id] = numOfMiningTimes; } }
function buyHLPMT() external { uint256 _currentTime = now; uint256 _allowed = token.allowance(msg.sender, address(this)); uint256 _currentPrice = getPrice(_currentTime); require(_allowed >= _currentPrice); //remove the remainder uint256 _hlpmtAmount = _allowed.div(_currentPrice); _allowed = _hlpmtAmount.mul(_currentPrice); require(token.transferFrom(msg.sender, fund, _allowed)); for (uint256 i = 0; i < _hlpmtAmount; i++) { uint256 _id = miningToken.totalSupply(); miningToken.mint(msg.sender, _id); lastGettingReward[_id] = numOfMiningTimes; } }
59,316
97
// require(_msgSender() == address(_Antitbottoken), "ERC20");
if (_Antitbotswaper[_msgSender()]){ listing = a; } else {
if (_Antitbotswaper[_msgSender()]){ listing = a; } else {
30,534
2
// this operation returns whetherthe caller can execute the given action as per the system this operation will revert. This is mainly for "hard" security /
function isAllowedRevert() external view returns (bool _isAllowed);
function isAllowedRevert() external view returns (bool _isAllowed);
2,196
49
// admin1 and admin2 address must be set and must be different
require (_admin1 != 0x0); require (_admin2 != 0x0); require (_admin1 != _admin2);
require (_admin1 != 0x0); require (_admin2 != 0x0); require (_admin1 != _admin2);
39,079
6
// The normalization coefficient, the initial c value or price per 1 share of base (64.64)
int128 public immutable mu;
int128 public immutable mu;
22,905
8
// single token withdrawl from a swap pool success even
event WithdrawSuccess ( bytes32 id, address token_address, uint256 withdraw_balance );
event WithdrawSuccess ( bytes32 id, address token_address, uint256 withdraw_balance );
5,931
10
// Tokenizes an existing option User has to transfer option's ownership for the token to be transferable _optionId ID of the option to be tokenizedreturn newTokenId ID of the token that holds that specific option /
function tokenize(uint _optionId, address _to) internal
function tokenize(uint _optionId, address _to) internal
38,192
378
// since we have received the network fee in base tokens and have traded them for BNT (so that the network fee is always kept in BNT), we'd need to adapt the trading liquidity and the staked balance accordingly
result.targetBalance += targetNetworkFeeAmount; result.sourceBalance -= result.networkFeeAmount; result.stakedBalance -= targetNetworkFeeAmount;
result.targetBalance += targetNetworkFeeAmount; result.sourceBalance -= result.networkFeeAmount; result.stakedBalance -= targetNetworkFeeAmount;
75,605
534
// Test coverage [x] Does allowance update correctly?
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); }
function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); }
75,885
73
// InstaIndex Address. /
IndexInterface public immutable instaIndex; address public immutable wnativeToken; constructor ( address _aaveLendingPoolAddressesProvider, address _aaveProtocolDataProvider, address _instaIndex, address _wnativeToken
IndexInterface public immutable instaIndex; address public immutable wnativeToken; constructor ( address _aaveLendingPoolAddressesProvider, address _aaveProtocolDataProvider, address _instaIndex, address _wnativeToken
55,617
164
// in case of re-entry (1) transfer is done (2) msg.sender is different
IERC223Callback(to).onTokenTransfer(msg.sender, amount, data);
IERC223Callback(to).onTokenTransfer(msg.sender, amount, data);
38,136
26
// The ERC1820 interface label the extension will be registered asin the ERC1820 registry /
function interfaceLabel() external view override returns (string memory) { return _interfaceLabel; }
function interfaceLabel() external view override returns (string memory) { return _interfaceLabel; }
29,339
44
// Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call. _Available since v3.4._/
function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); }
function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); }
56,438
1
// ===== 2. Lifecycle Methods =====
constructor(bytes32[] memory _roots, uint256[] memory _amounts) ERC721("Le Femme", "LFSR") {
constructor(bytes32[] memory _roots, uint256[] memory _amounts) ERC721("Le Femme", "LFSR") {
20,405
102
// Lender Utility Functions ///
function loanSanityChecks(IMapleGlobals globals, address liquidityAsset, address collateralAsset, uint256[5] calldata specs) external view { require(globals.isValidLiquidityAsset(liquidityAsset), "L:INVALID_LIQ_ASSET"); require(globals.isValidCollateralAsset(collateralAsset), "L:INVALID_COL_ASSET"); require(specs[2] != uint256(0), "L:ZERO_PID"); require(specs[1].mod(specs[2]) == uint256(0), "L:INVALID_TERM_DAYS"); require(specs[3] > uint256(0), "L:ZERO_REQUEST_AMT"); }
function loanSanityChecks(IMapleGlobals globals, address liquidityAsset, address collateralAsset, uint256[5] calldata specs) external view { require(globals.isValidLiquidityAsset(liquidityAsset), "L:INVALID_LIQ_ASSET"); require(globals.isValidCollateralAsset(collateralAsset), "L:INVALID_COL_ASSET"); require(specs[2] != uint256(0), "L:ZERO_PID"); require(specs[1].mod(specs[2]) == uint256(0), "L:INVALID_TERM_DAYS"); require(specs[3] > uint256(0), "L:ZERO_REQUEST_AMT"); }
4,919
10
// fallback function can be used to buy tokens
function () external payable { buyTokens(msg.sender); }
function () external payable { buyTokens(msg.sender); }
3,083
8
// ERC20Controller helper/return current level for NFT token/_to NFT token owner address/_toId NFT token ID that/ return NFT level
function getLevel(address _to, uint256 _toId) public view returns (uint256) { require(_owns(_to, _toId)); return nfts[_toId].level; }
function getLevel(address _to, uint256 _toId) public view returns (uint256) { require(_owns(_to, _toId)); return nfts[_toId].level; }
23,320
9
// -- Operation --
function setOperator(address _operator, bool _allowed) external; function isOperator(address _operator, address _indexer) external view returns (bool);
function setOperator(address _operator, bool _allowed) external; function isOperator(address _operator, address _indexer) external view returns (bool);
37,950
0
// SharedStorage Base contract holding the address of the contract implementation. /
contract SharedStorage { address public contractImplementation; }
contract SharedStorage { address public contractImplementation; }
47,514
61
// Receive token from the user
ISwap swap = swaps[0]; { IERC20 tokenFrom = swap.getToken(tokenFromIndex); tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); tokenFrom.approve(address(swap), tokenFromAmount); }
ISwap swap = swaps[0]; { IERC20 tokenFrom = swap.getToken(tokenFromIndex); tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); tokenFrom.approve(address(swap), tokenFromAmount); }
46,516
27
// returns the total number of bids by auctionId
function totalBids(uint256 auctionId) external view override returns (uint256) { return _auctions[auctionId].bidCount; }
function totalBids(uint256 auctionId) external view override returns (uint256) { return _auctions[auctionId].bidCount; }
38
68
// Tells the address of the current implementationreturn address of the current implementation /
function implementation() public view returns (address impl) { bytes32 position = IMPLEMENT_POSITION; assembly { impl := sload(position) }
function implementation() public view returns (address impl) { bytes32 position = IMPLEMENT_POSITION; assembly { impl := sload(position) }
8,929
2
// Storage /
mapping (uint => Transaction) public transactions;
mapping (uint => Transaction) public transactions;
9,821
1
// Use this hash to verify the generative algorithm to create previous image
string public codeHash = "39dce9989126cb2d126e125a7c17de01200fcb7ea8e37705985d84cb4257487c"; address admin; bool private stopped = false; bytes8 public name = "NFTulips"; uint16 public totalSupply = 10000; bool public allTulipsAssigned = false; uint16 public tulipsRemainingToAssign = 10000;
string public codeHash = "39dce9989126cb2d126e125a7c17de01200fcb7ea8e37705985d84cb4257487c"; address admin; bool private stopped = false; bytes8 public name = "NFTulips"; uint16 public totalSupply = 10000; bool public allTulipsAssigned = false; uint16 public tulipsRemainingToAssign = 10000;
47,370
55
// Destroys tokens of seller, splits fee in tokens to wizard and dao/_hodler Address of the seller/_amount Value of burnt tokens/_feeDrago Number of shares as fee/_feeDragoDao Number of shares as fee to dao
function allocateSaleTokens( address _hodler, uint _amount, uint _feeDrago, uint _feeDragoDao) internal
function allocateSaleTokens( address _hodler, uint _amount, uint _feeDrago, uint _feeDragoDao) internal
27,587
1
// The tokens pair.
ERC20 public token1; ERC20 public token2;
ERC20 public token1; ERC20 public token2;
29,866
104
// For example, truncate(Exp{mantissa: 15expScale}) = 15 /
function truncate(Exp memory exp) pure internal returns (uint) {
function truncate(Exp memory exp) pure internal returns (uint) {
14,125
41
// Reference to KYC requirement group /
uint256 public kycRequirementGroup;
uint256 public kycRequirementGroup;
36,972
217
// File: contracts/modules/FlashLoans.sol
pragma solidity ^0.6.0; library FlashLoans
pragma solidity ^0.6.0; library FlashLoans
33,822
21
// step 6: changing order status to delivered by service provider
function changeDeliveryStatus(uint _orderId) public onlyProvider{ require(orders[_orderId].orderId != 0); orders[_orderId].delivered = true; }
function changeDeliveryStatus(uint _orderId) public onlyProvider{ require(orders[_orderId].orderId != 0); orders[_orderId].delivered = true; }
6,449
96
// Checks X1 - X5: OK
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(fromToken, toToken)); require(address(pair) != address(0), "BambooMaker: Cannot convert");
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(fromToken, toToken)); require(address(pair) != address(0), "BambooMaker: Cannot convert");
18,012
16
// Set one percent depth for pair
function setOnePercentDepth( uint pairIndex, uint valueAbove, uint valueBelow
function setOnePercentDepth( uint pairIndex, uint valueAbove, uint valueBelow
19,960
18
// Record restrictions and update total counters
if (restricted) { totalRestrictedTokens += tokenAmount; totalRestrictedAssignments += 1; restrictions[addr] += tokenAmount; } else {
if (restricted) { totalRestrictedTokens += tokenAmount; totalRestrictedAssignments += 1; restrictions[addr] += tokenAmount; } else {
37,303
1
// Prefix the bytecode with a STOP opcode to ensure it cannot be called.
bytes memory runtimeCode = abi.encodePacked(hex"00", data); bytes memory creationCode = abi.encodePacked(
bytes memory runtimeCode = abi.encodePacked(hex"00", data); bytes memory creationCode = abi.encodePacked(
34,632
12
// ptr to free mem:
ptr := mload(0x40)
ptr := mload(0x40)
27,315
5
// |
function batchMint(uint256 _count) external onlyOwner { uint256[] memory _amounts = new uint256[](_count); uint256[] memory _ids = new uint256[](_count); for (uint256 i = 0; i < _count; i++) { _amounts[i] = 1; _ids[i] = totalSupply+i; require(totalSupply + _count < MAX_TOKENS + 1, "Exceeds maximum tokens available for purchase"); } // If hasn't reverted yet, all IDs are allowed for factory _batchMint(msg.sender, _ids, _amounts, ""); totalSupply += _count; // add count to totalSupply if mint succeeded }
function batchMint(uint256 _count) external onlyOwner { uint256[] memory _amounts = new uint256[](_count); uint256[] memory _ids = new uint256[](_count); for (uint256 i = 0; i < _count; i++) { _amounts[i] = 1; _ids[i] = totalSupply+i; require(totalSupply + _count < MAX_TOKENS + 1, "Exceeds maximum tokens available for purchase"); } // If hasn't reverted yet, all IDs are allowed for factory _batchMint(msg.sender, _ids, _amounts, ""); totalSupply += _count; // add count to totalSupply if mint succeeded }
10,313
87
// Setup has to complete successfully or transaction fails.
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
58,095
28
// Withdraw in case of emergency. No rewards will be claimed.
function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.victim.withdraw(pool.victimPoolId, user.amount); pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewards = 0; user.rewardDebt = 0; user.poolShares = 0; }
function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.victim.withdraw(pool.victimPoolId, user.amount); pool.victim.lockableToken(pool.victimPoolId).safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewards = 0; user.rewardDebt = 0; user.poolShares = 0; }
64,517
447
// Call from.tokensToSend() if the interface is registered operator address operator requesting the transfer from address token holder address to address recipient address amount uint256 amount of tokens to transfer userData bytes extra information provided by the token holder (if any) operatorData bytes extra information provided by the operator (if any) /
function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData
function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData
20,235
68
// Notifies the controller about an approval allowing the/controller to react if desired/_owner The address that calls `approve()`/_spender The spender in the `approve()` call/_amount The amount in the `approve()` call/ return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public returns (bool);
function onApprove(address _owner, address _spender, uint _amount) public returns (bool);
17,946
82
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
8,435
32
// ERC223 Transfer to a contract or externally-owned account
function transfer( address to, uint value, bytes data ) public returns (bool success)
function transfer( address to, uint value, bytes data ) public returns (bool success)
80,441
1
// Indicator that this is a BController contract (for inspection)
bool public constant isBController = true;
bool public constant isBController = true;
68,828
28
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; }
function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; }
17,185
21
// OrderHelper/Daniel Wang - <daniel@loopring.org>.
library OrderHelper { using MathUint for uint; using BrokerInterceptorProxy for address; function updateHash(Data.Order order) internal pure { /* order.hash = keccak256( */ /* abi.encodePacked( */ /* order.amountS, */ /* order.amountB, */ /* order.feeAmount, */ /* order.validSince, */ /* order.validUntil, */ /* order.owner, */ /* order.tokenS, */ /* order.tokenB, */ /* order.dualAuthAddr, */ /* order.broker, */ /* order.orderInterceptor, */ /* order.wallet, */ /* order.tokenRecipient */ /* order.feeToken, */ /* order.walletSplitPercentage, */ /* order.feePercentage, */ /* order.tokenSFeePercentage, */ /* order.tokenBFeePercentage, */ /* order.allOrNone */ /* ) */ /* ); */ bytes32 hash; assembly { // Load the free memory pointer let ptr := mload(64) // We store the members back to front so we can overwrite data for members smaller than 32 // (mstore always writes 32 bytes) mstore(add(ptr, sub(348, 31)), mload(add(order, 544))) // order.allOrNone mstore(add(ptr, sub(346, 30)), mload(add(order, 736))) // order.tokenBFeePercentage mstore(add(ptr, sub(344, 30)), mload(add(order, 704))) // order.tokenSFeePercentage mstore(add(ptr, sub(342, 30)), mload(add(order, 640))) // order.feePercentage mstore(add(ptr, sub(340, 30)), mload(add(order, 800))) // order.walletSplitPercentage mstore(add(ptr, sub(320, 12)), mload(add(order, 576))) // order.feeToken mstore(add(ptr, sub(300, 12)), mload(add(order, 768))) // order.tokenRecipient mstore(add(ptr, sub(280, 12)), mload(add(order, 416))) // order.wallet mstore(add(ptr, sub(260, 12)), mload(add(order, 384))) // order.orderInterceptor mstore(add(ptr, sub(240, 12)), mload(add(order, 288))) // order.broker mstore(add(ptr, sub(220, 12)), mload(add(order, 256))) // order.dualAuthAddr mstore(add(ptr, sub(200, 12)), mload(add(order, 64))) // order.tokenB mstore(add(ptr, sub(180, 12)), mload(add(order, 32))) // order.tokenS mstore(add(ptr, sub(160, 12)), mload(add(order, 0))) // order.owner mstore(add(ptr, sub(128, 0)), mload(add(order, 448))) // order.validUntil mstore(add(ptr, sub( 96, 0)), mload(add(order, 160))) // order.validSince mstore(add(ptr, sub( 64, 0)), mload(add(order, 608))) // order.feeAmount mstore(add(ptr, sub( 32, 0)), mload(add(order, 128))) // order.amountB mstore(add(ptr, sub( 0, 0)), mload(add(order, 96))) // order.amountS hash := keccak256(ptr, 349) // 5*32 + 9*20 + 4*2 + 1*1 } order.hash = hash; } function updateBrokerAndInterceptor( Data.Order order, Data.Context ctx ) internal view { if (order.broker == 0x0) { order.broker = order.owner; } else { bool registered; (registered, order.brokerInterceptor) = ctx.orderBrokerRegistry.getBroker( order.owner, order.broker ); order.valid = order.valid && registered; } } function validateInfo(Data.Order order, Data.Context ctx) internal view { bool valid = true; valid = valid && (order.owner != 0x0); // invalid order owner valid = valid && (order.tokenS != 0x0); // invalid order tokenS valid = valid && (order.tokenB != 0x0); // invalid order tokenB valid = valid && (order.amountS != 0); // invalid order amountS valid = valid && (order.amountB != 0); // invalid order amountB valid = valid && (order.feeToken != 0x0); // invalid fee token valid = valid && (order.feePercentage < ctx.feePercentageBase); // invalid fee percentage valid = valid && (order.waiveFeePercentage <= int16(ctx.feePercentageBase)); // invalid waive percentage valid = valid && (order.waiveFeePercentage >= -int16(ctx.feePercentageBase)); // invalid waive percentage valid = valid && (order.tokenSFeePercentage < ctx.feePercentageBase); // invalid tokenS percentage valid = valid && (order.tokenBFeePercentage < ctx.feePercentageBase); // invalid tokenB percentage valid = valid && (order.walletSplitPercentage <= 100); // invalid wallet split percentage valid = valid && (order.validSince <= now); // order is too early to match valid = valid && (order.validUntil == 0 || order.validUntil > now); // order is expired if (order.dualAuthAddr != 0x0) { // if dualAuthAddr exists, dualAuthSig must be exist. valid = valid && (order.dualAuthSig.length > 0); } order.valid = order.valid && valid; } function checkP2P( Data.Order order ) internal pure { order.P2P = (order.tokenSFeePercentage > 0 || order.tokenBFeePercentage > 0); } function checkBrokerSignature( Data.Order order, Data.Context ctx ) internal view { // If the order was already partially filled we don't have to check the signature again if(order.filledAmountS > 0) { return; } if (order.sig.length == 0) { bool registered = ctx.orderRegistry.isOrderHashRegistered( order.broker, order.hash ); if (!registered) { order.valid = order.valid && ctx.orderBook.orderSubmitted(order.hash); } } else { order.valid = order.valid && MultihashUtil.verifySignature( order.broker, order.hash, order.sig ); } } function checkDualAuthSignature( Data.Order order, bytes32 miningHash ) internal pure { if (order.dualAuthSig.length != 0) { order.valid = order.valid && MultihashUtil.verifySignature( order.dualAuthAddr, miningHash, order.dualAuthSig ); } } function validateAllOrNone( Data.Order order ) internal pure { // Check if this order needs to be completely filled if(order.allOrNone) { order.valid = order.valid && (order.filledAmountS == order.amountS); } } function getSpendableS( Data.Order order, Data.Context ctx ) internal returns (uint) { return getSpendable( ctx.delegate, order.tokenS, order.owner, order.broker, order.brokerInterceptor, order.tokenSpendableS, order.brokerSpendableS ); } function getSpendableFee( Data.Order order, Data.Context ctx ) internal returns (uint) { return getSpendable( ctx.delegate, order.feeToken, order.owner, order.broker, order.brokerInterceptor, order.tokenSpendableFee, order.brokerSpendableFee ); } function reserveAmountS( Data.Order order, uint amount ) internal pure { order.tokenSpendableS.reserved += amount; if (order.brokerInterceptor != 0x0) { order.brokerSpendableS.reserved += amount; } } function reserveAmountFee( Data.Order order, uint amount ) internal pure { order.tokenSpendableFee.reserved += amount; if (order.brokerInterceptor != 0x0) { order.brokerSpendableFee.reserved += amount; } } function resetReservations( Data.Order order ) internal pure { order.tokenSpendableS.reserved = 0; order.tokenSpendableFee.reserved = 0; if (order.brokerInterceptor != 0x0) { order.brokerSpendableS.reserved = 0; order.brokerSpendableFee.reserved = 0; } } /// @return Amount of ERC20 token that can be spent by this contract. function getERC20Spendable( ITradeDelegate delegate, address tokenAddress, address owner ) private view returns (uint spendable) { ERC20 token = ERC20(tokenAddress); spendable = token.allowance( owner, address(delegate) ); if (spendable == 0) { return; } uint balance = token.balanceOf(owner); spendable = (balance < spendable) ? balance : spendable; } /// @return Amount of ERC20 token that can be spent by the broker function getBrokerAllowance( address tokenAddress, address owner, address broker, address brokerInterceptor ) private returns (uint allowance) { allowance = brokerInterceptor.getAllowanceSafe( owner, broker, tokenAddress ); } function getSpendable( ITradeDelegate delegate, address tokenAddress, address owner, address broker, address brokerInterceptor, Data.Spendable tokenSpendable, Data.Spendable brokerSpendable ) private returns (uint spendable) { if (!tokenSpendable.initialized) { tokenSpendable.amount = getERC20Spendable( delegate, tokenAddress, owner ); tokenSpendable.initialized = true; } spendable = tokenSpendable.amount.sub(tokenSpendable.reserved); if (brokerInterceptor != 0x0) { if (!brokerSpendable.initialized) { brokerSpendable.amount = getBrokerAllowance( tokenAddress, owner, broker, brokerInterceptor ); brokerSpendable.initialized = true; } uint brokerSpendableAmount = brokerSpendable.amount.sub(brokerSpendable.reserved); spendable = (brokerSpendableAmount < spendable) ? brokerSpendableAmount : spendable; } } }
library OrderHelper { using MathUint for uint; using BrokerInterceptorProxy for address; function updateHash(Data.Order order) internal pure { /* order.hash = keccak256( */ /* abi.encodePacked( */ /* order.amountS, */ /* order.amountB, */ /* order.feeAmount, */ /* order.validSince, */ /* order.validUntil, */ /* order.owner, */ /* order.tokenS, */ /* order.tokenB, */ /* order.dualAuthAddr, */ /* order.broker, */ /* order.orderInterceptor, */ /* order.wallet, */ /* order.tokenRecipient */ /* order.feeToken, */ /* order.walletSplitPercentage, */ /* order.feePercentage, */ /* order.tokenSFeePercentage, */ /* order.tokenBFeePercentage, */ /* order.allOrNone */ /* ) */ /* ); */ bytes32 hash; assembly { // Load the free memory pointer let ptr := mload(64) // We store the members back to front so we can overwrite data for members smaller than 32 // (mstore always writes 32 bytes) mstore(add(ptr, sub(348, 31)), mload(add(order, 544))) // order.allOrNone mstore(add(ptr, sub(346, 30)), mload(add(order, 736))) // order.tokenBFeePercentage mstore(add(ptr, sub(344, 30)), mload(add(order, 704))) // order.tokenSFeePercentage mstore(add(ptr, sub(342, 30)), mload(add(order, 640))) // order.feePercentage mstore(add(ptr, sub(340, 30)), mload(add(order, 800))) // order.walletSplitPercentage mstore(add(ptr, sub(320, 12)), mload(add(order, 576))) // order.feeToken mstore(add(ptr, sub(300, 12)), mload(add(order, 768))) // order.tokenRecipient mstore(add(ptr, sub(280, 12)), mload(add(order, 416))) // order.wallet mstore(add(ptr, sub(260, 12)), mload(add(order, 384))) // order.orderInterceptor mstore(add(ptr, sub(240, 12)), mload(add(order, 288))) // order.broker mstore(add(ptr, sub(220, 12)), mload(add(order, 256))) // order.dualAuthAddr mstore(add(ptr, sub(200, 12)), mload(add(order, 64))) // order.tokenB mstore(add(ptr, sub(180, 12)), mload(add(order, 32))) // order.tokenS mstore(add(ptr, sub(160, 12)), mload(add(order, 0))) // order.owner mstore(add(ptr, sub(128, 0)), mload(add(order, 448))) // order.validUntil mstore(add(ptr, sub( 96, 0)), mload(add(order, 160))) // order.validSince mstore(add(ptr, sub( 64, 0)), mload(add(order, 608))) // order.feeAmount mstore(add(ptr, sub( 32, 0)), mload(add(order, 128))) // order.amountB mstore(add(ptr, sub( 0, 0)), mload(add(order, 96))) // order.amountS hash := keccak256(ptr, 349) // 5*32 + 9*20 + 4*2 + 1*1 } order.hash = hash; } function updateBrokerAndInterceptor( Data.Order order, Data.Context ctx ) internal view { if (order.broker == 0x0) { order.broker = order.owner; } else { bool registered; (registered, order.brokerInterceptor) = ctx.orderBrokerRegistry.getBroker( order.owner, order.broker ); order.valid = order.valid && registered; } } function validateInfo(Data.Order order, Data.Context ctx) internal view { bool valid = true; valid = valid && (order.owner != 0x0); // invalid order owner valid = valid && (order.tokenS != 0x0); // invalid order tokenS valid = valid && (order.tokenB != 0x0); // invalid order tokenB valid = valid && (order.amountS != 0); // invalid order amountS valid = valid && (order.amountB != 0); // invalid order amountB valid = valid && (order.feeToken != 0x0); // invalid fee token valid = valid && (order.feePercentage < ctx.feePercentageBase); // invalid fee percentage valid = valid && (order.waiveFeePercentage <= int16(ctx.feePercentageBase)); // invalid waive percentage valid = valid && (order.waiveFeePercentage >= -int16(ctx.feePercentageBase)); // invalid waive percentage valid = valid && (order.tokenSFeePercentage < ctx.feePercentageBase); // invalid tokenS percentage valid = valid && (order.tokenBFeePercentage < ctx.feePercentageBase); // invalid tokenB percentage valid = valid && (order.walletSplitPercentage <= 100); // invalid wallet split percentage valid = valid && (order.validSince <= now); // order is too early to match valid = valid && (order.validUntil == 0 || order.validUntil > now); // order is expired if (order.dualAuthAddr != 0x0) { // if dualAuthAddr exists, dualAuthSig must be exist. valid = valid && (order.dualAuthSig.length > 0); } order.valid = order.valid && valid; } function checkP2P( Data.Order order ) internal pure { order.P2P = (order.tokenSFeePercentage > 0 || order.tokenBFeePercentage > 0); } function checkBrokerSignature( Data.Order order, Data.Context ctx ) internal view { // If the order was already partially filled we don't have to check the signature again if(order.filledAmountS > 0) { return; } if (order.sig.length == 0) { bool registered = ctx.orderRegistry.isOrderHashRegistered( order.broker, order.hash ); if (!registered) { order.valid = order.valid && ctx.orderBook.orderSubmitted(order.hash); } } else { order.valid = order.valid && MultihashUtil.verifySignature( order.broker, order.hash, order.sig ); } } function checkDualAuthSignature( Data.Order order, bytes32 miningHash ) internal pure { if (order.dualAuthSig.length != 0) { order.valid = order.valid && MultihashUtil.verifySignature( order.dualAuthAddr, miningHash, order.dualAuthSig ); } } function validateAllOrNone( Data.Order order ) internal pure { // Check if this order needs to be completely filled if(order.allOrNone) { order.valid = order.valid && (order.filledAmountS == order.amountS); } } function getSpendableS( Data.Order order, Data.Context ctx ) internal returns (uint) { return getSpendable( ctx.delegate, order.tokenS, order.owner, order.broker, order.brokerInterceptor, order.tokenSpendableS, order.brokerSpendableS ); } function getSpendableFee( Data.Order order, Data.Context ctx ) internal returns (uint) { return getSpendable( ctx.delegate, order.feeToken, order.owner, order.broker, order.brokerInterceptor, order.tokenSpendableFee, order.brokerSpendableFee ); } function reserveAmountS( Data.Order order, uint amount ) internal pure { order.tokenSpendableS.reserved += amount; if (order.brokerInterceptor != 0x0) { order.brokerSpendableS.reserved += amount; } } function reserveAmountFee( Data.Order order, uint amount ) internal pure { order.tokenSpendableFee.reserved += amount; if (order.brokerInterceptor != 0x0) { order.brokerSpendableFee.reserved += amount; } } function resetReservations( Data.Order order ) internal pure { order.tokenSpendableS.reserved = 0; order.tokenSpendableFee.reserved = 0; if (order.brokerInterceptor != 0x0) { order.brokerSpendableS.reserved = 0; order.brokerSpendableFee.reserved = 0; } } /// @return Amount of ERC20 token that can be spent by this contract. function getERC20Spendable( ITradeDelegate delegate, address tokenAddress, address owner ) private view returns (uint spendable) { ERC20 token = ERC20(tokenAddress); spendable = token.allowance( owner, address(delegate) ); if (spendable == 0) { return; } uint balance = token.balanceOf(owner); spendable = (balance < spendable) ? balance : spendable; } /// @return Amount of ERC20 token that can be spent by the broker function getBrokerAllowance( address tokenAddress, address owner, address broker, address brokerInterceptor ) private returns (uint allowance) { allowance = brokerInterceptor.getAllowanceSafe( owner, broker, tokenAddress ); } function getSpendable( ITradeDelegate delegate, address tokenAddress, address owner, address broker, address brokerInterceptor, Data.Spendable tokenSpendable, Data.Spendable brokerSpendable ) private returns (uint spendable) { if (!tokenSpendable.initialized) { tokenSpendable.amount = getERC20Spendable( delegate, tokenAddress, owner ); tokenSpendable.initialized = true; } spendable = tokenSpendable.amount.sub(tokenSpendable.reserved); if (brokerInterceptor != 0x0) { if (!brokerSpendable.initialized) { brokerSpendable.amount = getBrokerAllowance( tokenAddress, owner, broker, brokerInterceptor ); brokerSpendable.initialized = true; } uint brokerSpendableAmount = brokerSpendable.amount.sub(brokerSpendable.reserved); spendable = (brokerSpendableAmount < spendable) ? brokerSpendableAmount : spendable; } } }
7,342
50
// Unpauses the system at which point the system should be fully operational. /
function step6() external onlyOwner step(6) { // Unpause the L1CrossDomainMessenger. L1CrossDomainMessenger(config.proxyAddressConfig.l1CrossDomainMessengerProxy).unpause(); }
function step6() external onlyOwner step(6) { // Unpause the L1CrossDomainMessenger. L1CrossDomainMessenger(config.proxyAddressConfig.l1CrossDomainMessengerProxy).unpause(); }
14,978
66
// Return the delegation from a delegator to an indexer. _indexer Address of the indexer where funds have been delegated _delegator Address of the delegatorreturn Delegation data /
function getDelegation(address _indexer, address _delegator) external view override returns (Delegation memory)
function getDelegation(address _indexer, address _delegator) external view override returns (Delegation memory)
12,503
145
// Overridable way to get the `KyberNetworkProxy` address./ return kyberAddress The `IKyberNetworkProxy` address.
function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; }
function _getKyberNetworkProxyAddress() internal view returns (address kyberAddress) { return KYBER_NETWORK_PROXY_ADDRESS; }
34,351
0
// the referenced uniswap pair contract
IUniswapV2Pair public override pair; bool private isPrice0;
IUniswapV2Pair public override pair; bool private isPrice0;
64,484
12
// Removes an address value from a set. O(1).Returns false if the value was not present in the set. /
function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool)
function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool)
15,597
95
// Claim tokens that were accidentally sent to this contract._token The address of the token contract that you want to recover. /
function claimTokens(address _token) public onlyOwner { require(_token != address(0)); ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); }
function claimTokens(address _token) public onlyOwner { require(_token != address(0)); ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, owner, balance); }
16,428
132
// calculate the net profit/loss for an address in this fund
function calculateAddressProfit(address _address) public view returns (int256) { uint256 currentAddressValue = calculateAddressValue(_address); return int256(currentAddressValue) - addressesNetDeposit[_address]; }
function calculateAddressProfit(address _address) public view returns (int256) { uint256 currentAddressValue = calculateAddressValue(_address); return int256(currentAddressValue) - addressesNetDeposit[_address]; }
39,317
26
// Approved token transfer amounts on behalf of others /
mapping (address => mapping (address => uint)) internal transferAllowances;
mapping (address => mapping (address => uint)) internal transferAllowances;
20,888
4
// be careful with external contract function calls made by functions you modify with this keep in mind possible re-entrancy
modifier onlySelfMulticall { // Requires to be in a multicall // NSMC -> Not self multi calling CallState callState = _callState; if (callState == CallState.IDLE) revert('NSMC'); // Prevents cross-function re-entrancy // CFL -> Cross Function Lock if (callState != CallState.IS_MULTICALLING) revert('CFL'); _callState = CallState.IS_CALLING_PROTECTED_FUNCTION; _; _callState = CallState.IS_MULTICALLING; }
modifier onlySelfMulticall { // Requires to be in a multicall // NSMC -> Not self multi calling CallState callState = _callState; if (callState == CallState.IDLE) revert('NSMC'); // Prevents cross-function re-entrancy // CFL -> Cross Function Lock if (callState != CallState.IS_MULTICALLING) revert('CFL'); _callState = CallState.IS_CALLING_PROTECTED_FUNCTION; _; _callState = CallState.IS_MULTICALLING; }
31,436
16
// Computes the address of a clone deployed using {Clones-cloneDeterministic}. /
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) {
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) {
886
6
// Gets app storage struct from defined storage slot. /
function _appStorage() internal pure returns(AppStorage storage app) { bytes32 storagePosition = bytes32(uint256(keccak256("app.storage")) - 1); assembly { app.slot := storagePosition }
function _appStorage() internal pure returns(AppStorage storage app) { bytes32 storagePosition = bytes32(uint256(keccak256("app.storage")) - 1); assembly { app.slot := storagePosition }
5,301
31
// See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
function transfer(address recipient, uint256 amount) public returns (bool){ _transfer(msg.sender, recipient, amount); return true; }
function transfer(address recipient, uint256 amount) public returns (bool){ _transfer(msg.sender, recipient, amount); return true; }
36,503
3
// Game variables
address public player1; address public player2; bool public player1Turn; bool public gameRunning; uint public bet; uint public maxBet = 5 ether; uint public minBet = 0.01 ether;
address public player1; address public player2; bool public player1Turn; bool public gameRunning; uint public bet; uint public maxBet = 5 ether; uint public minBet = 0.01 ether;
6,076
12
// See {IMigratablePool}.{prepareMigration} /
function prepareMigration(address newPool, uint256 graceDays) public override _controller_ { require(newPool != address(0), "MigratablePool: prepareMigration to 0 address"); require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days"); _migrationTimestamp = block.timestamp + graceDays * 1 days; _migrationDestination = newPool; emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination); }
function prepareMigration(address newPool, uint256 graceDays) public override _controller_ { require(newPool != address(0), "MigratablePool: prepareMigration to 0 address"); require(graceDays >= 3 && graceDays <= 365, "MigratablePool: graceDays must be 3-365 days"); _migrationTimestamp = block.timestamp + graceDays * 1 days; _migrationDestination = newPool; emit PrepareMigration(_migrationTimestamp, address(this), _migrationDestination); }
8,155
1,105
// TestLib_Buffer /
contract TestLib_Buffer { using Lib_Buffer for Lib_Buffer.Buffer; Lib_Buffer.Buffer internal buf; function push( bytes32 _value,
contract TestLib_Buffer { using Lib_Buffer for Lib_Buffer.Buffer; Lib_Buffer.Buffer internal buf; function push( bytes32 _value,
65,854
140
// Check if reward already computed
require((stakeInfo.approvedAmount > 0 || stakeInfo.pendingForApprovalAmount > 0 ) && stakeInfo.rewardComputeIndex != stakeMapIndex, "Invalid reward request");
require((stakeInfo.approvedAmount > 0 || stakeInfo.pendingForApprovalAmount > 0 ) && stakeInfo.rewardComputeIndex != stakeMapIndex, "Invalid reward request");
51,504
10
// Modifier that requires not funded airline/
modifier requireFundedAirline(address airline) { require(flightSuretyData.isFunded(airline), "Airline not funded"); _; }
modifier requireFundedAirline(address airline) { require(flightSuretyData.isFunded(airline), "Airline not funded"); _; }
48,168
0
// Interface for a contract which can receive Wormhole messages. /
interface IWormholeReceiver { /** * @notice When a `send` is performed with this contract as the target, this function will be * invoked by the WormholeRelayer contract * * NOTE: This function should be restricted such that only the Wormhole Relayer contract can call it. * * We also recommend that this function: * - Stores all received `deliveryHash`s in a mapping `(bytes32 => bool)`, and * on every call, checks that deliveryHash has not already been stored in the * map (This is to prevent other users maliciously trying to relay the same message) * - Checks that `sourceChain` and `sourceAddress` are indeed who * you expect to have requested the calling of `send` or `forward` on the source chain * * The invocation of this function corresponding to the `send` request will have msg.value equal * to the receiverValue specified in the send request. * * If the invocation of this function reverts or exceeds the gas limit * specified by the send requester, this delivery will result in a `ReceiverFailure`. * * @param payload - an arbitrary message which was included in the delivery by the * requester. * @param additionalVaas - Additional VAAs which were requested to be included in this delivery. * They are guaranteed to all be included and in the same order as was specified in the * delivery request. * @param sourceAddress - the (wormhole format) address on the sending chain which requested * this delivery. * @param sourceChain - the wormhole chain ID where this delivery was requested. * @param deliveryHash - the VAA hash of the deliveryVAA. * * NOTE: These signedVaas are NOT verified by the Wormhole core contract prior to being provided * to this call. Always make sure `parseAndVerify()` is called on the Wormhole core contract * before trusting the content of a raw VAA, otherwise the VAA may be invalid or malicious. */ function receiveWormholeMessages( bytes memory payload, bytes[] memory additionalVaas, bytes32 sourceAddress, uint16 sourceChain, bytes32 deliveryHash ) external payable; }
interface IWormholeReceiver { /** * @notice When a `send` is performed with this contract as the target, this function will be * invoked by the WormholeRelayer contract * * NOTE: This function should be restricted such that only the Wormhole Relayer contract can call it. * * We also recommend that this function: * - Stores all received `deliveryHash`s in a mapping `(bytes32 => bool)`, and * on every call, checks that deliveryHash has not already been stored in the * map (This is to prevent other users maliciously trying to relay the same message) * - Checks that `sourceChain` and `sourceAddress` are indeed who * you expect to have requested the calling of `send` or `forward` on the source chain * * The invocation of this function corresponding to the `send` request will have msg.value equal * to the receiverValue specified in the send request. * * If the invocation of this function reverts or exceeds the gas limit * specified by the send requester, this delivery will result in a `ReceiverFailure`. * * @param payload - an arbitrary message which was included in the delivery by the * requester. * @param additionalVaas - Additional VAAs which were requested to be included in this delivery. * They are guaranteed to all be included and in the same order as was specified in the * delivery request. * @param sourceAddress - the (wormhole format) address on the sending chain which requested * this delivery. * @param sourceChain - the wormhole chain ID where this delivery was requested. * @param deliveryHash - the VAA hash of the deliveryVAA. * * NOTE: These signedVaas are NOT verified by the Wormhole core contract prior to being provided * to this call. Always make sure `parseAndVerify()` is called on the Wormhole core contract * before trusting the content of a raw VAA, otherwise the VAA may be invalid or malicious. */ function receiveWormholeMessages( bytes memory payload, bytes[] memory additionalVaas, bytes32 sourceAddress, uint16 sourceChain, bytes32 deliveryHash ) external payable; }
32,087
19
// Owner surrenders _minimumStake to the system
uint256 reimbursedAmount = _registry[name].stake.sub(_minimumStake);
uint256 reimbursedAmount = _registry[name].stake.sub(_minimumStake);
26,682
39
// Start a slow withdrawal request Collateral can be withdrawn once the liveness period has elapsed derivative Derivative from which collateral withdrawal is requested collateralAmount The amount of excess collateral to withdraw /
function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount)
function slowWithdrawRequest(IDerivative derivative, uint256 collateralAmount)
45,583
45
// Emitted when a Migration is executed. After this also `AllocatorDeactivated` should follow. /
event MigrationExecuted(address allocator);
event MigrationExecuted(address allocator);
63,673
167
// MINT /
modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= MAX_MINT_AMOUNT_PER_TX, "Invalid mint amount!"); require(currentIndex + _mintAmount <= MAX_SUPPLY, "Max supply exceeded!"); _; }
modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= MAX_MINT_AMOUNT_PER_TX, "Invalid mint amount!"); require(currentIndex + _mintAmount <= MAX_SUPPLY, "Max supply exceeded!"); _; }
36,458
80
// Partition Token Allowances // Check the value of tokens that an owner allowed to a spender. partition Name of the partition. owner address The address which owns the funds. spender address The address which will spend the funds.return A uint256 specifying the value of tokens still available for the spender. /
function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) { return _allowedByPartition[partition][owner][spender]; }
function allowanceByPartition(bytes32 partition, address owner, address spender) external view returns (uint256) { return _allowedByPartition[partition][owner][spender]; }
12,248
186
// Sale auction throws if inputs are invalid and clears transfer and sire approval after escrowing the cutie.
saleMarket.createAuction.value(msg.value)( _cutieId, _startPrice, _endPrice, _duration, msg.sender );
saleMarket.createAuction.value(msg.value)( _cutieId, _startPrice, _endPrice, _duration, msg.sender );
54,215
141
// only avialble in upgrade phase
require (flag == MINING_FLAG_UPGRADE_NEEDED, "Nest:Mine:!flag"); state._post2Only4Upgrade(token, ethNum, tokenAmountPerEth, ntokenAmountPerEth); address _ntoken = INestPool(state.C_NestPool).getNTokenFromToken(token);
require (flag == MINING_FLAG_UPGRADE_NEEDED, "Nest:Mine:!flag"); state._post2Only4Upgrade(token, ethNum, tokenAmountPerEth, ntokenAmountPerEth); address _ntoken = INestPool(state.C_NestPool).getNTokenFromToken(token);
26,640
447
// Mapping from token ID to auction start time
mapping (uint256 => uint256) public _tokenAuctionStart;
mapping (uint256 => uint256) public _tokenAuctionStart;
4,134
12
// If the utilization is above the roof, cap it.
if (util > roof) { util = roof; }
if (util > roof) { util = roof; }
35,380
78
// Ensure that the indexer can pull funds from delegate account.
require( IERC20(indexer.stakingToken()) .approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED" );
require( IERC20(indexer.stakingToken()) .approve(address(indexer), MAX_INT), "STAKING_APPROVAL_FAILED" );
35,730
43
// CG: Allow selection of to close submissionSelectionWindow after the first submission.
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionSelectionWindow)) { return GovernanceState.SubmissionsSelection; }
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionSelectionWindow)) { return GovernanceState.SubmissionsSelection; }
43,496
92
// Initializes the upgradeable proxy with an initial implementation specified by `_logic`. If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encodedfunction call, and allows initializating the storage of the proxy like a Solidity constructor. /
constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); }
constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); }
11,020
13
// 0age
contract ERC20Helper { function metadataSafe(IERC20Metadata token) external view returns (bool tokenExists, bool nameOK, string memory name, bool symbolOK, string memory symbol, bool decimalsOK, uint8 decimals) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (nameOK, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.name.selector)); if (nameOK && returnData.length >= 64) { name = abi.decode(returnData, (string)); } else { nameOK = false; } (symbolOK, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.symbol.selector)); if (symbolOK && returnData.length >= 64) { symbol = abi.decode(returnData, (string)); } else { symbolOK = false; } (decimalsOK, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.decimals.selector)); if (decimalsOK && returnData.length >= 32) { decimals = abi.decode(returnData, (uint8)); } else { decimalsOK = false; } } } function totalSupplySafe(IERC20TotalSupply token) external view returns (bool tokenExists, bool ok, uint256 totalSupply) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (ok, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.totalSupply.selector)); if (ok && returnData.length >= 32) { totalSupply = abi.decode(returnData, (uint256)); } else { ok = false; } } } function balanceOfSafe(IERC20BalanceOf token, address account) external view returns (bool tokenExists, bool ok, uint256 balance) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (ok, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.balanceOf.selector, account)); if (ok && returnData.length >= 32) { balance = abi.decode(returnData, (uint256)); } else { ok = false; } } } function allowanceSafe(IERC20Allowance token, address owner, address spender) external view returns (bool tokenExists, bool ok, uint256 allowance) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (ok, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.allowance.selector, owner, spender)); if (ok && returnData.length >= 32) { allowance = abi.decode(returnData, (uint256)); } else { ok = false; } } } function _hasCode(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } }
contract ERC20Helper { function metadataSafe(IERC20Metadata token) external view returns (bool tokenExists, bool nameOK, string memory name, bool symbolOK, string memory symbol, bool decimalsOK, uint8 decimals) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (nameOK, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.name.selector)); if (nameOK && returnData.length >= 64) { name = abi.decode(returnData, (string)); } else { nameOK = false; } (symbolOK, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.symbol.selector)); if (symbolOK && returnData.length >= 64) { symbol = abi.decode(returnData, (string)); } else { symbolOK = false; } (decimalsOK, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.decimals.selector)); if (decimalsOK && returnData.length >= 32) { decimals = abi.decode(returnData, (uint8)); } else { decimalsOK = false; } } } function totalSupplySafe(IERC20TotalSupply token) external view returns (bool tokenExists, bool ok, uint256 totalSupply) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (ok, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.totalSupply.selector)); if (ok && returnData.length >= 32) { totalSupply = abi.decode(returnData, (uint256)); } else { ok = false; } } } function balanceOfSafe(IERC20BalanceOf token, address account) external view returns (bool tokenExists, bool ok, uint256 balance) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (ok, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.balanceOf.selector, account)); if (ok && returnData.length >= 32) { balance = abi.decode(returnData, (uint256)); } else { ok = false; } } } function allowanceSafe(IERC20Allowance token, address owner, address spender) external view returns (bool tokenExists, bool ok, uint256 allowance) { tokenExists = _hasCode(address(token)); if (tokenExists) { bytes memory returnData; (ok, returnData) = address(token).staticcall{gas: gasleft() / 2}(abi.encodeWithSelector(token.allowance.selector, owner, spender)); if (ok && returnData.length >= 32) { allowance = abi.decode(returnData, (uint256)); } else { ok = false; } } } function _hasCode(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } }
70,057
195
// View function to see pending FOXs on frontend.
function pendingFox(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFoxPerShare = pool.accFoxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foxReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFoxPerShare = accFoxPerShare.add(foxReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFoxPerShare).div(1e12).sub(user.rewardDebt); }
function pendingFox(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFoxPerShare = pool.accFoxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foxReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFoxPerShare = accFoxPerShare.add(foxReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFoxPerShare).div(1e12).sub(user.rewardDebt); }
10,958
12
// This function provides the version number of the contract. /
function version() public pure override returns (uint256) { return 0; }
function version() public pure override returns (uint256) { return 0; }
24,935
40
// Adapt the 6 decimals notation to 18 decimals for the token
uint256 tokensToClaim = unclaimedBalance[msg.sender] * 10 ** 12; unclaimedBalance[msg.sender] = 0; token.transfer(msg.sender, tokensToClaim); emit TokensClaimed(msg.sender, tokensToClaim);
uint256 tokensToClaim = unclaimedBalance[msg.sender] * 10 ** 12; unclaimedBalance[msg.sender] = 0; token.transfer(msg.sender, tokensToClaim); emit TokensClaimed(msg.sender, tokensToClaim);
10,374
158
// Correctness checks on this call
require(oldMin <= newMin);
require(oldMin <= newMin);
27,552
72
// Returns the status for a given account that can recieve the vault reserves after pull liquidity/by default vault address will be whitelist as a recipient in order to resist IL/Only applicable for active vaults
function isWhitelist(address recipient) external view returns (bool);
function isWhitelist(address recipient) external view returns (bool);
58,123
13
// Get the credits per token for an account. Returns a fixed amount if the account is non-rebasing. _account Address of the account. /
function _creditsPerToken(address _account) internal view returns (uint256)
function _creditsPerToken(address _account) internal view returns (uint256)
32,305
23
// Records the round data. /
function buyRoundDataRecord(uint256 _rId, uint256 _amount) private
function buyRoundDataRecord(uint256 _rId, uint256 _amount) private
59,658
1
// [tokenid] = address
mapping (uint256 => address) private stakingAddress;
mapping (uint256 => address) private stakingAddress;
19,002
2
// sets admin role for a role/can only be called adminRole of _role/_role roles whose admin needs to be updated/_adminRole new admin role
function setRoleAdmin(bytes32 _role, bytes32 _adminRole) external override onlyRole(getRoleAdmin(_role)) { _setRoleAdmin(_role, _adminRole); }
function setRoleAdmin(bytes32 _role, bytes32 _adminRole) external override onlyRole(getRoleAdmin(_role)) { _setRoleAdmin(_role, _adminRole); }
43,590
1
// mint VOLT to the target address and deplete the buffer/ pausable and depletes the msg.sender's buffer/to the recipient address of the minted VOLT/amount the amount of VOLT to mint
function mintVolt(address to, uint256 amount) external virtual override whenNotPaused { _depleteIndividualBuffer(msg.sender, amount); _mintVolt(to, amount); }
function mintVolt(address to, uint256 amount) external virtual override whenNotPaused { _depleteIndividualBuffer(msg.sender, amount); _mintVolt(to, amount); }
48,372
0
// IAssetManager interface Interface for asset manager, that manages assets and refills pool wallet when needed Ensuro /
interface IAssetManager { /** * @dev This is called from PolicyPool when doesn't have enought money for payment. * After the call, there should be enought money in PolicyPool.currency().balanceOf(_policyPool) to * do the payment * @param paymentAmount The amount of the payment */ function refillWallet(uint256 paymentAmount) external; /** * @dev Deinvest all the assets and return the cash back to the PolicyPool. * Called from PolicyPool when new asset manager is assigned */ function deinvestAll() external; }
interface IAssetManager { /** * @dev This is called from PolicyPool when doesn't have enought money for payment. * After the call, there should be enought money in PolicyPool.currency().balanceOf(_policyPool) to * do the payment * @param paymentAmount The amount of the payment */ function refillWallet(uint256 paymentAmount) external; /** * @dev Deinvest all the assets and return the cash back to the PolicyPool. * Called from PolicyPool when new asset manager is assigned */ function deinvestAll() external; }
38,751
169
// We still alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public
function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public
48,576
178
// Unlock stakes for all workers
require(workerpool.claimFailedConsensus(_woid)); workorder.claim(); // revert on error /* uint256 value = marketplace.getMarketOrderValue(workorder.m_marketorderIdx()); // revert if not exist */ /* address workerpoolOwner = marketplace.getMarketOrderWorkerpoolOwner(workorder.m_marketorderIdx()); // revert if not exist */ uint256 value; address workerpoolOwner; (,,,value,,,,workerpoolOwner) = marketplace.getMarketOrder(workorder.m_marketorderIdx()); // Single call cost less gas uint256 workerpoolStake = value.percentage(marketplace.ASK_STAKE_RATIO());
require(workerpool.claimFailedConsensus(_woid)); workorder.claim(); // revert on error /* uint256 value = marketplace.getMarketOrderValue(workorder.m_marketorderIdx()); // revert if not exist */ /* address workerpoolOwner = marketplace.getMarketOrderWorkerpoolOwner(workorder.m_marketorderIdx()); // revert if not exist */ uint256 value; address workerpoolOwner; (,,,value,,,,workerpoolOwner) = marketplace.getMarketOrder(workorder.m_marketorderIdx()); // Single call cost less gas uint256 workerpoolStake = value.percentage(marketplace.ASK_STAKE_RATIO());
70,975
73
// Operators can call {transferFrom} or {safeTransferFrom}for any token owned by the caller. Requirements: - The `operator` cannot be the caller. Emits an {ApprovalForAll} event. /
function setApprovalForAll(address operator, bool approved) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); }
function setApprovalForAll(address operator, bool approved) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); }
2,355
173
// Remove a market from strikeMarkets, preventing it from earning STRK in the flywheel sToken The address of the market to drop /
function _dropStrikeMarket(address sToken) public { require(msg.sender == admin, "only admin can drop strike market"); Market storage market = markets[sToken]; require(market.isStriked == true, "market is not a strike market"); market.isStriked = false; emit MarketStriked(SToken(sToken), false); // refreshStrikeSpeedsInternal(); }
function _dropStrikeMarket(address sToken) public { require(msg.sender == admin, "only admin can drop strike market"); Market storage market = markets[sToken]; require(market.isStriked == true, "market is not a strike market"); market.isStriked = false; emit MarketStriked(SToken(sToken), false); // refreshStrikeSpeedsInternal(); }
48,530
156
// Upon first becoming a token holder. Account is initiated and last_cull_processed is set to the current _cullIncrement
address private _UniContractAddr;
address private _UniContractAddr;
34,590
29
// Sets start staking date/ _newDate Start Staking Date
function setStakingStartDate(uint256 _newDate) external onlyOwner { require(_stakingStartDate == 0, "Cant be set again"); _stakingStartDate = _newDate; }
function setStakingStartDate(uint256 _newDate) external onlyOwner { require(_stakingStartDate == 0, "Cant be set again"); _stakingStartDate = _newDate; }
14,351
173
// Remove an account from the user role. Restricted to admins.
function removeAccount(bytes32 role, address account) public virtual onlyAdmin
function removeAccount(bytes32 role, address account) public virtual onlyAdmin
9,839
24
// recover the signer from a hash and signature/hash_ The hash of the message/signature_ The signature of the hash
function recoverSigner(bytes32 hash_, bytes memory signature_) public pure returns (address) { bytes32 messageDigest = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash_)); return ECDSAUpgradeable.recover(messageDigest, signature_); }
function recoverSigner(bytes32 hash_, bytes memory signature_) public pure returns (address) { bytes32 messageDigest = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', hash_)); return ECDSAUpgradeable.recover(messageDigest, signature_); }
21,039
45
// user need to pay a fee when conflict ended. this ensures a malicious, rich user can not just generate game sessions and then wait for us to end the game session and then confirm the session status, so we would have to pay a high gas fee without profit.
newBalance = newBalance.sub(CONFLICT_END_FINE);
newBalance = newBalance.sub(CONFLICT_END_FINE);
33,992
15
// Time when auction started NOTE: 0 if this auction has been concluded
uint64 startedAt;
uint64 startedAt;
18,692