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
18
// Smart contract constructor. name Full collection name symbol Collection symbol maxNftSupply Max collection supply /
constructor(string memory name, string memory symbol, uint256 maxNftSupply) ERC721(name, symbol) { MAX_testies = maxNftSupply; reserveAirdroptesties(AIRDROP_testies); }
constructor(string memory name, string memory symbol, uint256 maxNftSupply) ERC721(name, symbol) { MAX_testies = maxNftSupply; reserveAirdroptesties(AIRDROP_testies); }
7,227
7
// Set round length. Only callable by the controller owner _roundLength Round length in blocks /
function setRoundLength(uint256 _roundLength) external onlyControllerOwner { require(_roundLength > 0, "round length cannot be 0"); if (roundLength == 0) {
function setRoundLength(uint256 _roundLength) external onlyControllerOwner { require(_roundLength > 0, "round length cannot be 0"); if (roundLength == 0) {
1,282
33
// Returns true if the token is an underlying/_token address/ return bool true if underlying
function isUnderlying(address _token) public view returns (bool) { return _underlying.includes(_token); }
function isUnderlying(address _token) public view returns (bool) { return _underlying.includes(_token); }
28,549
81
// Insert or update leader
if (newPos < maxLeaders) { if (oldPos < maxLeaders-1) {
if (newPos < maxLeaders) { if (oldPos < maxLeaders-1) {
18,032
97
// Fetches the given transaction from the given fork and executes it on the current state
function transact(uint256 forkId, bytes32 txHash) external;
function transact(uint256 forkId, bytes32 txHash) external;
27,682
0
// ERC1538 Transparent Contract Standard/Required interface/Note: the ERC-165 identifier for this interface is 0x61455567
interface IERC1538 { /// @dev This emits when one or a set of functions are updated in a transparent contract. /// The message string should give a short description of the change and why /// the change was made. event CommitMessage(string message); /// @dev This emits for each function that is updated in a transparent contract. /// functionId is the bytes4 of the keccak256 of the function signature. /// oldDelegate is the delegate contract address of the old delegate contract if /// the function is being replaced or removed. /// oldDelegate is the zero value address(0) if a function is being added for the /// first time. /// newDelegate is the delegate contract address of the new delegate contract if /// the function is being added for the first time or if the function is being /// replaced. /// newDelegate is the zero value address(0) if the function is being removed. event FunctionUpdate(bytes4 indexed functionId, address indexed oldDelegate, address indexed newDelegate, string functionSignature); /// @notice Updates functions in a transparent contract. /// @dev If the value of _delegate is zero then the functions specified /// in _functionSignatures are removed. /// If the value of _delegate is a delegate contract address then the functions /// specified in _functionSignatures will be delegated to that address. /// @param _delegate The address of a delegate contract to delegate to or zero /// to remove functions. /// @param _functionSignatures A list of function signatures listed one after the other /// @param _commitMessage A short description of the change and why it is made /// This message is passed to the CommitMessage event. function updateContract(address _delegate, string calldata _functionSignatures, string calldata _commitMessage) external; }
interface IERC1538 { /// @dev This emits when one or a set of functions are updated in a transparent contract. /// The message string should give a short description of the change and why /// the change was made. event CommitMessage(string message); /// @dev This emits for each function that is updated in a transparent contract. /// functionId is the bytes4 of the keccak256 of the function signature. /// oldDelegate is the delegate contract address of the old delegate contract if /// the function is being replaced or removed. /// oldDelegate is the zero value address(0) if a function is being added for the /// first time. /// newDelegate is the delegate contract address of the new delegate contract if /// the function is being added for the first time or if the function is being /// replaced. /// newDelegate is the zero value address(0) if the function is being removed. event FunctionUpdate(bytes4 indexed functionId, address indexed oldDelegate, address indexed newDelegate, string functionSignature); /// @notice Updates functions in a transparent contract. /// @dev If the value of _delegate is zero then the functions specified /// in _functionSignatures are removed. /// If the value of _delegate is a delegate contract address then the functions /// specified in _functionSignatures will be delegated to that address. /// @param _delegate The address of a delegate contract to delegate to or zero /// to remove functions. /// @param _functionSignatures A list of function signatures listed one after the other /// @param _commitMessage A short description of the change and why it is made /// This message is passed to the CommitMessage event. function updateContract(address _delegate, string calldata _functionSignatures, string calldata _commitMessage) external; }
26,864
130
// See {IERC20-approve}. Note that accounts cannot have allowance issued by their operators. /
function approve(address spender, uint256 value) public override returns (bool) { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); address holder = _msgSender(); _approve(holder, spender, value); return true; }
function approve(address spender, uint256 value) public override returns (bool) { require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role"); address holder = _msgSender(); _approve(holder, spender, value); return true; }
15,835
172
// Internal function to unset a Locatoridentifier address On-chain address identifying the owner of a locator/
function _unsetLocator( address identifier
function _unsetLocator( address identifier
10,266
162
// The amounts of token0 and token1 that are owed to the protocol/Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
function protocolFees() external view returns (uint128 token0, uint128 token1);
37,033
72
// Determines if token exists by checking it's price_tokenId uint256 ID of token/
function tokenExists (uint256 _tokenId) public view returns (bool _exists) { return arkData[_tokenId].price > 0; }
function tokenExists (uint256 _tokenId) public view returns (bool _exists) { return arkData[_tokenId].price > 0; }
12,970
126
// Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws./assetData Byte array encoded for the asset./from Address to transfer token from./to Address to transfer token to./amount Amount of token to transfer.
function dispatchTransferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal;
function dispatchTransferFrom( bytes memory assetData, address from, address to, uint256 amount ) internal;
20,232
1
// Internal function for reducing onlyMediator modifier bytecode overhead. /
function _onlyMediator() internal view { IAMB bridge = bridgeContract(); require(msg.sender == address(bridge)); require(bridge.messageSender() == mediatorContractOnOtherSide()); }
function _onlyMediator() internal view { IAMB bridge = bridgeContract(); require(msg.sender == address(bridge)); require(bridge.messageSender() == mediatorContractOnOtherSide()); }
4,622
94
// info about rewards for a particular staking token
struct StakingRewardsInfo { address stakingRewards; uint rewardAmount; }
struct StakingRewardsInfo { address stakingRewards; uint rewardAmount; }
6,648
300
// Tell appeal-related information of a certain adjudication round_disputeId Identification number of the dispute being queried_roundId Identification number of the round being queried return maker Address of the account appealing the given round return appealedRuling Ruling confirmed by the appealer of the given round return taker Address of the account confirming the appeal of the given round return opposedRuling Ruling confirmed by the appeal taker of the given round/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
19,530
63
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20;
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20;
12,532
154
// The underlying - staking token mapping
mapping(address => address) public _stakingTokenMap;
mapping(address => address) public _stakingTokenMap;
55,236
23
// log1(bytes32(recoveredAddress), bytes32(DogeMessageLibrary.pub2address(uint(operatorPublicKeyX), operatorPublicKeyOdd)));
if (recoveredAddress != DogeMessageLibrary.pub2address(uint(operatorPublicKeyX), operatorPublicKeyOdd)) { emit ErrorDogeToken(ERR_OPERATOR_SIGNATURE); return; }
if (recoveredAddress != DogeMessageLibrary.pub2address(uint(operatorPublicKeyX), operatorPublicKeyOdd)) { emit ErrorDogeToken(ERR_OPERATOR_SIGNATURE); return; }
304
32
// ------------------------------ Request Ticket Life Cycle
event FileRequestTicket(address sender, uint ticketID, uint8 dataType, bool subjective, uint timeRequested, uint responseTimeWindow, uint feePaid);
event FileRequestTicket(address sender, uint ticketID, uint8 dataType, bool subjective, uint timeRequested, uint responseTimeWindow, uint feePaid);
8,125
42
// Constructor
function Utcoin() { totalSupply =10000000000000000 ; balances[msg.sender] = totalSupply; // Send all tokens to owner }
function Utcoin() { totalSupply =10000000000000000 ; balances[msg.sender] = totalSupply; // Send all tokens to owner }
17,604
1
// Give an account access to this role. /
function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; }
function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; }
30,469
113
// Used to initialize the contract during delegator contructortimelock_ The address of the Timelockstaking_ The address of the STAKINGvotingPeriod_ The initial voting periodvotingDelay_ The initial voting delayproposalThreshold_ The initial proposal threshold/
function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); staking = StakingInterface(staking_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; guardian = msg.sender; }
function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); staking = StakingInterface(staking_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; guardian = msg.sender; }
9,669
25
// Transfer `Crypto Dev` tokens from the user's address to the contract
ERC20(cryptoDevTokenAddress).transferFrom( msg.sender, address(this), _tokensSold );
ERC20(cryptoDevTokenAddress).transferFrom( msg.sender, address(this), _tokensSold );
31,937
187
// Interface for admin control /
interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); }
interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); }
33,537
1
// The Id of the pet that will be used for testing.
uint expectedPetId = 8;
uint expectedPetId = 8;
39,943
233
// If the price impact of one single tx is larger than priceFluctuation, skip the check only for liquidate()
if (!_skipFluctuationCheck) { _skipFluctuationCheck = isSingleTxOverFluctuation(_dir, quoteAssetAmount, _baseAssetAmount); }
if (!_skipFluctuationCheck) { _skipFluctuationCheck = isSingleTxOverFluctuation(_dir, quoteAssetAmount, _baseAssetAmount); }
29,871
6
// Send returns a boolean value indicating success or failure. This function is not recommended for sending Ether.
bool sent = _to.send(msg.value); require(sent, "Failed to send Ether");
bool sent = _to.send(msg.value); require(sent, "Failed to send Ether");
4,172
82
// The stored value fits in the slot, but the combined value will exceed it. get the keccak hash to get the contents of the array
mstore(0x0, _preBytes.slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32))
mstore(0x0, _preBytes.slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32))
33,007
129
// track claimable fees
uint256 public claimableFees;
uint256 public claimableFees;
13,560
79
// The minimum multiple that `callCost` must be above the credit/profit to be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
uint256 public profitFactor = 100;
20,176
7
// Account Liquidity represents the USD value borrowable by a user,/before it reaches liquidation. Users with a shortfall (negative liquidity/) are subject to liquidation, and can’t withdraw or borrow assets until Account Liquidity is positive again./For each market the user has entered into, their supplied balance is/multiplied by the market’s collateral factor, and summed; borrow balances are then subtracted,/to equal Account Liquidity./Borrowing an asset reduces Account Liquidity for each USD borrowed;/withdrawing an asset reduces Account Liquidity by the asset’s collateral factor times each USD withdrawn./Tuple of values (error, liquidity, shortfall). The error shall be 0 on success, otherwise an error code.
function getAccountLiquidity(address account) public view override returns ( uint256 error, uint256 liquidity, uint256 shortfall )
function getAccountLiquidity(address account) public view override returns ( uint256 error, uint256 liquidity, uint256 shortfall )
46,828
10
// Withdraw value from the deposit. withdrawAddress - Target to send to. amount- Amount to withdraw. /
function withdrawTo( address payable withdrawAddress, uint256 amount
function withdrawTo( address payable withdrawAddress, uint256 amount
24,540
116
// Approve Alchemix staking pools contract to transfer bAssets for deposits.
MassetHelpers.safeInfiniteApprove(bAsset, address(stakingPools));
MassetHelpers.safeInfiniteApprove(bAsset, address(stakingPools));
60,604
226
// issueId => [totalAmount, firstMatchAmount, secondMatchingAmount, thirdMatchingAmount]
mapping (uint256 => uint256[]) public historyAmount;
mapping (uint256 => uint256[]) public historyAmount;
13,262
20
// Pricing function `outputAmount` of token2 if we provide `inputAmount` of token1 in exchange.inputAmount uint256: Amount of token1 we are selling inputReserve uint256: Reserve of token1 we are selling outputReserve uint256: Reserve of token2 we are buyingreturn outputAmount uint256: Amount of token2 we receive in exchangefees taken intout account. 0,3 % fees . 0,3 % = 3/1000. Fees removed from `inputAmount` /
function getAmount( uint256 inputAmount, uint256 inputReserve, uint256 outputReserve
function getAmount( uint256 inputAmount, uint256 inputReserve, uint256 outputReserve
7,433
719
// loop over buckets in reverse order starting with the critical bucket
for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue;
for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue;
72,490
68
// gasLimitActive = false;
transferDelayEnabled = false; return true;
transferDelayEnabled = false; return true;
50,778
58
// Number of positions that the comma is shifted to the right. /
function digits() public pure returns(uint8) { return 24; }
function digits() public pure returns(uint8) { return 24; }
53,112
34
// refundMyContributions(): Allows users to refund their contributions in bulk/_sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer)/_jobId the index of the job/_contributionIds the array of indexes of the contributions being refunded
function refundMyContributions( address _sender, uint _jobId, uint _issuerId, uint[] memory _contributionIds) public senderIsValid(_sender)
function refundMyContributions( address _sender, uint _jobId, uint _issuerId, uint[] memory _contributionIds) public senderIsValid(_sender)
397
5
// The number of checkpoints
uint public supplyNumCheckpoints; event Deposit(address indexed from, uint tokenId, uint amount); event Withdraw(address indexed from, uint tokenId, uint amount); event NotifyReward(address indexed from, address indexed reward, uint epoch, uint amount); event ClaimRewards(address indexed from, address indexed reward, uint amount);
uint public supplyNumCheckpoints; event Deposit(address indexed from, uint tokenId, uint amount); event Withdraw(address indexed from, uint tokenId, uint amount); event NotifyReward(address indexed from, address indexed reward, uint epoch, uint amount); event ClaimRewards(address indexed from, address indexed reward, uint amount);
14,576
4
// head parts[2] = headSVGs[ KyodaiLibrary.parseInt(KyodaiLibrary.substring(_hash, 0, 1)) ];
parts[2] = headSVGs[ KyodaiLibrary.decodeHashIndex(KyodaiLibrary.substring(_hash, 0, 1)) ];
parts[2] = headSVGs[ KyodaiLibrary.decodeHashIndex(KyodaiLibrary.substring(_hash, 0, 1)) ];
20,052
40
// get this founder wallet
address oneFounderWallet = walletAddresses[i];
address oneFounderWallet = walletAddresses[i];
24,182
12
// thrown when invalid params for a method are submitted, e.g. 0x00 address
error AvoImportCreditsManager__InvalidParams();
error AvoImportCreditsManager__InvalidParams();
9,156
23
// only if specified in supplied indices, or we if we are doing "all" reduce the new allocationItem.amount
newAllocation[i].amount -= affordsForDestination;
newAllocation[i].amount -= affordsForDestination;
40,627
7
// This call returns a storage mapping with a unique non overwrite-able storage location which can be persisted through upgrades, even if they change storage layout
return (Storage.mappingAddressToPackedAddressUint("deposits"));
return (Storage.mappingAddressToPackedAddressUint("deposits"));
48,569
3
// Return the bps rate for reserve pool.
function getReservePoolBps() external view returns (uint256);
function getReservePoolBps() external view returns (uint256);
2,819
104
// Split the payment payout for the creator and fee recipient.nftContractThe nft contract. feeRecipient The fee recipient. feeBps The fee basis points. /
function _splitPayout( address nftContract, address feeRecipient, uint256 feeBps
function _splitPayout( address nftContract, address feeRecipient, uint256 feeBps
37,989
10
// Upload documentation for proof of marrage like a marriage certificate
function marriageProof(bytes IPFSProofHash) onlyowner
function marriageProof(bytes IPFSProofHash) onlyowner
22,225
34
// function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}./ Indicates that the contract has been initialized. /
bool private _initialized;
bool private _initialized;
2,259
5
// addInit - this function will write data of order to mapping inits in Initiations struct with address of the sender key
function addInit(address _addressFrom, address _addressTo, uint _amount, string _password) public
function addInit(address _addressFrom, address _addressTo, uint _amount, string _password) public
12,507
74
// See {IToken-freezePartialTokens}. /
function freezePartialTokens(address _userAddress, uint256 _amount) public override onlyAgent { uint256 balance = balanceOf(_userAddress); require(balance >= _frozenTokens[_userAddress] + _amount, "Amount exceeds available balance"); _frozenTokens[_userAddress] = _frozenTokens[_userAddress] + (_amount); emit TokensFrozen(_userAddress, _amount); }
function freezePartialTokens(address _userAddress, uint256 _amount) public override onlyAgent { uint256 balance = balanceOf(_userAddress); require(balance >= _frozenTokens[_userAddress] + _amount, "Amount exceeds available balance"); _frozenTokens[_userAddress] = _frozenTokens[_userAddress] + (_amount); emit TokensFrozen(_userAddress, _amount); }
5,536
15
// Maps debridgeId (see getDebridgeId) to threshold amount after which/ Math.max(excessConfirmations,SignatureVerifier.minConfirmations) is used instead of/ SignatureVerifier.minConfirmations
mapping(bytes32 => uint256) public getAmountThreshold;
mapping(bytes32 => uint256) public getAmountThreshold;
76,713
127
// Transfer ETH from msg.sender to protocol;
TransferETHHelper.safeTransferETH(address(this), _amount);
TransferETHHelper.safeTransferETH(address(this), _amount);
6,865
9
// Slices array from start (inclusive) to end (exclusive). Doesn't modify input array./
function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) { require(_start <= _end); if (_start == 0 && _end == _array.length) { return _array; } uint size = _end - _start; uint32[] memory sliced = new uint32[](size); for (uint i = 0; i < size; i++) { sliced[i] = _array[i + _start]; } return sliced; }
function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) { require(_start <= _end); if (_start == 0 && _end == _array.length) { return _array; } uint size = _end - _start; uint32[] memory sliced = new uint32[](size); for (uint i = 0; i < size; i++) { sliced[i] = _array[i + _start]; } return sliced; }
40,053
42
// The function can be called only by a whitelisted release agent. /
modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; }
modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; }
47,614
3,772
// 1887
entry "uninstituted" : ENG_ADJECTIVE
entry "uninstituted" : ENG_ADJECTIVE
18,499
8
// Contract to interact between user and strategy, and distribute daoToken to user
contract DAOVaultMediumUSDC is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; IStrategy public strategy; address public pendingStrategy; bool public canSetPendingStrategy = true; uint256 public unlockTime; uint256 public constant LOCKTIME = 2 days; event MigrateFunds(address indexed fromStrategy, address indexed toStrategy, uint256 amount); constructor(address _token, address _strategy) ERC20("DAO Vault Medium USDC", "dvmUSDC") { _setupDecimals(6); token = IERC20(_token); strategy = IStrategy(_strategy); } /** * @notice Deposit into strategy * @param _amounts A list that contains amounts to deposit * Requirements: * - Only EOA account can call this function */ function deposit(uint256[] memory _amounts) external { require(!address(msg.sender).isContract(), "Only EOA"); uint256 _before = strategy.balanceOf(address(this)); strategy.deposit(_amounts); uint256 _after = strategy.balanceOf(address(this)); _mint(msg.sender, _after.sub(_before)); } /** * @notice Withdraw from strategy * @param _shares A list that contains shares to withdraw * @dev amount _shares = amount daoToken * Requirements: * - Only EOA account can call this function */ function withdraw(uint256[] memory _shares) external { require(!address(msg.sender).isContract(), "Only EOA"); uint256 _before = strategy.balanceOf(address(this)); strategy.withdraw(_shares); uint256 _after = strategy.balanceOf(address(this)); _burn(msg.sender, _before.sub(_after)); } /** * @notice Refund from strategy * @notice This function usually only available when strategy in vesting state * Requirements: * - Only EOA account can call this function * - Amount dvmToken of user must greater than 0 */ function refund() external { require(!address(msg.sender).isContract(), "Only EOA"); uint256 _shares = balanceOf(msg.sender); require(_shares > 0, "No balance to refund"); uint256 _before = strategy.balanceOf(address(this)); strategy.refund(_shares); uint256 _after = strategy.balanceOf(address(this)); _burn(msg.sender, _before.sub(_after)); } /** * @notice Set pending strategy * @param _pendingStrategy Address of pending strategy * Requirements: * - Only owner of this contract call this function * - Pending strategy must be a contract */ function setPendingStrategy(address _pendingStrategy) external onlyOwner { require(canSetPendingStrategy, "Cannot set pending strategy now"); require(_pendingStrategy.isContract(), "New strategy is not contract"); pendingStrategy = _pendingStrategy; } /** * @notice Unlock function migrateFunds() * Requirements: * - Only owner of this contract call this function */ function unlockMigrateFunds() external onlyOwner { unlockTime = block.timestamp + LOCKTIME; canSetPendingStrategy = false; } /** * @notice Migrate all funds from old strategy to new strategy * Requirements: * - Only owner of this contract call this function * - Calling this function within unlock time * - Pending strategy is set */ function migrateFunds() external onlyOwner { require(unlockTime <= block.timestamp && unlockTime + 1 days >= block.timestamp, "Function locked"); require(pendingStrategy != address(0), "No pendingStrategy"); uint256 _amount = token.balanceOf(address(strategy)); require(_amount > 0, "No balance to migrate"); token.safeTransferFrom(address(strategy), pendingStrategy, _amount); // Remove balance of old strategy token IERC20 oldStrategyToken = IERC20(address(strategy)); oldStrategyToken.safeTransfer(address(strategy), oldStrategyToken.balanceOf(address(this))); address oldStrategy = address(strategy); strategy = IStrategy(pendingStrategy); pendingStrategy = address(0); canSetPendingStrategy = true; unlockTime = 0; // Lock back this function emit MigrateFunds(oldStrategy, address(strategy), _amount); } }
contract DAOVaultMediumUSDC is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; IStrategy public strategy; address public pendingStrategy; bool public canSetPendingStrategy = true; uint256 public unlockTime; uint256 public constant LOCKTIME = 2 days; event MigrateFunds(address indexed fromStrategy, address indexed toStrategy, uint256 amount); constructor(address _token, address _strategy) ERC20("DAO Vault Medium USDC", "dvmUSDC") { _setupDecimals(6); token = IERC20(_token); strategy = IStrategy(_strategy); } /** * @notice Deposit into strategy * @param _amounts A list that contains amounts to deposit * Requirements: * - Only EOA account can call this function */ function deposit(uint256[] memory _amounts) external { require(!address(msg.sender).isContract(), "Only EOA"); uint256 _before = strategy.balanceOf(address(this)); strategy.deposit(_amounts); uint256 _after = strategy.balanceOf(address(this)); _mint(msg.sender, _after.sub(_before)); } /** * @notice Withdraw from strategy * @param _shares A list that contains shares to withdraw * @dev amount _shares = amount daoToken * Requirements: * - Only EOA account can call this function */ function withdraw(uint256[] memory _shares) external { require(!address(msg.sender).isContract(), "Only EOA"); uint256 _before = strategy.balanceOf(address(this)); strategy.withdraw(_shares); uint256 _after = strategy.balanceOf(address(this)); _burn(msg.sender, _before.sub(_after)); } /** * @notice Refund from strategy * @notice This function usually only available when strategy in vesting state * Requirements: * - Only EOA account can call this function * - Amount dvmToken of user must greater than 0 */ function refund() external { require(!address(msg.sender).isContract(), "Only EOA"); uint256 _shares = balanceOf(msg.sender); require(_shares > 0, "No balance to refund"); uint256 _before = strategy.balanceOf(address(this)); strategy.refund(_shares); uint256 _after = strategy.balanceOf(address(this)); _burn(msg.sender, _before.sub(_after)); } /** * @notice Set pending strategy * @param _pendingStrategy Address of pending strategy * Requirements: * - Only owner of this contract call this function * - Pending strategy must be a contract */ function setPendingStrategy(address _pendingStrategy) external onlyOwner { require(canSetPendingStrategy, "Cannot set pending strategy now"); require(_pendingStrategy.isContract(), "New strategy is not contract"); pendingStrategy = _pendingStrategy; } /** * @notice Unlock function migrateFunds() * Requirements: * - Only owner of this contract call this function */ function unlockMigrateFunds() external onlyOwner { unlockTime = block.timestamp + LOCKTIME; canSetPendingStrategy = false; } /** * @notice Migrate all funds from old strategy to new strategy * Requirements: * - Only owner of this contract call this function * - Calling this function within unlock time * - Pending strategy is set */ function migrateFunds() external onlyOwner { require(unlockTime <= block.timestamp && unlockTime + 1 days >= block.timestamp, "Function locked"); require(pendingStrategy != address(0), "No pendingStrategy"); uint256 _amount = token.balanceOf(address(strategy)); require(_amount > 0, "No balance to migrate"); token.safeTransferFrom(address(strategy), pendingStrategy, _amount); // Remove balance of old strategy token IERC20 oldStrategyToken = IERC20(address(strategy)); oldStrategyToken.safeTransfer(address(strategy), oldStrategyToken.balanceOf(address(this))); address oldStrategy = address(strategy); strategy = IStrategy(pendingStrategy); pendingStrategy = address(0); canSetPendingStrategy = true; unlockTime = 0; // Lock back this function emit MigrateFunds(oldStrategy, address(strategy), _amount); } }
43,736
185
// generate a shape pool randomn numbers pool spacing for shapes size of shapes hatched mode bool switchreturn positions of shape /
function _generateBox( bytes32[] memory pool, uint8[2] memory spacing, uint8[4] memory size, bool hatched ) internal pure returns (int256[2] memory positions, int256[2] memory dimensions)
function _generateBox( bytes32[] memory pool, uint8[2] memory spacing, uint8[4] memory size, bool hatched ) internal pure returns (int256[2] memory positions, int256[2] memory dimensions)
23,814
161
// burn all of it's balance Destroy all FAC in this contract
IFatAsset(cash).burn(IERC20(cash).balanceOf(address(this)));
IFatAsset(cash).burn(IERC20(cash).balanceOf(address(this)));
19,770
292
// withdraw `amount` of `ether` from sender's account to sender's address withdraw `amount` of `ether` from msg.sender's account to msg.sender etherAmount Amount of ether to be converted to WETH user User account address /
function withdrawEther(address user, uint256 etherAmount) internal returns (uint256)
function withdrawEther(address user, uint256 etherAmount) internal returns (uint256)
26,119
61
// Returns the owner of the `tokenId` token. Requirements: - `tokenId` must exist. /
function ownerOf(uint256 tokenId) external view returns (address owner);
function ownerOf(uint256 tokenId) external view returns (address owner);
21,574
67
// ERC20 compilant DML token contact instance
DmlToken public dmlToken; mapping (address => WhitelistUser) private whitelisted; address[] private whitelistedIndex;
DmlToken public dmlToken; mapping (address => WhitelistUser) private whitelisted; address[] private whitelistedIndex;
24,112
206
// A mapping from hashes to parameters (use to store a particular configuration on the controller) A contribution fee can be in the organization token or the scheme token or a combination
struct Parameters { uint orgNativeTokenFee; // a fee (in the organization's token) that is to be paid for submitting a contribution bytes32 voteApproveParams; IntVoteInterface intVote; }
struct Parameters { uint orgNativeTokenFee; // a fee (in the organization's token) that is to be paid for submitting a contribution bytes32 voteApproveParams; IntVoteInterface intVote; }
35,359
10
// Check if the token URI is not empty
require(bytes(newTokenURI).length > 0, "Token URI cannot be empty"); for(uint i=0; i<quantity; i++){ _mintToken(recipient, newTokenURI); }
require(bytes(newTokenURI).length > 0, "Token URI cannot be empty"); for(uint i=0; i<quantity; i++){ _mintToken(recipient, newTokenURI); }
7,378
70
// return unstreamed balance to borrower
IERC20(acceptedPayTokenAddress).transfer(_borrower, uint256(_balanceNotStreamed));
IERC20(acceptedPayTokenAddress).transfer(_borrower, uint256(_balanceNotStreamed));
7,549
9
// Price for sale
uint256 public salePrice;
uint256 public salePrice;
9,711
14
// Calculate the fixed token balance given both fixed and variable balances/amountFixed A fixed balance/amountVariable A variable balance/accruedVariableFactorWad An annualised factor in wei-years/termStartTimestampWad When does the period of time begin, in wei-seconds/termEndTimestampWad When does the period of time end, in wei-seconds/ return fixedTokenBalance The fixed token balance for that time period
function getFixedTokenBalance( int256 amountFixed, int256 amountVariable, uint256 accruedVariableFactorWad, uint256 termStartTimestampWad, uint256 termEndTimestampWad
function getFixedTokenBalance( int256 amountFixed, int256 amountVariable, uint256 accruedVariableFactorWad, uint256 termStartTimestampWad, uint256 termEndTimestampWad
3,399
5
// Balancer constants to memoize the target assets and weights from pool
IAsset[] private assets; uint256[] private initialWeights; uint256[] private endWeights;
IAsset[] private assets; uint256[] private initialWeights; uint256[] private endWeights;
39,721
39
// If this special manager already exists
if ( specialManagerAddressNumberMap[ _onSpecialManagerAddress ]>0 ) {
if ( specialManagerAddressNumberMap[ _onSpecialManagerAddress ]>0 ) {
6,547
3
// purges an address from the allowList this is a convenience function, it is equivalent to calling set(_addr, 0) _addr address to be removed /
function remove(address _addr) external onlyOwner { delete map[_addr]; emit Set(_addr, 0); }
function remove(address _addr) external onlyOwner { delete map[_addr]; emit Set(_addr, 0); }
19,542
208
// General call function where the contract execute an arbitrary call with data and ETH following governor orders._data Transaction data._value Transaction value._target Transaction target. /
function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor { _target.call.value(_value)(_data); }
function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor { _target.call.value(_value)(_data); }
49,074
40
// Reduce the max supply of tokens available to mint in the presale _newPresaleMaxSupply The new maximum supply of presale tokens available to mint /
function reducePresaleMaxSupply(uint256 _newPresaleMaxSupply) external onlyOwner
function reducePresaleMaxSupply(uint256 _newPresaleMaxSupply) external onlyOwner
29,142
3
// This user role allows for only managing metadata configuration
uint256 public constant PERMISSION_BIT_METADATA = 2 ** 4;
uint256 public constant PERMISSION_BIT_METADATA = 2 ** 4;
15,209
58
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salt, msg.sender);
key = _deriveKey(salt, msg.sender);
23,019
99
// This method can be used by the controller to extract mistakenly/sent tokens to this contract./_token The address of the token contract that you want to recover/set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); }
function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } ERC20 token = ERC20(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); }
3,071
43
// Transfer the MOMO tokens from the user to the contract
_transfer(msg.sender, address(this), ticketPriceInMOMO); currentTicketID++; tickets[currentTicketID] = Ticket({ owner: msg.sender, lotteryVersion: lotteryVersion });
_transfer(msg.sender, address(this), ticketPriceInMOMO); currentTicketID++; tickets[currentTicketID] = Ticket({ owner: msg.sender, lotteryVersion: lotteryVersion });
35,034
6
// leaf withdraw preview, emulates push value from updated node to leaf leaf - withdrawing leaf /
function nodeWithdrawView(uint48 leaf) public view returns (uint128 withdrawAmount)
function nodeWithdrawView(uint48 leaf) public view returns (uint128 withdrawAmount)
23,105
34
// Let the validator's mining address send their accumulated tx fees to some wallet
return (_sender.balance > 0 ? BASIC : NONE, false);
return (_sender.balance > 0 ? BASIC : NONE, false);
32,797
11
// 0x46daedbb
function disableContract_4166886220() public onlyOwner { isEnable = false; }
function disableContract_4166886220() public onlyOwner { isEnable = false; }
37,122
37
// pause contract preventing further purchase. pausing however has no effect on those who already purchased.
function pause(bool _paused) public onlyOwner { paused = _paused;}
function pause(bool _paused) public onlyOwner { paused = _paused;}
33,541
18
// Transfer in all the Crystals and stake them.
crystals.transferFrom(msg.sender, address(this), tokenId); contractTokenIDs[i] = 4_000_000 + tokenId;
crystals.transferFrom(msg.sender, address(this), tokenId); contractTokenIDs[i] = 4_000_000 + tokenId;
51,961
13
// 交易销毁比例
burnRatio = _transferBurnRatio;
burnRatio = _transferBurnRatio;
35,469
22
// condition 5, the remain airdrop amount is enough
require( hasAirdropAmount + singleAirdropAmount <= totalAirdropAmount, "the remain airdrop amount is not enough" );
require( hasAirdropAmount + singleAirdropAmount <= totalAirdropAmount, "the remain airdrop amount is not enough" );
3,291
20
// fund the airline insurance
function fundAirlineInsurance() external payable requireIsOperational
function fundAirlineInsurance() external payable requireIsOperational
21,440
8
// This is BITX itself (not a complete interface)
interface BITX { function decimals() external view returns(uint8); function stakingRequirement() external view returns(uint256); function balanceOf(address tokenOwner) external view returns(uint); function dividendsOf(address tokenOwner) external view returns(uint); function calculateTokensReceived(uint256 _ethereumToSpend) external view returns(uint256); function calculateEthereumReceived(uint256 _tokensToSell) external view returns(uint256); function myTokens() external view returns(uint256); function myDividends(bool _includeReferralBonus) external view returns(uint256); function totalSupply() external view returns(uint256); function transfer(address to, uint value) external returns(bool); function buy(address referrer) external payable returns(uint256); function sell(uint256 amount) external; function withdraw() external; }
interface BITX { function decimals() external view returns(uint8); function stakingRequirement() external view returns(uint256); function balanceOf(address tokenOwner) external view returns(uint); function dividendsOf(address tokenOwner) external view returns(uint); function calculateTokensReceived(uint256 _ethereumToSpend) external view returns(uint256); function calculateEthereumReceived(uint256 _tokensToSell) external view returns(uint256); function myTokens() external view returns(uint256); function myDividends(bool _includeReferralBonus) external view returns(uint256); function totalSupply() external view returns(uint256); function transfer(address to, uint value) external returns(bool); function buy(address referrer) external payable returns(uint256); function sell(uint256 amount) external; function withdraw() external; }
21,431
38
// Access modifier for CFO-only functionality.
modifier onlyCFO() { require(msg.sender == cfoAddress); _; }
modifier onlyCFO() { require(msg.sender == cfoAddress); _; }
34,556
50
// Protocol governance can set the pricing deal for all new data. /
function setPricing(Pricing pricing) public onlyOwner { prices[prices.length] = pricing; }
function setPricing(Pricing pricing) public onlyOwner { prices[prices.length] = pricing; }
38,656
153
// locks an nft in the shelf/ requires an issued loan
function lock(uint loan) external owner(loan) note { if(address(subscriber) != address(0)) { subscriber.unlockEvent(loan); } NFTLike_2(shelf[loan].registry).transferFrom(msg.sender, address(this), shelf[loan].tokenId); }
function lock(uint loan) external owner(loan) note { if(address(subscriber) != address(0)) { subscriber.unlockEvent(loan); } NFTLike_2(shelf[loan].registry).transferFrom(msg.sender, address(this), shelf[loan].tokenId); }
22,814
18
// Number of times this has been mined. // Amount of pending rewards (merged but not yet transferred). // MintHelper approved rewards (to be claimed in transfer). // Solved solutions (to prevent duplicate rewards). /
constructor(address _miningLeader) public { /* Initialize the mining leader (eg 0xBitcoin). */ miningLeader = ERC918Interface(_miningLeader); /* Initialize the ZeroGold contract. */ // NOTE We hard-code the address here, since it should never change. zeroGold = ERC20Interface(0x6ef5bca539A4A01157af842B4823F54F9f7E9968); }
constructor(address _miningLeader) public { /* Initialize the mining leader (eg 0xBitcoin). */ miningLeader = ERC918Interface(_miningLeader); /* Initialize the ZeroGold contract. */ // NOTE We hard-code the address here, since it should never change. zeroGold = ERC20Interface(0x6ef5bca539A4A01157af842B4823F54F9f7E9968); }
14,174
85
// Require that all auctions have a duration of at least one minute.
require(_duration >= 1 minutes); clockAuctionStorage.addAuction( _tokenId, _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) );
require(_duration >= 1 minutes); clockAuctionStorage.addAuction( _tokenId, _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) );
49,502
0
// TOTAL MAX SUPPLY = 50,000 spolars
uint256 public constant FARMING_POOL_REWARD_ALLOCATION = 41000e18; uint256 public constant COMMUNITY_FUND_POOL_ALLOCATION = 4500e18; uint256 public constant DEV_FUND_POOL_ALLOCATION = 4500e18; uint256 public constant VESTING_DURATION = 300 days; uint256 public startTime; uint256 public endTime; uint256 public communityFundRewardRate; uint256 public devFundRewardRate;
uint256 public constant FARMING_POOL_REWARD_ALLOCATION = 41000e18; uint256 public constant COMMUNITY_FUND_POOL_ALLOCATION = 4500e18; uint256 public constant DEV_FUND_POOL_ALLOCATION = 4500e18; uint256 public constant VESTING_DURATION = 300 days; uint256 public startTime; uint256 public endTime; uint256 public communityFundRewardRate; uint256 public devFundRewardRate;
34,515
47
// end point, after which all tokens will be unlocked
uint256 public lockEndpoint;
uint256 public lockEndpoint;
30,960
51
// paste the wallet adress, that earns the marketingFee here
marketingWallet = 0xe73AfF6b06D5c2c05ee96d0F9F71E702D821d3C9;
marketingWallet = 0xe73AfF6b06D5c2c05ee96d0F9F71E702D821d3C9;
23,120
21
// make sure that the sourceKeyId is not any of the beneficiaries either.
for(uint256 x = 0; x < beneficiaries.length; x++) { require(sourceKeyId != beneficiaries[x], 'SOURCE_IS_DESTINATION'); assert(t.beneficiaries.add(beneficiaries[x])); }
for(uint256 x = 0; x < beneficiaries.length; x++) { require(sourceKeyId != beneficiaries[x], 'SOURCE_IS_DESTINATION'); assert(t.beneficiaries.add(beneficiaries[x])); }
13,879
152
// tokens to return
tokens_to_return = tokens_max.sub(tokens);
tokens_to_return = tokens_max.sub(tokens);
13,010
145
// token type (0: sSYNR, 1: SYNR, 2: SYNR Pass...
uint8 tokenType;
uint8 tokenType;
34,966
32
// ========== CONSTRUCTOR========== //Constructor that initializes the most important configurations./_excessConfirmations minimal required confirmations in case of too many confirmations/_weth wrapped native token contract
function initialize( uint8 _excessConfirmations, IWETH _weth
function initialize( uint8 _excessConfirmations, IWETH _weth
71,804
56
// Internal function for initializing execution limits for some token._token address of the token contract._limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]./
function _setExecutionLimits(address _token, uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); }
function _setExecutionLimits(address _token, uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); }
49,190
16
// don&39;t allow refund if swap did not expire
require(now > s.expiration);
require(now > s.expiration);
46,121
84
// EURt
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256);
function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256);
21,632
117
// Creates `_amount` tokens and assigns them to `_account`, increasingthe total supply.
* Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address _account, uint256 _amount) internal nonReentrant { require(_account != address(0), "Mint to the zero address"); bool isNonRebasingAccount = _isNonRebasingAccount(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); _creditBalances[_account] = _creditBalances[_account].add(creditAmount); // If the account is non rebasing and doesn't have a set creditsPerToken // then set it i.e. this is a mint from a fresh contract if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.add(_amount); } else { rebasingCredits = rebasingCredits.add(creditAmount); } _totalSupply = _totalSupply.add(_amount); require(_totalSupply < MAX_SUPPLY, "Max supply"); emit Transfer(address(0), _account, _amount); }
* Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address _account, uint256 _amount) internal nonReentrant { require(_account != address(0), "Mint to the zero address"); bool isNonRebasingAccount = _isNonRebasingAccount(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); _creditBalances[_account] = _creditBalances[_account].add(creditAmount); // If the account is non rebasing and doesn't have a set creditsPerToken // then set it i.e. this is a mint from a fresh contract if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.add(_amount); } else { rebasingCredits = rebasingCredits.add(creditAmount); } _totalSupply = _totalSupply.add(_amount); require(_totalSupply < MAX_SUPPLY, "Max supply"); emit Transfer(address(0), _account, _amount); }
18,750