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
49
// Slippage protection
require(nSignal >= _nSignalOutMin, "GNS: Slippage protection");
require(nSignal >= _nSignalOutMin, "GNS: Slippage protection");
50,131
3,696
// 1850
entry "convolutionally" : ENG_ADVERB
entry "convolutionally" : ENG_ADVERB
22,686
35
// Retrieves the poll fee.return pollFee The poll fee. /
function getPollFee() external view override returns (uint256) { return pollFee; }
function getPollFee() external view override returns (uint256) { return pollFee; }
9,068
6
// Whether batch transfers are enabled for this asset
mapping(address => bool) public batchTransferEnabled;
mapping(address => bool) public batchTransferEnabled;
7,844
191
// Internal Functions: Contract Interaction//Creates a new contract and associates it with some contract address. _contractAddress Address to associate the created contract with. _bytecode Bytecode to be used to create the contract.return Final OVM contract address.return Revertdata, if and only if the creation threw an exception. /
function _createContract( address _contractAddress, bytes memory _bytecode, MessageType _messageType ) internal returns ( address, bytes memory )
function _createContract( address _contractAddress, bytes memory _bytecode, MessageType _messageType ) internal returns ( address, bytes memory )
27,995
2
// WeiBountyBounty is when you put money, then someone outside the DAO worksThat is why bounty is always prepaid /
contract WeiBounty is WeiGenericTask { bytes32 constant public START_BOUNTY = keccak256("startBounty"); constructor(IDaoBase _daoBase, string _caption, string _desc, uint _neededWei, uint64 _deadlineTime, uint64 _timeToCancell) public WeiGenericTask(_daoBase, _caption, _desc, false, false, _neededWei, _deadlineTime, _timeToCancell) { } // callable by anyone // anyone should call this function when for starting the task /** * @notice This function should be called only by account with START_BOUNTY permissions * @dev starts bounty */ function startTask() public isCanDo(START_BOUNTY) { require(getCurrentState() == State.PrePaid); startTime = block.timestamp; employee = msg.sender; state = State.InProgress; emit WeiGenericTaskStateChanged(state); } }
contract WeiBounty is WeiGenericTask { bytes32 constant public START_BOUNTY = keccak256("startBounty"); constructor(IDaoBase _daoBase, string _caption, string _desc, uint _neededWei, uint64 _deadlineTime, uint64 _timeToCancell) public WeiGenericTask(_daoBase, _caption, _desc, false, false, _neededWei, _deadlineTime, _timeToCancell) { } // callable by anyone // anyone should call this function when for starting the task /** * @notice This function should be called only by account with START_BOUNTY permissions * @dev starts bounty */ function startTask() public isCanDo(START_BOUNTY) { require(getCurrentState() == State.PrePaid); startTime = block.timestamp; employee = msg.sender; state = State.InProgress; emit WeiGenericTaskStateChanged(state); } }
14,669
68
// Returns whether a bit is set or off at a given position in our map
(uint256 quotient, uint256 remainder) = getDivided(position, 256); require(position <= 255 + (quotient * 256)); return (map[quotient] >> (255 - remainder)) & 1;
(uint256 quotient, uint256 remainder) = getDivided(position, 256); require(position <= 255 + (quotient * 256)); return (map[quotient] >> (255 - remainder)) & 1;
53,444
5
// Destroy currency from the account of the owner.
function burn(uint256 amount) public
function burn(uint256 amount) public
48,684
205
// Converts a bytes32 UUID to a UUID string with dashes e9071858e63b4f2792d70603235c0b8c => e9071858-e63b-4f27-92d7-0603235c0b8c
function bytes32ToUUIDString(bytes32 b) internal pure returns (string memory) { bytes memory bytesArray = new bytes(36); uint j; for (uint256 i; i < 32; i++) { bytesArray[j] = b[i];
function bytes32ToUUIDString(bytes32 b) internal pure returns (string memory) { bytes memory bytesArray = new bytes(36); uint j; for (uint256 i; i < 32; i++) { bytesArray[j] = b[i];
66,638
550
// if _collateral isn't enabled as collateral by _user, it cannot be liquidated
if (!vars.isCollateralEnabled) { return ( uint256(LiquidationErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), "The collateral chosen cannot be liquidated" ); }
if (!vars.isCollateralEnabled) { return ( uint256(LiquidationErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), "The collateral chosen cannot be liquidated" ); }
51,666
10
// сколько нужно времени между доениями
uint time_to_milk;
uint time_to_milk;
58,380
117
// Relinquishment is a voluntary giving up of the Orb. It's a combination of withdrawing all funds not/owed to the beneficiary since last settlement and transferring the Orb to the contract. Keepers giving/up the Orb may start an auction for it for their own benefit. Once auction is finalized, most of the/proceeds (minus the royalty) go to the relinquishing Keeper. Alternatives to relinquisment are setting/the price to zero or withdrawing all funds. Orb creator cannot start the keeper auction via this/function, and must call `relinquish(false)` and `startAuction()` separately to run the creator/auction./Calls `_withdraw()`, which does value transfer from the contract. Emits
function relinquish(bool withAuction) external virtual onlyKeeper onlyKeeperSolvent { _settle(); price = 0; emit Relinquishment(msg.sender); if (withAuction && auctionKeeperMinimumDuration > 0) { if (owner() == msg.sender) { revert NotPermitted(); } auctionBeneficiary = msg.sender; auctionEndTime = block.timestamp + auctionKeeperMinimumDuration; emit AuctionStart(block.timestamp, auctionEndTime, auctionBeneficiary); } _transferOrb(msg.sender, address(this)); _withdraw(msg.sender, fundsOf[msg.sender]); }
function relinquish(bool withAuction) external virtual onlyKeeper onlyKeeperSolvent { _settle(); price = 0; emit Relinquishment(msg.sender); if (withAuction && auctionKeeperMinimumDuration > 0) { if (owner() == msg.sender) { revert NotPermitted(); } auctionBeneficiary = msg.sender; auctionEndTime = block.timestamp + auctionKeeperMinimumDuration; emit AuctionStart(block.timestamp, auctionEndTime, auctionBeneficiary); } _transferOrb(msg.sender, address(this)); _withdraw(msg.sender, fundsOf[msg.sender]); }
18,824
49
// receive approval /
function receiveApproval(address _from, uint256 _value, address _to, bytes _extraData) public;
function receiveApproval(address _from, uint256 _value, address _to, bytes _extraData) public;
40,884
142
// Event for tracking pending validators limit. When it's exceeded, the deposits will be set for the activation.pendingValidatorsLimit - pending validators percent limit.sender - address of the transaction sender./
event PendingValidatorsLimitUpdated(uint256 pendingValidatorsLimit, address sender);
event PendingValidatorsLimitUpdated(uint256 pendingValidatorsLimit, address sender);
67,479
252
// we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1)
if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1)
2,804
43
// check white ball 1
for(uint8 i=0;i<4; i++){ if(_result[i] == tickets[_ticketId].ball1){ _prize ++; break; }
for(uint8 i=0;i<4; i++){ if(_result[i] == tickets[_ticketId].ball1){ _prize ++; break; }
13,745
200
// Safe bbr transfer function, just in case if rounding error causes pool to not have enough BBRs.
function safeBBRTransfer(address _to, uint256 _amount) internal { uint256 bbrBal = bbr.balanceOf(address(this)); if (_amount > bbrBal) { bbr.transfer(_to, bbrBal); } else { bbr.transfer(_to, _amount); } }
function safeBBRTransfer(address _to, uint256 _amount) internal { uint256 bbrBal = bbr.balanceOf(address(this)); if (_amount > bbrBal) { bbr.transfer(_to, bbrBal); } else { bbr.transfer(_to, _amount); } }
28,508
7
// Returns the total supply of the variable debt token. Represents the total debt accrued by the usersreturn The total supply /
function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); }
function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); }
13,100
4
// Minor adaptation on `factory` and `WETH` to help conform to compiler bump.
interface IUniswapV2Router01x { function factory() external view returns (address); function WETH() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
interface IUniswapV2Router01x { function factory() external view returns (address); function WETH() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
39,292
7
// An event emitted when the voting delay is set
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
34,927
575
// Called by user to pay joining membership fee/
function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } }
function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } }
28,748
90
// Buying
if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Leave some for the rest of us" ); require(amount + balanceOf(to) <= maxWallet, "Easy Whaley" ); }
if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Leave some for the rest of us" ); require(amount + balanceOf(to) <= maxWallet, "Easy Whaley" ); }
13,941
69
// teleportable token {_tokenAddr} is wrapped token
require(IWrappedToken(_tokenAddr).burnFrom(msgSender, _amount), "burn failed"); emit TeleportStarted( ++teleportIdGenerator, msgSender, originalToken.chainId, originalToken.addr, _tokenAddr, _amount,
require(IWrappedToken(_tokenAddr).burnFrom(msgSender, _amount), "burn failed"); emit TeleportStarted( ++teleportIdGenerator, msgSender, originalToken.chainId, originalToken.addr, _tokenAddr, _amount,
42,487
2
// Initialize the TugOfWar contract
IERC20Upgradeable(assetToken_).approve(newContract, rewardAmount_); uint256 gameEndTime = beginTime + (_counter * 24 hours) - 5 minutes; // 23h 55m ITugOfWar(newContract).startGame(assetToken_, rewardAmount_, gameEndTime); currentGameAddress = newContract; emit ContractCreated(newContract);
IERC20Upgradeable(assetToken_).approve(newContract, rewardAmount_); uint256 gameEndTime = beginTime + (_counter * 24 hours) - 5 minutes; // 23h 55m ITugOfWar(newContract).startGame(assetToken_, rewardAmount_, gameEndTime); currentGameAddress = newContract; emit ContractCreated(newContract);
14,932
0
// get maximum value in an array array array to searchreturn maximum value /
function max ( uint[] storage array ) internal view returns (uint) { uint maxValue = 0; for (uint i; i < array.length; i++) { if (array[i] > maxValue) { maxValue = array[i]; }
function max ( uint[] storage array ) internal view returns (uint) { uint maxValue = 0; for (uint i; i < array.length; i++) { if (array[i] > maxValue) { maxValue = array[i]; }
34,910
78
// Returns the minimum value in an array.data is the array to calculate min from return min amount and its index within the array/
function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } }
function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for (uint256 i = data.length - 2; i > 0; i--) { if (data[i] < min) { min = data[i]; minIndex = i; } } }
41,685
1,518
// compute the round end time as a function of the round Id. data input data object. roundId uniquely identifies the current round.return timestamp unix time of when the current round will end. /
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); }
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); }
17,866
37
// AdminUpgradeabilityProxy This contract combines an upgradeability proxy with an authorizationmechanism for administrative tasks.All external functions in this contract must be guarded by the`ifAdmin` modifier. See ethereum/solidity3864 for a Solidityfeature proposal that would enable this to be done automatically. /
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override virtual { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
2,084
307
// After Loopring performs all of the transfers necessary to complete all the submittedrings it will call this function for every order's brokerInterceptor (if set) passingalong the final fill counts for tokenB, tokenS and feeToken. This allows actions to beperformed on a per-order basis after all tokenS/feeToken funds have left the order owner'spossession and the tokenB funds have been transferred to the order owner's intended recipient /
function onOrderFillReport(BrokerData.BrokerInterceptorReport calldata fillReport) external;
function onOrderFillReport(BrokerData.BrokerInterceptorReport calldata fillReport) external;
3,038
133
// Enforce the maximum stake time // Ensure newStakedSuns is enough for at least one stake share ///
uint256 newLockedDay = g._currentDay.add(1);
uint256 newLockedDay = g._currentDay.add(1);
2,837
2
// CORI Marketplace filterer registry. Set to address(0) when not used to avoid extra inter-contract calls. /
address public operatorFiltererRegistry; function __MarketplaceFilterer__init__(bool useFilterer) internal onlyInitializing {
address public operatorFiltererRegistry; function __MarketplaceFilterer__init__(bool useFilterer) internal onlyInitializing {
40,523
146
// calculate the position's new interest rate state by calculating the new rate accumulator,and the updated accrued rebate by deducting the current rebate claim (if delta normal debt is negative)
{ uint64 rateAccumulator = _calculateRateAccumulator(globalIRS, totalNormalDebtBefore); positionIRS.accruedRebate = _calculateAccruedRebate(positionIRS, rateAccumulator, normalDebtBefore); positionIRS.snapshotRateAccumulator = rateAccumulator; }
{ uint64 rateAccumulator = _calculateRateAccumulator(globalIRS, totalNormalDebtBefore); positionIRS.accruedRebate = _calculateAccruedRebate(positionIRS, rateAccumulator, normalDebtBefore); positionIRS.snapshotRateAccumulator = rateAccumulator; }
26,652
123
// Views
function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256);
function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256);
82,686
80
// this contract version
uint public version;
uint public version;
49,854
114
// Override this function.This version is to keep track of BaseRelayRecipient you are usingin your contract. /
function versionRecipient() external pure override returns (string memory) { return "1"; }
function versionRecipient() external pure override returns (string memory) { return "1"; }
27,680
55
// Storage /
uint constant MAX_SUPPLY = 10_000; uint constant MAX_MINT_PER_CALL = 3; uint constant MAX_MINT_PER_ADDRESS = 3; uint constant MINT_FEE_PRIVATE = 0.2 ether; uint constant MINT_FEE_PUBLIC = 0.25 ether; uint constant PERCENTAGE_DENOMINATOR = 10_000;
uint constant MAX_SUPPLY = 10_000; uint constant MAX_MINT_PER_CALL = 3; uint constant MAX_MINT_PER_ADDRESS = 3; uint constant MINT_FEE_PRIVATE = 0.2 ether; uint constant MINT_FEE_PUBLIC = 0.25 ether; uint constant PERCENTAGE_DENOMINATOR = 10_000;
52,197
25
// Update the hash for a verified address known to the contract. Upon successful update of a verified address the contract must emit `VerifiedAddressUpdated(addr, oldHash, hash, msg.sender)`. If the hash is the same as the value already stored then no `VerifiedAddressUpdated` event is to be emitted. It MUST throw if the hash is zero, or if the address is unverified.addr The verified address of the person represented by the supplied hash.hash A new cryptographic hash of the address holder's updated verified information. /
function updateVerified(address addr, bytes32 hash) public onlyOwner isVerifiedAddress(addr)
function updateVerified(address addr, bytes32 hash) public onlyOwner isVerifiedAddress(addr)
11,059
38
// function {isUnlimited} Return if an address is unlimited (is not subject to per txn and per wallet limits)queryAddress_ The address being queriedreturn bool The address is / isn't unlimited /
function isUnlimited(address queryAddress_) public view returns (bool) { return (_unlimited.contains(queryAddress_)); }
function isUnlimited(address queryAddress_) public view returns (bool) { return (_unlimited.contains(queryAddress_)); }
29,510
20
// Make sure the sender is either the timelock or the operator
_requireIsTimelockOrOperator(); uint128 _unclaimedFees = redemptionQueueAccounting.unclaimedFees;
_requireIsTimelockOrOperator(); uint128 _unclaimedFees = redemptionQueueAccounting.unclaimedFees;
33,882
70
// 锁定期到期
while(tmp_date != 0 && tmp_date <= now) {
while(tmp_date != 0 && tmp_date <= now) {
31,029
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); }
5,091
9
// Return url for contract metadatareturn contract URI /
function contractURI() public pure returns (string memory) { return "https://arcadenfts.com/c_metadata.json"; }
function contractURI() public pure returns (string memory) { return "https://arcadenfts.com/c_metadata.json"; }
50,829
13
// I know. It's NOT random but if you have the time, energy, resources, and you care enough to guess the number then you REALLY need to get a life.
function getRandomAmount(address sender) private view returns (uint256) { uint256 random = uint256(keccak256(abi.encodePacked( block.timestamp, block.difficulty, sender, blockhash(block.number - 1) ))) % 901; // Number from 100 to 1000 return random + 100; }
function getRandomAmount(address sender) private view returns (uint256) { uint256 random = uint256(keccak256(abi.encodePacked( block.timestamp, block.difficulty, sender, blockhash(block.number - 1) ))) % 901; // Number from 100 to 1000 return random + 100; }
16,985
30
// set token price in between $1 to $1000, pass 111 for $1.11, 100000 for $1000
function setTokenPrice(uint _tokenPrice) external onlyOwner returns (bool) { require(_tokenPrice >= 100 && _tokenPrice <= 100000); tokenPrice=_tokenPrice; TokenPriceUpdated(_tokenPrice); return true; }
function setTokenPrice(uint _tokenPrice) external onlyOwner returns (bool) { require(_tokenPrice >= 100 && _tokenPrice <= 100000); tokenPrice=_tokenPrice; TokenPriceUpdated(_tokenPrice); return true; }
6,601
273
// Register new user liquidity _user the user to register the liquidity of /
function registerUserLiquidity(address _user) external;
function registerUserLiquidity(address _user) external;
28,011
182
// Calculate the latest sumIpc./collToken The cToken.
function _calcLatestSumIpc(address collToken) internal returns(uint) { uint balance = ICERC20(collToken).balanceOf(address(this)); uint mintBalance = totalMintAmt[collToken]; uint interest = mintBalance > balance ? mintBalance.sub(balance) : 0; uint currIpc = (mintBalance == 0) ? 0 : (interest.mul(MULTIPLIER)).div(mintBalance); if (currIpc > 0){ sumIpcMap[collToken] = sumIpcMap[collToken].add(currIpc); } return sumIpcMap[collToken]; }
function _calcLatestSumIpc(address collToken) internal returns(uint) { uint balance = ICERC20(collToken).balanceOf(address(this)); uint mintBalance = totalMintAmt[collToken]; uint interest = mintBalance > balance ? mintBalance.sub(balance) : 0; uint currIpc = (mintBalance == 0) ? 0 : (interest.mul(MULTIPLIER)).div(mintBalance); if (currIpc > 0){ sumIpcMap[collToken] = sumIpcMap[collToken].add(currIpc); } return sumIpcMap[collToken]; }
61,894
947
// These internal functions are supposed to act identically to modifiers, but re-used modifiers unnecessarily increase contract bytecode size. source: https:blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); }
function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); }
10,240
37
// Off-chain contribution registered id bytes32 A unique contribution id contributor address The recipient of the tokens amount uint256 The amount of tokens /
event ContributionRegistered(bytes32 indexed id, address indexed contributor, uint256 amount);
event ContributionRegistered(bytes32 indexed id, address indexed contributor, uint256 amount);
37,729
9
// Memory address of the buffer data
let bufptr := mload(buf)
let bufptr := mload(buf)
5,559
31
// Emits a {Transfer} event with `to` set to the zero address. Requirements: - `account` cannot be the zero address. - `account` must have at least `amount` tokens./
function _burn(address account, uint256 amount) internal virtual { require(account != address(0x0)); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0x0), amount); }
function _burn(address account, uint256 amount) internal virtual { require(account != address(0x0)); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0x0), amount); }
84,092
109
// force Swap back if slippage above 49% for launch.
function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); }
function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); }
11,493
919
// And mint the child
backend.mint(msg.sender, children[i]);
backend.mint(msg.sender, children[i]);
21,814
8
// Trasnfer Mock Dai tokens to this contract for staking
daiToken.transferFrom(msg.sender, address(this), _amount);
daiToken.transferFrom(msg.sender, address(this), _amount);
19,499
32
// Read Contract Functionsget total token balance in contract
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
function getTotalTokenBalance(address _tokenAddress) view public returns (uint256)
56,928
53
// Default fallback function
function() payable
function() payable
43,126
6
// remove the token amount from the users balance before send
balances[msg.sender] -= _amount;
balances[msg.sender] -= _amount;
13,836
104
// Withdraw DRPU tokens from the proxy and reduce the owners weight accordingly _value The amount of DRPU tokens to withdraw /
function withdrawDRPU(uint _value) public { Balance storage b = allocated[msg.sender]; // Require sufficient balance require(b.drpu >= _value); require(b.drpu - _value <= b.drpu); // Update balance b.drpu -= _value; // Reduce weight _adjustWeight(msg.sender, _value, false); // Call external if (!drpuToken.transfer(msg.sender, _value)) { revert(); } }
function withdrawDRPU(uint _value) public { Balance storage b = allocated[msg.sender]; // Require sufficient balance require(b.drpu >= _value); require(b.drpu - _value <= b.drpu); // Update balance b.drpu -= _value; // Reduce weight _adjustWeight(msg.sender, _value, false); // Call external if (!drpuToken.transfer(msg.sender, _value)) { revert(); } }
41,235
32
// termRepoId A Term Repo id/borrower The address of the borrower/collateralToken The address of the collateral token locked/amount The amount of collateral being unlocked
function emitCollateralUnlocked( bytes32 termRepoId, address borrower, address collateralToken, uint256 amount ) external;
function emitCollateralUnlocked( bytes32 termRepoId, address borrower, address collateralToken, uint256 amount ) external;
27,884
1
// Mapping is also used for faster verification
mapping(address => bool) public frax_pools;
mapping(address => bool) public frax_pools;
25,637
6
// the hash contains all of the information about the meta transaction to be called
bytes32 _hash = getHash(signer, destination, value, data, rewardToken, rewardAmount);
bytes32 _hash = getHash(signer, destination, value, data, rewardToken, rewardAmount);
38,199
14
// Add extra owner. /
function addOwner(address owner) onlyOwner public { require(owner != address(0)); require(!isOwner[owner]); ownerHistory.push(owner); isOwner[owner] = true; emit OwnerAddedEvent(owner); }
function addOwner(address owner) onlyOwner public { require(owner != address(0)); require(!isOwner[owner]); ownerHistory.push(owner); isOwner[owner] = true; emit OwnerAddedEvent(owner); }
9,182
98
// Holders fee
fees[2] = tAmount * _taxHolderFee / 100; // t fees[3] = fees[2] * rate; // r
fees[2] = tAmount * _taxHolderFee / 100; // t fees[3] = fees[2] * rate; // r
29,154
50
// 8% fee if a user deposits and withdraws in between same block and 59 minutes.
pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(userFeeStage[1]).div(100)); pool.lpToken.safeTransfer(address(devaddr), _amount.mul(devFeeStage[1]).div(100));
pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(userFeeStage[1]).div(100)); pool.lpToken.safeTransfer(address(devaddr), _amount.mul(devFeeStage[1]).div(100));
13,422
5
// Adds an account to storage THROWS when `msg.sender` doesn't have permission THROWS when the account already existsaddr The address of the accountkind The kind of accountisFrozen The frozen status of the accountparent The account parent/ownerhash The hash that uniquely identifies the account /
function addAccount(address addr, uint8 kind, bool isFrozen, address parent, bytes32 hash)
function addAccount(address addr, uint8 kind, bool isFrozen, address parent, bytes32 hash)
43,853
45
// Sending ether directly to the contract invokes buy() and assigns tokens to the sender
function () public payable { buy(); }
function () public payable { buy(); }
18,764
0
// be specified by overriding the virtual {_implementation} function.Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to adifferent contract through the {_delegate} function./ Delegates the current call to `implementation`.This function does not return to its internall call site, it will return directly to the external caller. /
function _delegate(address implementation) internal {
function _delegate(address implementation) internal {
32,177
36
// An auxiliary function, calculate parameter d1 and d2 in B_S formulas. currentPrice current underlying price. strikePrice option's strike price. expiration option's expiration left time. Equal option's expiration timestamp - now. derta implied volatility value in B-S formulas. /
function calculateD1D2(uint256 currentPrice, uint256 strikePrice, uint256 expiration, uint256 derta)
function calculateD1D2(uint256 currentPrice, uint256 strikePrice, uint256 expiration, uint256 derta)
31,868
130
// We use < for ownerIndexEnd and tokenBalanceOwner because tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed
require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" );
require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" );
13,946
33
// View function to search for a known key, salt, and/or submittergiven a supplied home address. Keys can be controlled directly by anaddress that matches the first 20 bytes of the key, or they can be derivedfrom a salt and a submitter - if the key is not a derived key, the salt andsubmitter fields will both have a value of zero. homeAddress address The home address to check for key information.return The key, salt, and/or submitter used to deploy to the home address,assuming they have been submitted to the reverse lookup. To populate these values, call `setReverseLookup` for cases where
function reverseLookup(address homeAddress)
function reverseLookup(address homeAddress)
44,070
8
// Get the CandidateCount weight hint/ @custom:selector a9a981a3/ return The CandidateCount weight hint
function candidateCount() external view returns (uint256);
function candidateCount() external view returns (uint256);
32,297
19
// Returns total supply of issued tokens /
function totalSupply() constant returns (uint256) { return supply; }
function totalSupply() constant returns (uint256) { return supply; }
877
21
// function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path, bool useRebate) external view returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] calldata path, bool useRebate, address _user) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path, bool useRebate) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path, bool useRebate, address _user) external view returns (uint[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin,
function getAmountsOut(uint amountIn, address[] calldata path, bool useRebate) external view returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] calldata path, bool useRebate, address _user) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path, bool useRebate) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path, bool useRebate, address _user) external view returns (uint[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin,
13,337
24
// Get the active delegates state for `account` at epoch `epoch`
function getActiveDelegation(address account, uint16 epoch) public view returns (DelegationChange memory activeDelegation, uint16 latestEpoch) { DelegationState storage userState = delegatorStates[account]; if (userState.latestChangeEpoch == 0) { return (activeDelegation, 0); } if (epoch >= userState.latestChangeEpoch) { return (userState.delegationTimeline[userState.latestChangeEpoch], userState.latestChangeEpoch); } uint16 nextChange = 0; while (true) { if (userState.delegationTimeline[nextChange].nextChange > epoch) { return (userState.delegationTimeline[nextChange], nextChange); } nextChange = userState.delegationTimeline[nextChange].nextChange; } }
function getActiveDelegation(address account, uint16 epoch) public view returns (DelegationChange memory activeDelegation, uint16 latestEpoch) { DelegationState storage userState = delegatorStates[account]; if (userState.latestChangeEpoch == 0) { return (activeDelegation, 0); } if (epoch >= userState.latestChangeEpoch) { return (userState.delegationTimeline[userState.latestChangeEpoch], userState.latestChangeEpoch); } uint16 nextChange = 0; while (true) { if (userState.delegationTimeline[nextChange].nextChange > epoch) { return (userState.delegationTimeline[nextChange], nextChange); } nextChange = userState.delegationTimeline[nextChange].nextChange; } }
22,036
155
// Returns whether the CKToken component default position real unit is greater than or equal to units passed in. /
function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) { return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); }
function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) { return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); }
6,965
54
// burn user&39;s token BST token balance, refund Eth sent
uint256 ethRefund = fundValue[msg.sender]; balancesArray[msg.sender] = 0; fundValue[msg.sender] = 0; Burn(msg.sender, ethRefund);
uint256 ethRefund = fundValue[msg.sender]; balancesArray[msg.sender] = 0; fundValue[msg.sender] = 0; Burn(msg.sender, ethRefund);
30,024
55
// create iNFT bound to NFT minted and locking the AI Personality minted
IntelligentNFTv2(iNftContract).mintBatch( nextId, // first recordId aliValue, // ALI value personalityContract, // AI Personality contract address nextId, // first AI Personality ID nftContract, // NFT contract address nextId, // first target NFT ID _amount // amount of iNFTs to create );
IntelligentNFTv2(iNftContract).mintBatch( nextId, // first recordId aliValue, // ALI value personalityContract, // AI Personality contract address nextId, // first AI Personality ID nftContract, // NFT contract address nextId, // first target NFT ID _amount // amount of iNFTs to create );
45,065
33
// Stop copying when the memory counter reaches the new combined length of the arrays.
end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) {
25,467
41
// unlist tulip
tulips[tokenId].listingTime = 0;
tulips[tokenId].listingTime = 0;
59,406
27
// Retrieve the offer item.
OfferItem memory offerItem = orderParameters.offer[i];
OfferItem memory offerItem = orderParameters.offer[i];
14,912
31
// datasize = message length - payload offset
datasize := sub(mload(_data), srcdataptr)
datasize := sub(mload(_data), srcdataptr)
33,990
0
// wallet for charity - GiveEth https:giveth.io/
address public charityWallet = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc; address public ownerWallet; address public owner; bool public gameStarted; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event Bounty(address hunter, uint256 amount); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
address public charityWallet = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc; address public ownerWallet; address public owner; bool public gameStarted; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event Bounty(address hunter, uint256 amount); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
57,858
63
// Bid event
emit Bid( _mintableToken, tokenID, _auction.lastOwner, _auction.highestBidder, _auction.currentBid, block.timestamp, _auction.erc20Token );
emit Bid( _mintableToken, tokenID, _auction.lastOwner, _auction.highestBidder, _auction.currentBid, block.timestamp, _auction.erc20Token );
20,488
59
// Burn on behalf
function approveBurnOnBehalf(address delegate) external { _setApproval(BURN_FOR_ADDRESS, msg.sender, delegate); }
function approveBurnOnBehalf(address delegate) external { _setApproval(BURN_FOR_ADDRESS, msg.sender, delegate); }
12,163
6
// The mapping below maps all requesters' IDs to their studentId
mapping(uint256 => uint256[]) public requestOwners;
mapping(uint256 => uint256[]) public requestOwners;
45,060
46
// See {ITokenYou-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for ``sender``'s tokens of at least`amount`. /
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; }
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; }
10,624
132
// The admin of reward token
address public override admin;
address public override admin;
40,471
38
// using Address for address;
mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public whiteLists; uint256 private _totalSupply; string private _name; string private _symbol;
mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public whiteLists; uint256 private _totalSupply; string private _name; string private _symbol;
37,934
13
// TMHC-MOMO 결합 팀 스테이킹 여부를 저장합니다.
struct StakeTeam{ address stakeowner; uint16[] boostIds; uint256 lastUpdateBlock; }
struct StakeTeam{ address stakeowner; uint16[] boostIds; uint256 lastUpdateBlock; }
20,587
8
// Compute new balances.
sumOutcome = sumOutcome.add(newBals[i]);
sumOutcome = sumOutcome.add(newBals[i]);
44,932
73
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) { sharesToUnlock = (schedule.initialLockedTokens.sub(schedule.unlockedTokens)); schedule.lastUnlockTimestampSec = schedule.endAtSec; } else {
if (now >= schedule.endAtSec) { sharesToUnlock = (schedule.initialLockedTokens.sub(schedule.unlockedTokens)); schedule.lastUnlockTimestampSec = schedule.endAtSec; } else {
17,852
478
// Cutoff where an exchange rate may overflow after multiplying by an underlying balance./Approximately 1.2e49
uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE;
uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE;
36,487
1
// The total supply of interest tokens
uint128 public override interestSupply;
uint128 public override interestSupply;
24,236
279
// non-zero _value and arithmetic overflow check on the allowance
require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
49,864
49
// uint[] memory ids = c.putids;
uint len = c.lastid; putusers memory firstuser = c.aucusers[0];
uint len = c.lastid; putusers memory firstuser = c.aucusers[0];
47,631
58
// Verify that the implementation address is a contract.
require(Address.isContract(implementation), "ERR_NOT_CONTRACT");
require(Address.isContract(implementation), "ERR_NOT_CONTRACT");
46,931
185
// Defines colors for OG NFTs. When minting, a color and an application (which part of the OG NFT to colorize) has to be defined.There are four different applications (back, frame, digit, slug). You can totally mess your mint up by using unsupported color strings. Make sure you know what you are doing as there is no refund for wasted mints. nfttank.eth /
contract OGColor is ERC721, Ownable { uint256 private _totalSupply = 0; uint256 private constant MAX_SUPPLY = 2500; mapping(uint256 => string) private _colors; mapping(uint256 => string) private _applications; mapping(address => string[]) private _backColorsForAddress; mapping(address => string[]) private _frameColorsForAddress; mapping(address => string[]) private _digitColorsForAddress; mapping(address => string[]) private _slugColorsForAddress; uint256 public _colorPrice = 40000000000000000; //0.04 ETH uint256 public _extPrice = 100000000000000000; //0.10 ETH; constructor() ERC721("OGColor", "OGCOLOR") Ownable() { } /** * @notice Mint a color for a specific application for all your OG tokens you hold in the same wallet. * Applications are back, frame, digit and slug. * It's recommended to use lower case color strings like #ffffff instead of #FFFFFF. * You can totally mess your mint up by using unsupported color strings. * Make sure you know what you are doing as there is no refund for wasted mints. * @param application The part of the OG NFT to colorize. back, frame, digit or slug. * @param color The color of the NFT to mint. Use a format like #ffffff or #fff. If you mess this up, your minted color won't work. */ function mint(string calldata application, string calldata color) public payable { require(_totalSupply < MAX_SUPPLY, "No tokens available anymore."); require(isValidApplication(application), "Application invalid, allowed are 'back', 'frame', 'digit' and 'slug'."); if (_msgSender() != owner()) { if (bytes(color).length <= 7) { // like #527862 or #fff require(_colorPrice <= msg.value, "Ether value sent is not correct"); } else { // what can that be? oO require(_extPrice <= msg.value, "Ether value sent is not correct"); } } uint256 newId = ++_totalSupply; _colors[newId] = color; _applications[newId] = application; _safeMint(_msgSender(), newId); } function setPrice(uint256 forColor, uint256 forExt) external onlyOwner { _colorPrice = forColor; _extPrice = forExt; } function getPrice() external view returns (uint256, uint256) { return (_colorPrice, _extPrice); } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function totalSupply() public view virtual returns (uint256) { return _totalSupply; } function renderSvg(uint256 tokenId) public virtual view returns (string memory) { require(tokenId > 0 && tokenId <= MAX_SUPPLY, "Token Id invalid"); require(_exists(tokenId), "Token does not exist"); string[] memory parts = new string[](7); parts[0] = "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='1000' height='1000' viewBox='0 0 1000 1000'>"; parts[1] = string(abi.encodePacked("<defs>", formatColor(_colors[tokenId], _applications[tokenId]), "</defs>")); parts[2] = "<mask id='_mask'>"; parts[3] = " <circle vector-effect='non-scaling-stroke' cx='500' cy='500' r='450' fill='white' stroke='none' />"; parts[4] = "</mask>"; parts[5] = string(abi.encodePacked("<circle vector-effect='non-scaling-stroke' cx='500' cy='500' r='450' fill='url(#", _applications[tokenId], ")' mask='url(#_mask)' />")); parts[6] = "</svg>"; return string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6])); } function tokenURI(uint256 tokenId) override public view returns (string memory) { require(tokenId > 0 && tokenId <= MAX_SUPPLY, "Token Id invalid"); require(_exists(tokenId), "Token does not exist"); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "OG Color", "description": "", ', getAttributesForColor(tokenId), ', "image": "data:image/svg+xml;base64,', Base64.encode(bytes(renderSvg(tokenId))), '"}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } function getAttributesForColor(uint256 tokenId) private view returns (string memory) { bytes memory ax = '#c8fbfb'; bytes memory ap = '#856f56'; bytes memory zz = '#7da269'; string memory traits = string(abi.encodePacked('{ "trait_type": "Application", "value": "', _applications[tokenId], '" }')); bytes memory color = bytes(_colors[tokenId]); string memory type_; if (stringContains(color, ax)) { type_ = 'Alien'; } else if (stringContains(color, ap)) { type_ = 'Ape'; } else if (stringContains(color, zz)) { type_ = 'Zombie'; } if (bytes(type_).length > 0) { traits = string(abi.encodePacked(traits, (bytes(traits).length > 0 ? ', ' : ''), '{ "trait_type": "Type", "value": "', type_, '" }')); } return string(abi.encodePacked('"attributes": [', traits, ']')); } function getOgAttributes(address forAddress, uint256 tokenId) external view returns (string memory) { (string memory back, string memory frame, string memory digit, string memory slug) = this.getColors(forAddress, tokenId); bytes memory b = bytes(back); bytes memory f = bytes(frame); bytes memory d = bytes(digit); bytes memory s = bytes(slug); bytes memory ax = '#c8fbfb'; bytes memory ap = '#856f56'; bytes memory zz = '#7da269'; if (stringContains(b, ax) || stringContains(f, ax) || stringContains(d, ax) || stringContains(s, ax)) { return '{ "trait_type": "Color", "value": "Alien" }'; } if (stringContains(b, ap) || stringContains(f, ap) || stringContains(d, ap) || stringContains(s, ap)) { return '{ "trait_type": "Color", "value": "Ape" }'; } if (stringContains(b, zz) || stringContains(f, zz) || stringContains(d, zz) || stringContains(s, zz)) { return '{ "trait_type": "Color", "value": "Zombie" }'; } return ''; } function isValidApplication(string calldata application) private pure returns (bool) { bytes32 k = keccak256(bytes(application)); return k == keccak256("back") || k == keccak256("frame") || k == keccak256("digit") || k == keccak256("slug"); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { super._beforeTokenTransfer(from, to, tokenId); if (from == to) // pseudo use of from-variable to prevent warnings while keeping the overridden method signature return; string memory color = _colors[tokenId]; bytes32 application = keccak256(bytes(_applications[tokenId])); if (application == keccak256("back")) { if (from != address(0)) removeColor(_backColorsForAddress[from], color); _backColorsForAddress[to].push(color); } else if (application == keccak256("frame")) { if (from != address(0)) removeColor(_frameColorsForAddress[from], color); _frameColorsForAddress[to].push(color); } else if (application == keccak256("digit")) { if (from != address(0)) removeColor(_digitColorsForAddress[from], color); _digitColorsForAddress[to].push(color); } else if (application == keccak256("slug")) { if (from != address(0)) removeColor(_slugColorsForAddress[from], color); _slugColorsForAddress[to].push(color); } } function removeColor(string[] storage colors, string memory exceptColor) private { bytes memory except = bytes(exceptColor); // https://ethereum.stackexchange.com/questions/63653/why-i-cannot-loop-through-array-backwards-in-solidity/63654 for (uint256 i = colors.length; i > 0; i--) { if (bytesEquals(bytes(colors[i - 1]), except)) { delete colors[i - 1]; return; } } } function bytesEquals(bytes memory a, bytes memory b) internal pure returns(bool) { return (a.length == b.length) && (keccak256(a) == keccak256(b)); } function stringContains(bytes memory where, bytes memory what) internal pure returns (bool) { require(where.length >= what.length); bool found = false; for (uint i = 0; i <= where.length - what.length; i++) { bool flag = true; for (uint j = 0; j < what.length; j++) if (where [i + j] != what [j]) { flag = false; break; } if (flag) { found = true; break; } } return found; } function getColors(address forAddress, uint256 tokenId) external view returns (string memory backColor, string memory frameColor, string memory digitColor, string memory slugColor) { string[] memory colors = tokenId < 99999 ? _backColorsForAddress[forAddress] : new string[](0); // pseudo use of tokenId to prevent warnings. We still want the tokenId in the method arguments to be able to modify colors by the tokenId in the future. string memory back = getColorFromArray(colors, "#ffffff", "back"); colors = _frameColorsForAddress[forAddress]; string memory frame = getColorFromArray(colors, "#000000", "frame"); colors = _digitColorsForAddress[forAddress]; string memory digit = getColorFromArray(colors, "#000000", "digit"); colors = _slugColorsForAddress[forAddress]; string memory slug = getColorFromArray(colors, "#ffffff", "slug"); return (back, frame, digit, slug); } function getColorFromArray(string[] memory colors, string memory fallbackValue, string memory application) internal pure returns (string memory) { string memory color; // https://ethereum.stackexchange.com/questions/63653/why-i-cannot-loop-through-array-backwards-in-solidity/63654 for (uint256 i = colors.length; i > 0; i--) { if (bytes(colors[i - 1]).length > 0) { color = colors[i - 1]; break; } } if (bytes(color).length == 0) { color = fallbackValue; } return formatColor(color, application); } function formatColor(string memory color, string memory application) internal pure returns (string memory) { // turn hex colors like #527862 into a linear gradient if (bytes(color).length <= 7) { return string(abi.encodePacked("<linearGradient id='", application, "'><stop stop-color='", color, "'/></linearGradient>")); } return color; } }
contract OGColor is ERC721, Ownable { uint256 private _totalSupply = 0; uint256 private constant MAX_SUPPLY = 2500; mapping(uint256 => string) private _colors; mapping(uint256 => string) private _applications; mapping(address => string[]) private _backColorsForAddress; mapping(address => string[]) private _frameColorsForAddress; mapping(address => string[]) private _digitColorsForAddress; mapping(address => string[]) private _slugColorsForAddress; uint256 public _colorPrice = 40000000000000000; //0.04 ETH uint256 public _extPrice = 100000000000000000; //0.10 ETH; constructor() ERC721("OGColor", "OGCOLOR") Ownable() { } /** * @notice Mint a color for a specific application for all your OG tokens you hold in the same wallet. * Applications are back, frame, digit and slug. * It's recommended to use lower case color strings like #ffffff instead of #FFFFFF. * You can totally mess your mint up by using unsupported color strings. * Make sure you know what you are doing as there is no refund for wasted mints. * @param application The part of the OG NFT to colorize. back, frame, digit or slug. * @param color The color of the NFT to mint. Use a format like #ffffff or #fff. If you mess this up, your minted color won't work. */ function mint(string calldata application, string calldata color) public payable { require(_totalSupply < MAX_SUPPLY, "No tokens available anymore."); require(isValidApplication(application), "Application invalid, allowed are 'back', 'frame', 'digit' and 'slug'."); if (_msgSender() != owner()) { if (bytes(color).length <= 7) { // like #527862 or #fff require(_colorPrice <= msg.value, "Ether value sent is not correct"); } else { // what can that be? oO require(_extPrice <= msg.value, "Ether value sent is not correct"); } } uint256 newId = ++_totalSupply; _colors[newId] = color; _applications[newId] = application; _safeMint(_msgSender(), newId); } function setPrice(uint256 forColor, uint256 forExt) external onlyOwner { _colorPrice = forColor; _extPrice = forExt; } function getPrice() external view returns (uint256, uint256) { return (_colorPrice, _extPrice); } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function totalSupply() public view virtual returns (uint256) { return _totalSupply; } function renderSvg(uint256 tokenId) public virtual view returns (string memory) { require(tokenId > 0 && tokenId <= MAX_SUPPLY, "Token Id invalid"); require(_exists(tokenId), "Token does not exist"); string[] memory parts = new string[](7); parts[0] = "<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='1000' height='1000' viewBox='0 0 1000 1000'>"; parts[1] = string(abi.encodePacked("<defs>", formatColor(_colors[tokenId], _applications[tokenId]), "</defs>")); parts[2] = "<mask id='_mask'>"; parts[3] = " <circle vector-effect='non-scaling-stroke' cx='500' cy='500' r='450' fill='white' stroke='none' />"; parts[4] = "</mask>"; parts[5] = string(abi.encodePacked("<circle vector-effect='non-scaling-stroke' cx='500' cy='500' r='450' fill='url(#", _applications[tokenId], ")' mask='url(#_mask)' />")); parts[6] = "</svg>"; return string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6])); } function tokenURI(uint256 tokenId) override public view returns (string memory) { require(tokenId > 0 && tokenId <= MAX_SUPPLY, "Token Id invalid"); require(_exists(tokenId), "Token does not exist"); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "OG Color", "description": "", ', getAttributesForColor(tokenId), ', "image": "data:image/svg+xml;base64,', Base64.encode(bytes(renderSvg(tokenId))), '"}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } function getAttributesForColor(uint256 tokenId) private view returns (string memory) { bytes memory ax = '#c8fbfb'; bytes memory ap = '#856f56'; bytes memory zz = '#7da269'; string memory traits = string(abi.encodePacked('{ "trait_type": "Application", "value": "', _applications[tokenId], '" }')); bytes memory color = bytes(_colors[tokenId]); string memory type_; if (stringContains(color, ax)) { type_ = 'Alien'; } else if (stringContains(color, ap)) { type_ = 'Ape'; } else if (stringContains(color, zz)) { type_ = 'Zombie'; } if (bytes(type_).length > 0) { traits = string(abi.encodePacked(traits, (bytes(traits).length > 0 ? ', ' : ''), '{ "trait_type": "Type", "value": "', type_, '" }')); } return string(abi.encodePacked('"attributes": [', traits, ']')); } function getOgAttributes(address forAddress, uint256 tokenId) external view returns (string memory) { (string memory back, string memory frame, string memory digit, string memory slug) = this.getColors(forAddress, tokenId); bytes memory b = bytes(back); bytes memory f = bytes(frame); bytes memory d = bytes(digit); bytes memory s = bytes(slug); bytes memory ax = '#c8fbfb'; bytes memory ap = '#856f56'; bytes memory zz = '#7da269'; if (stringContains(b, ax) || stringContains(f, ax) || stringContains(d, ax) || stringContains(s, ax)) { return '{ "trait_type": "Color", "value": "Alien" }'; } if (stringContains(b, ap) || stringContains(f, ap) || stringContains(d, ap) || stringContains(s, ap)) { return '{ "trait_type": "Color", "value": "Ape" }'; } if (stringContains(b, zz) || stringContains(f, zz) || stringContains(d, zz) || stringContains(s, zz)) { return '{ "trait_type": "Color", "value": "Zombie" }'; } return ''; } function isValidApplication(string calldata application) private pure returns (bool) { bytes32 k = keccak256(bytes(application)); return k == keccak256("back") || k == keccak256("frame") || k == keccak256("digit") || k == keccak256("slug"); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { super._beforeTokenTransfer(from, to, tokenId); if (from == to) // pseudo use of from-variable to prevent warnings while keeping the overridden method signature return; string memory color = _colors[tokenId]; bytes32 application = keccak256(bytes(_applications[tokenId])); if (application == keccak256("back")) { if (from != address(0)) removeColor(_backColorsForAddress[from], color); _backColorsForAddress[to].push(color); } else if (application == keccak256("frame")) { if (from != address(0)) removeColor(_frameColorsForAddress[from], color); _frameColorsForAddress[to].push(color); } else if (application == keccak256("digit")) { if (from != address(0)) removeColor(_digitColorsForAddress[from], color); _digitColorsForAddress[to].push(color); } else if (application == keccak256("slug")) { if (from != address(0)) removeColor(_slugColorsForAddress[from], color); _slugColorsForAddress[to].push(color); } } function removeColor(string[] storage colors, string memory exceptColor) private { bytes memory except = bytes(exceptColor); // https://ethereum.stackexchange.com/questions/63653/why-i-cannot-loop-through-array-backwards-in-solidity/63654 for (uint256 i = colors.length; i > 0; i--) { if (bytesEquals(bytes(colors[i - 1]), except)) { delete colors[i - 1]; return; } } } function bytesEquals(bytes memory a, bytes memory b) internal pure returns(bool) { return (a.length == b.length) && (keccak256(a) == keccak256(b)); } function stringContains(bytes memory where, bytes memory what) internal pure returns (bool) { require(where.length >= what.length); bool found = false; for (uint i = 0; i <= where.length - what.length; i++) { bool flag = true; for (uint j = 0; j < what.length; j++) if (where [i + j] != what [j]) { flag = false; break; } if (flag) { found = true; break; } } return found; } function getColors(address forAddress, uint256 tokenId) external view returns (string memory backColor, string memory frameColor, string memory digitColor, string memory slugColor) { string[] memory colors = tokenId < 99999 ? _backColorsForAddress[forAddress] : new string[](0); // pseudo use of tokenId to prevent warnings. We still want the tokenId in the method arguments to be able to modify colors by the tokenId in the future. string memory back = getColorFromArray(colors, "#ffffff", "back"); colors = _frameColorsForAddress[forAddress]; string memory frame = getColorFromArray(colors, "#000000", "frame"); colors = _digitColorsForAddress[forAddress]; string memory digit = getColorFromArray(colors, "#000000", "digit"); colors = _slugColorsForAddress[forAddress]; string memory slug = getColorFromArray(colors, "#ffffff", "slug"); return (back, frame, digit, slug); } function getColorFromArray(string[] memory colors, string memory fallbackValue, string memory application) internal pure returns (string memory) { string memory color; // https://ethereum.stackexchange.com/questions/63653/why-i-cannot-loop-through-array-backwards-in-solidity/63654 for (uint256 i = colors.length; i > 0; i--) { if (bytes(colors[i - 1]).length > 0) { color = colors[i - 1]; break; } } if (bytes(color).length == 0) { color = fallbackValue; } return formatColor(color, application); } function formatColor(string memory color, string memory application) internal pure returns (string memory) { // turn hex colors like #527862 into a linear gradient if (bytes(color).length <= 7) { return string(abi.encodePacked("<linearGradient id='", application, "'><stop stop-color='", color, "'/></linearGradient>")); } return color; } }
49,331
162
// Owner restakes position with ID: `_id` for `_period` seconds/_id ID of the position/_period Period of time, in seconds, to lockup your funds/ return _sher Amount of SHER tokens to be released to owner address after `_period` ends/Only the owner of `_id` will be able to restake their position using this call/`_period` needs to be whitelisted/Can only be called after lockup `_period` has ended
function ownerRestake(uint256 _id, uint256 _period) external returns (uint256 _sher);
function ownerRestake(uint256 _id, uint256 _period) external returns (uint256 _sher);
62,295
9
// owner > nonce mapping used in {permit}.
mapping(address => uint256) public nonces; event Approval(address indexed owner, address indexed spender, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 amount);
mapping(address => uint256) public nonces; event Approval(address indexed owner, address indexed spender, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 amount);
41,651
81
// Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; }
function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; }
20,010
242
// Usable to cancel hashes generated from {hashToSignToSellToken} /
function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); }
function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale(_msgSender(), version, nonce, tokenId, pricesAndTimestamps); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); }
38,492